TableAjax.php 201 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672
  1. <?php
  2. Lib::loadClass('ViewAjax');
  3. Lib::loadClass('TableAjaxMap');
  4. Lib::loadClass('Typespecial');
  5. Lib::loadClass('SE_Layout');
  6. Lib::loadClass('FoldersConfig');
  7. Lib::loadClass('FileUploader');
  8. Lib::loadClass('UserProfile');
  9. class TableAjax extends ViewAjax {
  10. private $_cnf = '';// Column
  11. private $_htmlID = '';
  12. private $_rowFunctions = array();
  13. private $_pageSize = 10;
  14. private $_pageSizes = array();
  15. private $_filterInit = null;
  16. private $_forceFilterInit = null;
  17. private $_showProcesInit = true;
  18. public function __construct($tblAcl) {
  19. $this->_tbl = $tblAcl->getName();
  20. $this->_acl = $tblAcl;
  21. $this->_zasobID = $tblAcl->getID();
  22. $this->_pageSize = 10;
  23. {
  24. UserProfile::load();
  25. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  26. $this->_pageSize = V::get('pageSize', 10, $tableAjaxSettings, 'int');
  27. }
  28. $this->_pageSizes = array(10, 20, 50, 100);// default page sizes
  29. $this->_filterInit = new stdClass();
  30. $hash = V::get('_hash', '', $_GET);
  31. if ($hash) {
  32. $this->_htmlID = $hash;
  33. $this->_readState();
  34. } else {
  35. $this->_htmlID = $this->generateHtmlID();
  36. $this->_readState();
  37. }
  38. }
  39. public function showProcesInit($bool = true) {
  40. $this->_showProcesInit = $bool;
  41. }
  42. private function _hasStateFilterInit() {
  43. return array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache']) && array_key_exists('_filterInit', $_SESSION['TableAjax_Cache'][$this->_htmlID]);
  44. }
  45. // TODO: read state from cache by key $this->_htmlID
  46. // TODO: load filters and state: table, edit, add, etc.
  47. // TODO: save this data in Workspace 1, 2, 3, etc.
  48. // TODO: default filters in VIEWTABLE_AJAX
  49. // $tbl->setLabel($zasobObj->OPIS);
  50. // $tbl->setFilterInit($filterInit);
  51. // $tbl->addRowFunction('edit');
  52. // $tbl->addRowFunction('hist');
  53. // $tbl->addRowFunction('files');
  54. // $tbl->addRowFunction('cp');
  55. private function _readState() {
  56. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  57. $_SESSION['TableAjax_Cache'] = array();
  58. }
  59. //trigger_error("F." . __FUNCTION__ . " (" . (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) . ")", E_USER_NOTICE);
  60. //trigger_error("F." . __FUNCTION__ . " (".basename($_SERVER['SCRIPT_FILENAME'])."::_filterInit: " . json_encode($_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit']) . ")", E_USER_NOTICE);
  61. if (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  62. foreach ($_SESSION['TableAjax_Cache'][$this->_htmlID] as $k => $v) {
  63. //trigger_error("F." . __FUNCTION__ . " key: ({$k})", E_USER_NOTICE);
  64. switch ($k) {
  65. case '_label':
  66. $this->_label = $v;
  67. break;
  68. case '_filterInit':
  69. $this->_filterInit = $v;
  70. break;
  71. case '_rowFunctions':
  72. $this->_rowFunctions = $v;
  73. break;
  74. default:
  75. }
  76. }
  77. }
  78. }
  79. protected function _saveState($key = null) {
  80. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  81. $_SESSION['TableAjax_Cache'] = array();
  82. }
  83. if (!array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  84. $_SESSION['TableAjax_Cache'][$this->_htmlID] = array();
  85. }
  86. if (!$key) {
  87. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  88. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  89. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  90. } else if ($key == '_label') {
  91. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  92. } else if ($key == '_filterInit') {
  93. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  94. } else if ($key == '_rowFunctions') {
  95. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  96. }
  97. }
  98. public function setPageSizes($pageSizes) {
  99. $this->_pageSizes = $pageSizes;
  100. }
  101. public function setFilterInit($filterInit) {
  102. if ($this->_hasStateFilterInit()) {
  103. return;
  104. }
  105. $this->_filterInit = (object)$filterInit;
  106. $this->_saveState();
  107. }
  108. /**
  109. * @param array $forceFilterInit
  110. */
  111. public function setForceFilterInit($forceFilterInit) {
  112. $this->_forceFilterInit = (object)$forceFilterInit;
  113. }
  114. private function setFilters($filterInit) {
  115. $this->_filterInit = (object)$filterInit;
  116. $this->_saveState();
  117. }
  118. public function addRowFunction($funName, $funParams = array()) {
  119. $defaultRowFunction = array();
  120. //$defaultRowFunction['edit'] = '<a href="#EDIT/{0}" class="glyphicon glyphicon-pencil" title="Edytuj rekord"></a>';
  121. //$defaultRowFunction['hist'] = '<a href="#HIST/{0}" class="glyphicon glyphicon-book" title="Historia"></a>';
  122. //$defaultRowFunction['files'] = '<a href="#FILES/{0}" class="glyphicon glyphicon-folder-open" title="Pliki"></a>';
  123. //$defaultRowFunction['cp'] = '<a href="#" class="glyphicon glyphicon-plus-sign" title="Kopiuj rekord" onclick="return tableAjaxCopy({0});"></a>';
  124. $defaultRowFunction['edit'] = array('href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord');
  125. $defaultRowFunction['hist'] = array('href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia');
  126. $defaultRowFunction['files'] = array('href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki');
  127. $defaultRowFunction['cp'] = array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  128. if (array_key_exists($funName, $defaultRowFunction)) {
  129. $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
  130. }
  131. else {
  132. $this->_rowFunctions[$funName] = $funParams;
  133. }
  134. $this->_saveState('_rowFunctions');
  135. }
  136. private function _parseRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
  137. $rowFunctions = array();
  138. foreach ($this->_rowFunctions as $kFunName => $vParams) {
  139. if (in_array($kFunName, $pomin)) continue;
  140. //$rowFunctionsOut .= str_replace('{0}', $recordID, $vUrl);
  141. $attrs = array();
  142. // $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  143. $label = '';
  144. $ico = '';
  145. foreach ($vParams as $kParamName => $v) {
  146. if ($kParamName == 'ico') {
  147. $ico = '<span class="' . $v . '"></span>';
  148. continue;
  149. }
  150. $attr = $v;
  151. if ($recordID > 0) {
  152. $attr = str_replace('{0}', $recordID, $attr);
  153. }
  154. if ($showLabel && $kParamName == 'title') {
  155. $label = $attr;
  156. }
  157. $attr = $kParamName . '="' . $attr . '"';
  158. $attrs[] = $attr;
  159. }
  160. $rowFunctions[$kFunName] = '<a ' . implode(' ', $attrs) . '>' . "{$ico} {$label} " . '</a>';
  161. }
  162. return $rowFunctions;
  163. }
  164. private function _showRowFunctions($recordID = null, $pomin = array(), $showLabel = false) {
  165. $rowFunctionsOut = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
  166. $rowFunctionsOut = implode('', $rowFunctionsOut);
  167. return $rowFunctionsOut;
  168. }
  169. private function _showRowFunctionsJson($recordID = null, $pomin = array(), $showLabel = false) {
  170. $rowFunctions = $this->_parseRowFunctions($recordID, $pomin, $showLabel);
  171. $rowFunctions = (object)$rowFunctions;
  172. return $rowFunctions;
  173. }
  174. private function _showExportFieldsJson() {
  175. $exportFields = $this->_acl->getExportFieldList();
  176. return $exportFields;
  177. }
  178. private function getProcesInitSelected() {
  179. $userAcl = User::getAcl();
  180. return $userAcl->getPermsFiltrProcesId();
  181. }
  182. public function allowTreeView() {
  183. if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
  184. if ($this->_tbl == 'CRM_PROCES') return true;
  185. return false;
  186. }
  187. public function hasGeomFields() {
  188. $hasGeomFields = false;
  189. $fieldsList = $this->_acl->getFields();
  190. foreach ($fieldsList as $kID => $vCol) {
  191. if ($this->_acl->isGeomField($vCol['name'])) {
  192. if ($this->_acl->hasFieldPerm($kID, 'R')) {
  193. $hasGeomFields = true;
  194. break;
  195. }
  196. }
  197. }
  198. return $hasGeomFields;
  199. }
  200. public function render() {
  201. $hasGeomFlds = $this->hasGeomFields();
  202. $tblAjaxMap = null;
  203. if ($hasGeomFlds) {
  204. $tblAjaxMap = new TableAjaxMap($this->_acl, 512, 400);
  205. }
  206. $hasPermCreate = $this->_acl->hasCreatePerms();
  207. $jsToogleFiltrProcesuFunctionName = 'tableAjaxToggleFiltrProcesInit';
  208. ob_start();
  209. ?>
  210. <div class="container">
  211. <?php SE_Layout::showMessagesForTable($this->_tbl); ?>
  212. </div>
  213. <?php if ($tblAjaxMap) $tblAjaxMap->printCSS(); ?>
  214. <?php if ($tblAjaxMap) $tblAjaxMap->printJS(); ?>
  215. <script src="stuff/jquery-ui-1.10.4.custom.min.js"></script>
  216. <link rel="stylesheet" type="text/css" href="stuff/jquery-ui-smoothness/jquery-ui-1.10.4.custom.min.css">
  217. <style type="text/css">
  218. .AjaxTable{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;}
  219. .AjaxTableCont {position:relative; margin:10px 0; width:100%; overflow-x:auto; border:none;}
  220. .AjaxTable *,
  221. .AjaxTable.table {white-space:nowrap; width:auto;}
  222. .AjaxTable .popover * {white-space:normal;}
  223. .AjaxTable p {margin:0;}
  224. .AjaxTable td, .AjaxTable th {line-height:18px;}
  225. .AjaxTable i {margin: 0 0 0 2px;opacity: 0.5;}
  226. .AjaxTable span.filter {background-color:#999;}
  227. .AjaxTable .indeterminate {opacity: 0.4;-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)";filter:alpha(opacity=40);}
  228. .AjaxTable .columnpicker li, .AjaxTable .actions li {padding-left:5px;}
  229. .AjaxTableCont .btn-toolbar {margin:2px 0 0 0;}
  230. .AjaxTableCont .btn-toolbar .btn-group {vertical-align:top;}
  231. .AjaxTable input[type=checkbox] {margin:0;padding:0;height:13px;}
  232. .AjaxTable input[type=text].filter {margin:0;padding:0 5px;box-shadow:none;width:100%;background:#eee;color:#000;}
  233. .AjaxTable input[type=text].filter {border-width:2px 0;border-color:#eee;border-style:solid;}
  234. .AjaxTable input[type=text].filter-active {border-color:#00ACCC;}
  235. .AjaxTable .date-wrap {width:100%;min-width:115px;}
  236. .AjaxTable .dateWrap .add-on {margin:0;padding:0;background:none;border:none;float:right;cursor:pointer;}
  237. .AjaxTableCont .dropdown-menu {max-height:250px;padding:0 20px 0 0;overflow:auto;}
  238. .AjaxTable .actions a {padding:0;margin:0;}
  239. .AjaxTableCont .text-right {text-align:right}
  240. .AjaxTableCont .breadcrumb em {color:#bbb;}
  241. .AjaxTable-loading .head-info {background:url(./icon/loading.gif) no-repeat left top; background-position:0 6px;}
  242. .AjaxTable-loading .loading-info,
  243. .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block; padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;}
  244. .AjaxTableCont .loading-info {display:none;}
  245. .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block;}
  246. .AjaxTableCont .table {margin-bottom:0px;}
  247. .AjaxTableCont .stickyCol1 a { color:#333; }
  248. .AjaxTableCont .stickyCol1 a:hover { color:#337AB7; text-decoration:none; }
  249. .AjaxTableTaskCnt {padding:0 10px 10px 10px;}
  250. .AjaxTable .tbl-short-txt{max-width:140px; overflow:hidden;}
  251. .AjaxTable .tbl-short-txt span{display:block; height:18px;}
  252. .AjaxTable .tooltip-inner{white-space:normal;}
  253. .AjaxTable thead .sort .ta-ordering {cursor:pointer;}
  254. .AjaxTable thead .sort .ta-ordering span {margin:0 10px 0 0; padding:0; background-repeat:no-repeat; background-position:right top;}
  255. .AjaxTable thead .sort .ta-ordering-down span:after{content:"\e252";font-family:"Glyphicons Halflings";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
  256. .AjaxTable thead .sort .ta-ordering-up span:after{content:"\e253";font-family:"Glyphicons Halflings";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
  257. .AjaxTable thead .sort .ta-ordering {position:relative;}
  258. .AjaxTable thead .sort th .hover-show:hover{background-color:#000; background-image:url(stuff/twitter-bootstrap/img/glyphicons-halflings-white.png);}
  259. .AjaxTable thead .sort th .hover-show{display:none;}
  260. .AjaxTable thead .sort th:hover .hover-show{display:inline;}
  261. .AjaxTable thead .sort .ta-ordering .remove-cell {position:absolute; top:6px; right:2px; display:none; color:#f00;}
  262. .AjaxTable thead .sort .ta-ordering:hover .remove-cell {display:block;}
  263. .AjaxTableCont .pagination { margin:0; }
  264. .AjaxTableCont .pagination a { line-height:16px; }
  265. .AjaxTableCont .AjaxTableEdit-label { display:block; margin:0 0 3px 0; font-size:12px !important; line-height:16px !important; }
  266. .AjaxTableCont .AjaxTableEdit-label code { padding:0; white-space:nowrap; background-color:transparent; border:none; color:#777; font-size:10px !important; line-height:14px !important; }
  267. .AjaxTableCont .AjaxTableEdit .show-last-value .button-appendBack .glyphicon,
  268. .AjaxTableCont .AjaxFrmHorizontalEdit .show-last-value .button-appendBack .glyphicon {display:none;}
  269. .AjaxTableHist em {color:silver;}
  270. .AjaxTableCont .foot * { font-size:12px !important; }
  271. .AjaxTableCont .foot { margin:10px; }
  272. .AjaxTableCont .foot .foot-info { float:left; padding:0 20px; }
  273. .AjaxTableCont .foot .foot-info p { line-height:16px; margin:5px 0; }
  274. .AjaxTable-loading .foot .foot-info {padding-left:20px; background:url(./icon/loading.gif) no-repeat left top;}
  275. .tblAjax__head__specialFilter {margin:0;padding:4px 4px 4px 127px;}
  276. .tblAjax__head__specialFilter .btn-group {margin:0 4px;padding:0;}
  277. .tblAjax__head__specialFilter .btn-group .glyphicon-remove {color:#f00;}
  278. .tblAjax__head__specialFilter .btn-group button.disabled .glyphicon-remove {color:#bbb;}
  279. /* overwrite bootstrap table border */
  280. .AjaxTable, .AjaxTableEdit,
  281. .AjaxTable td, .AjaxTableEdit td,
  282. .AjaxTable th, .AjaxTableEdit th { border-color:#999; }
  283. /* cell A_STATUS */
  284. .AjaxTable .cell-A_STATUS-NORMAL { background:#aeffae; color:#000; text-align:center; }
  285. .AjaxTable .cell-A_STATUS-WAITING { background:#ffd2ff; color:#000; text-align:center; }
  286. .AjaxTable .cell-A_STATUS-MONITOR { background:#cccaff; color:#000; text-align:center; }
  287. .AjaxTable .cell-A_STATUS-WARNING { background:#ffbaba; color:#000; text-align:center; }
  288. .AjaxTable .cell-A_STATUS-DELETED { background:#e0e0e0; color:#808080; text-align:center; }
  289. .AjaxTable .cell-A_STATUS-OFF_SOFT { background:#fce3b7; color:#808080; text-align:center; }
  290. .AjaxTable .cell-A_STATUS-OFF_HARD { background:#eee; color:#808080; text-align:center; }
  291. /* cell Status */
  292. .AjaxTable .cell-Status-U { background:rgb(0,176,80); color:#000; text-align:center; }
  293. .AjaxTable .cell-Status-NU { background:#f00; color:#000; text-align:center; }
  294. .AjaxTable .cell-Status-P { background:rgb(112,48,160); color:#000; text-align:center; }
  295. .AjaxTable .cell-Status-PT { background:rgb(127,127,127); color:#000; text-align:center; }
  296. .AjaxTable .cell-Status-O { background:rgb(0,176,240); color:#000; text-align:center; }
  297. .AjaxTable .cell-Status-DZ { background:rgb(0,112,192); color:#000; text-align:center; }
  298. .AjaxTable .cell-Status-Z {}
  299. /* map */
  300. .AjaxTable .cell-mapfld { cursor:pointer; }
  301. .AjaxTable .cell-mapfld:hover { opacity:1; }
  302. .AjaxTable .cell-mapfld-remove { display:none; }
  303. .AjaxTable .cell-mapfld-hasValue .cell-mapfld-select { color:#f00; }
  304. .AjaxTable .cell-mapfld-hasValue .cell-mapfld-remove { display:inline-block; }
  305. .AjaxTableCont .mapEditor { position:absolute; bottom:0; right:6px; width:512px; height:318px; overflow:hidden; color:#eee; border:1px solid #999; }
  306. .AjaxTableCont .mapEditor-panel { height:16px; padding:0 6px; background:#999; border-bottom:1px solid #eee; }
  307. .AjaxTableCont .mapEditor-panel a { display:block; float:right; padding:0 6px; font-weight:bold; font-size:12px; line-height:16px; color:#fff; }
  308. .AjaxTableCont .mapEditor-panel a:hover { color:#006CD7; text-decoration:none; }
  309. .AjaxTableCont .mapEditor-panel a.mapEditor-panel-close:hover { color:#f00; }
  310. .AjaxTableCont .mapEditor-map { background:#fff; height:400px; }
  311. .AjaxTableCont-mapEditorContainer .mapEditor-map { border:1px solid #999; overflow:hidden; }
  312. /* .mapEditor-btnBackToWindow "olControlSave",overview_replacement */
  313. .olControlEditingToolbar .mapEditor-btnBackToWindowItemInactive,
  314. .olControlEditingToolbar .mapEditor-btnBackToWindowItemActive {
  315. background-image: url(icon/map.window.png);
  316. background-position: 0 0;
  317. background-repeat: no-repeat;
  318. }
  319. /*
  320. .mapEditor-btnBackToWindowItemInactive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
  321. .mapEditor-btnBackToWindowItemActive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
  322. */
  323. .ui-dialog-content .mapEditor-btnBackToWindowItemInactive,
  324. .ui-dialog-content .mapEditor-btnBackToWindowItemActive { display:none; }
  325. .AjaxTableCont .valign-btns-bottom a { vertical-align:text-bottom; font-weight:normal; font-size:12px; line-height:14px; }
  326. .ui-resizable-s { bottom:0; }
  327. .ui-resizable-e { right:0; }
  328. .AjaxTableCont-mapEditorContainer .ui-resizable-s { background-color:#ddd; }
  329. .AjaxTableCont-mapEditorContainer .ui-resizable-s:hover { background-color:#888; }
  330. </style>
  331. <div class="AjaxTableCont">
  332. <ul class="breadcrumb">
  333. <li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>
  334. <!-- TODO: if has perm 'C' then add btn to create new record -->
  335. <?php if ($hasPermCreate) : ?>
  336. <li><a title="Dodaj nowy rekord"
  337. class=""
  338. href="#CREATE"><span class="glyphicon glyphicon-plus"></span> Dodaj nowy rekord</a></li>
  339. <?php endif; ?>
  340. <?php if ($this->_showProcesInit) : ?>
  341. <div class="btn-group pull-right">
  342. <a class="btn btn-xs btn-info dropdown-toggle"
  343. data-toggle="dropdown"
  344. href="#"
  345. title="Uruchom filtr procesu powiązanego z tabelą <?php echo $this->getLabel(); ?>"
  346. onclick="return <?php echo $jsToogleFiltrProcesuFunctionName; ?>(this);">
  347. Filtr procesu <span class="caret"></span>
  348. </a>
  349. <ul class="dropdown-menu pull-left">
  350. <li class="disabled"><a href="#" onclick="return false;"> loading ... </a></li>
  351. </ul>
  352. </div>
  353. <?php endif; ?>
  354. <?php if ($this->_tbl == 'IN7_MK_BAZA_DYSTRYBUCJI') : ?>
  355. <a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=TREEJS&ZASOB_ID={$this->_zasobID}"; ?>"><i class="glyphicon glyphicon-eye-open"></i> Drzewo</a>
  356. <?php elseif ($this->allowTreeView()) : ?>
  357. <a class="pull-right" style="padding:0 20px 0 0;" href="<?php echo "index.php?MENU_INIT=VIEWTREE_AJAX&ZASOB_ID={$this->_zasobID}"; ?>"><i class="glyphicon glyphicon-eye-open"></i> Drzewo</a>
  358. <?php endif; ?>
  359. </ul>
  360. <div id="<?php echo $this->_htmlID; ?>"></div>
  361. </div>
  362. <script>
  363. (function($) {
  364. var TableAjaxGeomField = function() {
  365. var priv = {}; //private api
  366. var publ = {}; //public api
  367. priv.options = {};
  368. var defaults = {
  369. recordID: '',
  370. fieldValue: '',
  371. hasValueClassName: 'TableAjaxGeomField-hasValue',
  372. linkClassNamePrefix: 'TableAjaxGeomField',
  373. linkSelectClassName: 'select',
  374. linkSelectAddClassNames: '', // 'glyphicon glyphicon-map-marker'
  375. linkRemoveClassName: 'remove',
  376. linkRemoveAddClassNames: '', // 'glyphicon glyphicon-remove'
  377. removeUrl: '',
  378. onSelect: null,
  379. onRemove: null,
  380. debug: false
  381. };
  382. priv.init = function() {
  383. priv.render();
  384. };
  385. priv.render = function() {
  386. var state = priv.options;
  387. var cellMapSelect = jQuery('<i title="Pokaż/utwórz obiekt na mapie"></i>');
  388. cellMapSelect.addClass(state.linkClassNamePrefix + '-' + state.linkSelectClassName);
  389. if (state.linkSelectAddClassNames) {
  390. cellMapSelect.addClass(state.linkSelectAddClassNames);
  391. }
  392. cellMapSelect.on('click', {recordID: priv.options.recordID, fieldValue: priv.options.fieldValue}, function(e) {
  393. if (typeof state.onSelect == "function") {
  394. state.onSelect.call(this, e.data.recordID, e.data.fieldValue);
  395. }
  396. });
  397. var cellMapRemove = jQuery('<i title="Usuń obiekt z mapy"></i>');
  398. cellMapRemove.addClass(state.linkClassNamePrefix + '-' + state.linkRemoveClassName);
  399. if (state.linkRemoveAddClassNames) {
  400. cellMapRemove.addClass(state.linkRemoveAddClassNames);
  401. }
  402. cellMapRemove.on('click', {recordID: state.recordID, fieldValue: state.fieldValue}, function(e) {
  403. if (typeof state.onRemove == "function") {
  404. state.onRemove.call(this, publ, e.data.recordID, e.data.fieldValue);
  405. }
  406. });
  407. var node = $(state.id);
  408. node.empty();
  409. node.addClass(state.linkClassNamePrefix);
  410. node.removeClass(state.hasValueClassName);
  411. if (state.fieldValue) {
  412. node.addClass(state.hasValueClassName);
  413. }
  414. node.append(cellMapSelect);
  415. node.append(cellMapRemove);
  416. };
  417. publ.setValue = function(value) {
  418. if (priv.options.debug) console.log('TEST setValue: ', value, 'this', this);
  419. priv.options.fieldValue = value;
  420. priv.render();
  421. };
  422. publ.init = function(options) {
  423. if (priv.options.debug) console.log('TableAjaxGeomField initialization...', options);
  424. //merge supplied options with defaults
  425. $.extend(priv.options, defaults, options);
  426. priv.init();
  427. return publ;
  428. };
  429. return publ;
  430. };
  431. $.fn.TableAjaxGeomFieldSetValue = function(value) {
  432. return this.each(function() {
  433. var tblAjaxMapGeomFld = $(this).data('TableAjaxGeomField');
  434. if (tblAjaxMapGeomFld) {
  435. tblAjaxMapGeomFld.setValue(value);
  436. }
  437. });
  438. return this;
  439. };
  440. $.fn.TableAjaxGeomField = function(options) {
  441. options = options || {};
  442. return this.each(function() {
  443. options.id = this;
  444. if (!$(this).data('TableAjaxGeomField')) {
  445. $(this).data('TableAjaxGeomField', new TableAjaxGeomField().init(options));
  446. }
  447. });
  448. return this;
  449. };
  450. }(jQuery));
  451. (function($, undefined) {
  452. var TableAjax = function () {
  453. var priv = {}; //private api
  454. var publ = {}; //public api
  455. priv.options = {};
  456. var defaults = {
  457. url: '', //webservice url
  458. urlData: '', //webservice params
  459. urlPost: false, //use POST instead of GET
  460. debug: false, //prints debug info to console
  461. filter: false, //show filter row
  462. filterInit: false,// init filters data
  463. forceFilterInit: false,
  464. columnPicker: false, //show columnpicker
  465. checkboxes: false, //show body checkboxes
  466. actions: '', //holds action links
  467. pageSize: 10, //current pagesize
  468. pageSizes: [10, 20, 30, 40, 50, 'All'], //available pagesizes
  469. hidePagerOnEmpty: false, //removes pager if no rows
  470. types: { //type specific options
  471. string: {},
  472. number: {},
  473. bool: {},
  474. date: {}
  475. },
  476. rowFunctions: false,
  477. tblFunctions: false,
  478. specialFilterFunctions: false,
  479. filtersClean: false,
  480. router: false,
  481. longDesc: false,
  482. exportFields: [],
  483. mapEditor: false, // mapEditor visible or not
  484. mapEditorContainer: 'window' // 'window' or 'dock'
  485. };
  486. var _uiNodeCont; // container holding table
  487. var _uiNode$Table; // the table node
  488. var _head; // table header
  489. var _headSort; // table header sorting row
  490. var _headFilter; // table header columns filter row
  491. var _headSpecialFilter; // table header special filter row
  492. var _body; // table body
  493. var _foot; // table footer
  494. var _inlineEditBox; // inline edit box with form
  495. var _popoverCell; // inline popover cell
  496. var _popoverCellCurrent; // inline popover cell
  497. var _popoverCellAjaxXhr;
  498. var _mapEditor; // map editor node
  499. var _mapEditorWrap; // map editor wrapper node
  500. var _mapEditorDialog; // map editor jquery ui dialog node
  501. var _state = {};// state - to replace variables below (date, ...)
  502. var _data; //columns and rows
  503. var _totalPages; // total pages
  504. var _currDpOp; // clicked datetimepicker operator
  505. var _filterFields = {}; // array with filter DOM elements
  506. var _filterTimeout; // timer for delayed filtering
  507. var _uniqueCols = {}; // array with checked rows /// TODO: mv to _state.
  508. var _checkToggleChecked = false; // check-all toggle state
  509. var _exportFieldsSelect = {};
  510. var _tableWidth;
  511. /*
  512. initialize the plugin.
  513. */
  514. priv.init = function () {
  515. _uiNodeCont = priv.options.id;
  516. _state = {};// init state
  517. _state.page = 1;
  518. _state.specialFilters = {};
  519. _state.filters = {};
  520. _state.filters.currSortCol = '';
  521. _state.filters.currSortFlip = false;
  522. _state.filters.filterCols = {};
  523. priv.initEvents();
  524. priv.initialRender();// set up _uiNode$...
  525. priv.options.types.string = ((priv.options.types || {}).string || {});
  526. priv.options.types.number = ((priv.options.types || {}).number || {});
  527. priv.options.types.bool = ((priv.options.types || {}).bool || {});
  528. priv.options.types.date = ((priv.options.types || {}).date || {});
  529. if (priv.options.mapEditorContainer != 'dock'
  530. && priv.options.mapEditorContainer != 'window') {
  531. priv.options.mapEditorContainer = 'window';
  532. }
  533. if (priv.options.filterInit) {
  534. priv.setStateFilters(priv.options.filterInit);
  535. }
  536. $.each(priv.options.exportFields, function(ind, col) {
  537. _exportFieldsSelect[col] = true;
  538. });
  539. //try call webservice for data
  540. priv.update(priv.options.router);
  541. if (typeof priv.options.router == "function") {
  542. $(window).bind('hashchange', function() {
  543. priv.options.router.apply(this);
  544. });
  545. }
  546. };
  547. priv.initEvents = function () {
  548. jQuery(_uiNodeCont).on('TableAjax:render', priv.onRender);
  549. };
  550. priv.onRender = function(e) {
  551. if (priv.options.debug) console.log('onRender.arguments:', arguments.length, arguments, 'e:', e);
  552. if (arguments.length > 1) {
  553. for (var i=1; i<arguments.length; i++) {
  554. switch (arguments[i]) {
  555. case 'head': _head = undefined; break;
  556. case 'body': _body = undefined; break;
  557. case 'foot': _foot = undefined; break;
  558. case 'foot_pagination': {
  559. priv.renderFooterInfo();
  560. priv.renderFooterPagination();
  561. priv.renderFooterPageSizes();
  562. }
  563. break;
  564. case 'footer__toolbar__info': priv.renderFooterInfo(); break;
  565. case 'footer__toolbar__pagination': priv.renderFooterPagination(); break;
  566. case 'footer__toolbar__pagesizes': priv.renderFooterPageSizes(); break;
  567. case 'foot__columnPicker': priv.renderFooterColumnPicker(); break;
  568. case 'head__specialFilters': priv.renderHeadSpecialFilters(); break;
  569. }
  570. }
  571. priv.renderTable();
  572. }
  573. };
  574. priv.initialRender = function () {
  575. _uiNode$Table = $('<table class="AjaxTable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_uiNodeCont);
  576. _head = $('<thead></thead>').prependTo(_uiNode$Table);
  577. _headSort = $('<tr class="sort tblAjax__head__sort"></tr>').prependTo(_head);
  578. _headFilter = $('<tr class="filter tblAjax__head__filter"></tr>').appendTo(_head);
  579. _body = $('<tbody></tbody>').insertAfter(_head);
  580. $('<tfoot></tfoot>').insertAfter(_body);
  581. _foot = $('<div class="foot tblAjax__footer"></div>').insertAfter(_uiNodeCont);
  582. var footToolbar = $('<div class="btn-toolbar tblAjax__footer__toolbar"></div>').appendTo(_foot);
  583. $('<span class="tblAjax__footer__toolbar__info"></span>').appendTo(footToolbar);
  584. $('<span class="tblAjax__footer__toolbar__pagination"></span>').appendTo(footToolbar);
  585. $('<span class="tblAjax__footer__toolbar__pagesizes"></span>').appendTo(footToolbar);
  586. $('<span class="tblAjax__footer__toolbar__columnPicker"></span>').appendTo(footToolbar);
  587. $('<span class="tblAjax__footer__toolbar__functions"></span>').appendTo(footToolbar);
  588. $('<span class="tblAjax__footer__toolbar__export"></span>').appendTo(footToolbar);
  589. _mapEditorWrap = $('<div class="mapEditor" style="display:none"></div>').insertAfter(_foot);
  590. _mapEditor = $('<div class="mapEditor-map"></div>').appendTo(_mapEditorWrap);
  591. _popoverCell = $('<div class="popoverCell" style="display:none"></div>').insertAfter(_foot);
  592. $('<div class="tblAjax__inlineEditBox"></div>').insertAfter(_foot);
  593. $('<div class="btn-toolbar tblAjax__head__specialFilter"></div>').insertBefore(_uiNodeCont);
  594. priv.renderInlineEditBox();// .tblAjax__inlineEditBox
  595. _foot = _head = _body = _headSort = _headFilter = undefined;// TODO: refactor
  596. /// console.log('L.<?php echo __LINE__; ?> priv.initialRender, _uiNode$Table: ', _uiNode$Table.html())
  597. }
  598. /*
  599. creates the table with all its parts and handlers.
  600. note that only the parts we need is created.
  601. (yeah, the function is huge)
  602. */
  603. priv.renderTable = function () {
  604. //create table itself
  605. /// console.log('renderTable:: _data', _data);//TODO:DBG:RMME
  606. /// console.log('renderTable:: _uiNode$Table', _uiNode$Table);//TODO:DBG:RMME
  607. //create the header which will later hold both sorting and filtering
  608. /// console.log('L.<?php echo __LINE__; ?> renderTable:: _head', _head);//TODO:DBG:RMME
  609. if (!_head) {
  610. _headSort = _headFilter = _headSpecialFilter = undefined;
  611. //_head = $('<thead></thead>');
  612. // $('<tr class="sort"></tr>').prependTo(_head);
  613. //_uiNode$Table.find('thead').replaceWith(_head);
  614. _head = _uiNode$Table.find('thead');
  615. }
  616. //create the header sorting row
  617. if (!_headSort) {
  618. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadSort...');//TODO:DBG:RMME
  619. priv.renderTableTheadSort();
  620. }
  621. //create the header filtering row
  622. if (!_headFilter && priv.options.filter) {
  623. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadFilter...');//TODO:DBG:RMME
  624. priv.renderTableTheadFilter();
  625. _headFilter = true;
  626. }
  627. //create the header special filters row
  628. if (!_headSpecialFilter && priv.options.specialFilterFunctions) {
  629. priv.renderHeadSpecialFilters();
  630. _headSpecialFilter = true;
  631. }
  632. //create the body
  633. if (!_body) {
  634. _uiNode$Table.find('tbody').remove();
  635. _body = $('<tbody></tbody>').insertAfter(_head);
  636. //_body.on('change', '.unique', priv.rowChecked);
  637. //find out what rows to show next...
  638. var rowsAdded = 0;
  639. //slice out the chunk of data we need and create rows
  640. $.each(_data.rows, function (index, props) {
  641. var row = $('<tr></tr>').appendTo(_body);
  642. if (priv.options.rowFunctions || priv.options.filtersClean) {
  643. var cell = $('<td class="text-right stickyCol1"></td>').appendTo(row);
  644. var cellID = _state.uniqueCol || 'ID';
  645. cellID = (cellID in props)? props[cellID] : null;
  646. $.map(priv.options.rowFunctions, function(funObj, funName){
  647. $(funObj.f(cellID)).appendTo(cell);
  648. });
  649. }
  650. //create checkbox
  651. if (_state.uniqueCol && priv.options.checkboxes) {
  652. var check = _uniqueCols[props[_state.uniqueCol]] != undefined ? 'checked' : '';
  653. var checkable = props['checkable'] === false ? 'disabled' : '';
  654. var cell = $('<td></td>').appendTo(row);
  655. $('<input class="unique" {0} {1} type="checkbox" />'.f(check, checkable)).appendTo(cell);
  656. }
  657. //create cells
  658. var primaryKeyField = '';
  659. for (var i = 0; i < _state.colsSorted.length; i++) {
  660. var key = _state.colsSorted[i];
  661. var val = props[key];
  662. if (!_data.cols[key]) return;
  663. if (_data.cols[key].unique) row.data('unique', val);
  664. primaryKeyField = _state.uniqueCol || 'ID';
  665. cellID = (primaryKeyField in props)? props[primaryKeyField] : null;
  666. if (!_data.cols[key].hidden) {
  667. var cell = $('<td></td>').appendTo(row);
  668. if (key !== primaryKeyField) {
  669. cell.on('dblclick', {id:cellID, col:key}, priv.rowDblClicked);
  670. }
  671. var cellCnt;
  672. if (i == 1) {// primaryKey(ID)
  673. cellCnt = $('<div></div>').appendTo(cell);// fix dblclick for copy
  674. cell.addClass('stickyCol2');
  675. } else {
  676. cellCnt = $('<span></span>').appendTo(cell);
  677. }
  678. cell.data('column', key);
  679. if (val === undefined) continue;
  680. var format = props[key + 'Format'] || _data.cols[key].format || '{0}';
  681. var showTooltip = true;
  682. switch (_data.cols[key].type) {
  683. case "string":
  684. cellCnt.html(format.f(val));
  685. break;
  686. case "number":
  687. val = Number(val);
  688. var forceDecimals = !isNaN(_data.cols[key].decimals);
  689. if (forceDecimals) cellCnt.html(format.f(val.toFixed(_data.cols[key].decimals)));
  690. else {
  691. (val || 0) % 1 === 0
  692. ? cellCnt.html(format.f(val))
  693. : cellCnt.html(format.f(val.toFixed(priv.options.types.number.decimals || 2)));
  694. }
  695. break;
  696. case "date":
  697. cellCnt.html(format.f(val));
  698. break;
  699. case "bool":
  700. $('<input type="checkbox" {0} disabled />'.f(val ? "checked" : "")).appendTo(cellCnt);
  701. break;
  702. case "special":
  703. cellCnt.html(format.f(val));
  704. break;
  705. case "simpleLink":
  706. var valLink = String(val);
  707. if (undefined !== _data.cols[key]._tsRetId
  708. && (0 === _data.cols[key]._tsRetId || '0' === _data.cols[key]._tsRetId)
  709. && undefined !== _data.cols[key]._tsSimpleLink) {
  710. valLink = _data.cols[key]._tsSimpleLink.format;
  711. $.each(_data.cols[key]._tsSimpleLink.aliasMap, function (i, v) {
  712. //console.log('simpleLink aliasMap key:', key, 'i:', i, 'v:', v, 'props['+v+']', props[v], 'val', val, 'typeof val', typeof val);
  713. if (undefined !== props[v]) {
  714. valLink = valLink.replace(new RegExp('\{' + i + '\}', 'g'), props[v]);
  715. }
  716. });
  717. }
  718. cellCnt.html(format.f(valLink));
  719. break;
  720. case "geom":
  721. cellCnt.TableAjaxGeomField({
  722. recordID: cellID,
  723. fieldValue: val,
  724. hasValueClassName: 'cell-mapfld-hasValue',
  725. //removeUrl: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + cellID,
  726. linkClassNamePrefix: 'cell-mapfld',
  727. linkSelectClassName: 'select',
  728. linkSelectAddClassNames: 'glyphicon glyphicon-map-marker',
  729. linkRemoveClassName: 'remove',
  730. linkRemoveAddClassNames: 'glyphicon glyphicon-remove',
  731. onSelect: function(recordID, geomShape) {
  732. if (priv.options.debug) console.log('recordID:', recordID, 'geomShape:', geomShape);
  733. priv.mapEditorShow();
  734. _mapEditor.TableAjaxMapSelectRecord(recordID, geomShape);
  735. },
  736. onRemove: function(geomField, recordID, geomShape) {
  737. if (confirm('Czy usunąć obiekt z mapy dla rekordu ' + recordID + '?')) {
  738. if (!recordID) return;
  739. var selectedRecordId = recordID;
  740. function notifyAjaxCallback(data) {
  741. var notify = {};
  742. notify.type = (data && data.type)? data.type : '';
  743. notify.msg = (data && data.msg)? data.msg : '';
  744. switch (notify.type) {
  745. case 'success':
  746. if (!notify.msg) notify.msg = 'Usunięto obiekt z mapy dla rekordu ' + selectedRecordId;
  747. break;
  748. case 'info':
  749. if (!notify.msg) notify.msg = 'Rekord nie był powiązany z żadnym obiektem na mapie';
  750. break;
  751. case 'error':
  752. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  753. break;
  754. case 'warning':
  755. notify.type = 'warn';
  756. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  757. break;
  758. default:
  759. notify.msg = 'Nieznany błąd';
  760. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  761. notify.type = '';
  762. }
  763. jQuery.notify(notify.msg, notify.type);
  764. }
  765. $.ajax({
  766. data: {},
  767. dataType: 'json',
  768. type: "POST",
  769. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_REMOVE&ID=' + recordID
  770. })
  771. .done(function(data, textStatus, jqXHR){
  772. notifyAjaxCallback(data);
  773. if (priv.options.debug) console.log('data.record.the_geom:', data.record.the_geom);
  774. if (data && data.record && data.record.the_geom) {
  775. if (priv.options.debug) console.log('data.record.the_geom:2:', data.record.the_geom);
  776. geomField.setValue(data.record.the_geom);
  777. }
  778. else if (data && data.record) {
  779. if (priv.options.debug) console.log('data.record.the_geom:2:', data.record.the_geom);
  780. geomField.setValue(data.record.the_geom);
  781. }
  782. _mapEditor.TableAjaxMapRefresh();
  783. })
  784. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  785. if (jqXHR.responseJSON) {
  786. notifyAjaxCallback(jqXHR.responseJSON);
  787. }
  788. else {
  789. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  790. if (jqXHR.status == 404) {
  791. jQuery.notify(jqXHR.responseText, 'error');
  792. } else {
  793. jQuery.notify(jqXHR.responseText, 'warn');
  794. }
  795. }
  796. });
  797. }
  798. }
  799. });
  800. break;
  801. }
  802. if (_data.cols[key]._tsRetId) {
  803. showTooltip = false;
  804. if (_data.cols[key]._tsRetId > 0) {
  805. cellCnt.on('click', {id:cellID, col:key, friendly:_data.cols[key].friendly, value:format.f(val)}, priv.popoverCell);
  806. }
  807. }
  808. if (i > 1 && priv.options.longDesc) {
  809. cell.addClass('tbl-short-txt');
  810. if (showTooltip) {
  811. cellCnt.tooltip({title: cellCnt.text(), placement: 'left'});
  812. }
  813. }
  814. }
  815. }
  816. rowsAdded++;
  817. //enough rows created?
  818. if (rowsAdded >= priv.options.pageSize) {
  819. return false;
  820. }
  821. });
  822. if (_state.page == 1) {
  823. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  824. }
  825. //pad with empty rows if we're at last page.
  826. if (_state.page == _totalPages) {
  827. while (rowsAdded < priv.options.pageSize) {
  828. var rowNode = priv.renderRowEmptyNode();
  829. if (rowNode) rowNode.appendTo(_body);
  830. rowsAdded++;
  831. }
  832. }
  833. }
  834. //create the footer
  835. if (!_foot) {
  836. priv.renderTableTfoot();
  837. priv.renderFooter();
  838. }
  839. _foot = $(_uiNodeCont).next('.foot');
  840. var stickyCol1Width = (12 + 3) * 4 + 2 * 5 + 1;
  841. var stickyCol2Width = 50 + 2 * 5 + 1;
  842. if (undefined === _tableWidth) {
  843. _tableWidth = true;
  844. var contW = jQuery(_uiNodeCont).width();
  845. var th1 = _uiNode$Table.find('.stickyCol1:first');
  846. var th2 = th1.next();
  847. var th1W = th1.innerWidth();
  848. var th2W = 50 + 2 * 5;//th2.innerWidth();
  849. var colsW = stickyCol1Width + stickyCol2Width;
  850. jQuery(_uiNodeCont).css({width:'' + (contW - colsW) + 'px', marginLeft:'' + colsW + 'px', overflowX:'scroll', overflowY:'visible', paddingBottom:'1px'});
  851. }
  852. _uiNode$Table.find('.stickyCol1').css({position:'absolute',
  853. left:'0',
  854. top:'auto',
  855. width:'' + stickyCol1Width + 'px',
  856. });
  857. //_uiNode$Table.find('.filter').find('.stickyCol1').css({height:'34px'});
  858. var sortStickyColHeight = _uiNode$Table.find('.sort').find('th:last').outerHeight();
  859. _uiNode$Table.find('.sort').find('.stickyCol1').css({height: sortStickyColHeight + 'px'});
  860. _uiNode$Table.find('.sort').find('.stickyCol2').css({height: sortStickyColHeight + 'px'});
  861. _uiNode$Table.find('.stickyCol2').css({position:'absolute',
  862. left:'' + (stickyCol1Width) + 'px',
  863. top:'auto',
  864. width:'' + stickyCol2Width + 'px',
  865. borderRight: '1px solid silver'
  866. });
  867. if (_data.total == 0 && priv.options.hidePagerOnEmpty) {
  868. $('.btn-toolbar', _foot).remove();
  869. }
  870. if (priv.options.debug) console.log('table created L.<?php echo __LINE__; ?>');
  871. if (typeof priv.options.tableCreated == 'function') {
  872. priv.options.tableCreated.call(_uiNode$Table.get(0), {table: _uiNode$Table.get(0)});
  873. }
  874. };
  875. priv.renderRowEmptyNode = function() {
  876. var row = $('<tr></tr>');
  877. if (_state.uniqueCol && priv.options.checkboxes) {
  878. var cell = $('<td></td>').appendTo(row);
  879. $('<input disabled type="checkbox" />').appendTo(cell);
  880. }
  881. if (priv.options.rowFunctions || priv.options.filtersClean) {
  882. $('<td class="text-right stickyCol1">&nbsp;</td>').appendTo(row);
  883. }
  884. for (var i = 0; i < _state.colsSorted.length; i++) {
  885. var key = _state.colsSorted[i];
  886. if (!_data.cols[key]) return;
  887. var props = _data.cols[key];
  888. if (props.hidden) continue;
  889. if (i == 1) {
  890. $('<td class="stickyCol2">&nbsp;</td>').appendTo(row);
  891. } else {
  892. $('<td>&nbsp;</td>').appendTo(row);
  893. }
  894. }
  895. return row;
  896. };
  897. priv.renderTableTheadSort = function() {
  898. var nodeClass = 'tblAjax__' + 'head__sort',
  899. currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
  900. node;
  901. // currentNode.find('i').tooltip('hide');
  902. node = $('<tr class="sort ' + nodeClass + '"></tr>');
  903. //create the functions column
  904. if (priv.options.rowFunctions || priv.options.filtersClean) {
  905. var headCell = $('<th class="text-right head-info stickyCol1"></th>').appendTo(node);
  906. $.map(priv.options.tblFunctions, function(funObj, funName){
  907. var funHtml = $('<a></a>');
  908. funHtml.attr('href', funObj.href || '#');
  909. if (funObj.title) funHtml.attr('title', funObj.title);
  910. if (funObj.icon) funHtml.html('<span class="glyphicon glyphicon-' + funObj.icon + '"></span> ');
  911. if (funObj.method && priv[funObj.method] && typeof priv[funObj.method] == 'function') {
  912. funHtml.on('click', priv[funObj.method]);
  913. }
  914. funHtml.appendTo(headCell);
  915. });
  916. }
  917. //create the checkall toggle
  918. if (_state.uniqueCol && priv.options.checkboxes) {
  919. var checked = _checkToggleChecked ? 'checked' : '';
  920. var headCell = $('<th></th>').appendTo(node);
  921. var elem = $('<input {0} class="checkToggle" type="checkbox" />'.f(checked)).appendTo(headCell);
  922. elem.on('change', priv.checkToggleChanged);
  923. }
  924. //create the sortable headers
  925. for (var i = 0; i < _state.colsSorted.length; i++) {
  926. var column = _state.colsSorted[i];
  927. var props = _data.cols[column];
  928. if (!props.hidden) {
  929. var headCell = $('<th class="ta-ordering"></th>').appendTo(node);
  930. if (i == 1) headCell.addClass('stickyCol2');
  931. if (false) {// TODO: old way
  932. var link = $('<a class="pull-left" href="#">{0}</a>'.f(props.friendly || column));
  933. link.on('click', {column: column}, priv.columnClicked).appendTo(headCell);
  934. if (props.tooltip) {
  935. $('<i class="glyphicon glyphicon-info-sign"></i>').tooltip({
  936. title: props.tooltip.trim(),
  937. html: true,
  938. container: 'body',
  939. placement: "top",
  940. delay: {
  941. show: 500,
  942. hide: 100
  943. }
  944. }).appendTo(link);
  945. }
  946. //Add sort arrow
  947. if (column == _state.filters.currSortCol) {
  948. if (_state.filters.currSortFlip) $('<i class="glyphicon glyphicon-chevron-down pull-right"></i>').appendTo(headCell);
  949. else $('<i class="glyphicon glyphicon-chevron-up pull-right"></i>').appendTo(headCell);
  950. }
  951. //Add hide btn
  952. if (column != 'ID') {
  953. var hideColBtn = $('<i class="glyphicon glyphicon-remove pull-right hover-show"></i>');
  954. hideColBtn.on('click', {column: column}, priv.columnHideClicked);
  955. hideColBtn.appendTo(headCell);
  956. }
  957. }
  958. if (props.type != 'special' && props.type != 'geom') {
  959. headCell.on('click', {column: column}, priv.columnClicked);
  960. }
  961. var colTitle = column;
  962. if (props.description && props.description.length > 0) {
  963. colTitle = props.description;
  964. colTitle += ' (' + column + ')';
  965. }
  966. else if (props._tsRetId > 0) {
  967. colTitle = 'Kliknij na pole i przejdź do powiązanych rekordów (' + colTitle + ')';
  968. }
  969. if (props.friendly) {
  970. var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(props.friendly, colTitle));
  971. } else {
  972. var headCnt = $('<span class="pull-left" title="{1}">{0}</span>'.f(column, colTitle));
  973. }
  974. headCnt.appendTo(headCell);
  975. //Add sort arrow
  976. if (column == _state.filters.currSortCol) {
  977. if (_state.filters.currSortFlip) headCell.addClass('ta-ordering-down');
  978. else headCell.addClass('ta-ordering-up');
  979. }
  980. if (column != 'ID') {
  981. var hideColBtn = $('<i class="glyphicon glyphicon-remove remove-cell"></i>');
  982. hideColBtn.on('click', {column: column}, priv.columnHideClicked);
  983. hideColBtn.appendTo(headCell);
  984. }
  985. }
  986. }
  987. currentNode.replaceWith(node);
  988. };
  989. priv.renderHeadSpecialFilters = function() {
  990. var nodeClass = 'tblAjax__' + 'head__specialFilter',
  991. currentNode = $(_uiNodeCont).prev('.' + nodeClass),
  992. node;
  993. /// console.log('L.<?php echo __LINE__; ?> renderTable::renderTableTheadFilter...');//TODO:DBG:RMME
  994. if (!priv.options.specialFilterFunctions) {
  995. return;
  996. }
  997. var node = $('<div class="btn-toolbar tblAjax__head__specialFilter"></div>');
  998. $.map(priv.options.specialFilterFunctions, function(groupObj, groupName) {
  999. var btnHtml, btnSelected, groupHtml = $('<div class="btn-group"></div>');
  1000. // _state.specialFilters[e.data.group] = e.data.value;
  1001. if (groupName in _state.specialFilters) {
  1002. btnSelected = _state.specialFilters[groupName];
  1003. }
  1004. if (groupObj.icon) {
  1005. $('<button class="btn btn-xs btn-default" title="' + groupName + '"><i class="' + groupObj.icon + '"></i></button>').appendTo(groupHtml);
  1006. }
  1007. $.map(groupObj.btns, function(btnObj, btnName) {
  1008. btnHtml = $('<button class="btn btn-xs btn-default' + ((btnSelected && btnSelected == btnObj.value)? ' active' : '') + '">' + btnName + '</button>').appendTo(groupHtml);
  1009. btnHtml.on('click', {group: groupName, value: btnObj.value}, priv.specialFilterChanged);
  1010. });
  1011. btnHtml = $('<button class="btn btn-xs btn-default' + ((!btnSelected)? ' disabled' : '') + '" title="Kasuj filtr"><i class="glyphicon glyphicon-remove"></i></button>').appendTo(groupHtml);
  1012. btnHtml.on('click', {group: groupName, value: ''}, priv.specialFilterChanged);
  1013. groupHtml.appendTo(node);
  1014. });
  1015. currentNode.replaceWith(node);
  1016. };
  1017. priv.renderTableTheadFilter = function() {
  1018. var nodeClass = 'tblAjax__' + 'head__filter',
  1019. currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
  1020. node;
  1021. // currentNode.find('i').tooltip('hide');
  1022. node = $('<tr class="filter ' + nodeClass + '"></tr>');
  1023. //_head.find(".filter").remove();
  1024. //_headFilter = $('<tr class="filter"></tr>').appendTo(_head);
  1025. var headCell;
  1026. var elem;
  1027. var placeHolder = '';
  1028. var tooltip = '';
  1029. //create the functions column
  1030. if (priv.options.rowFunctions || priv.options.filtersClean) {
  1031. var headCell = $('<th class="text-right stickyCol1"></th>').appendTo(node);
  1032. headCell.css({padding: '0'});
  1033. if (priv.options.filtersClean) {
  1034. var elem = $('<button title="Kasuj filtry" class="btn btn-xs btn-link glyphicon glyphicon-remove"></button>').appendTo(headCell);
  1035. elem.on('click', priv.filtersClean);
  1036. }
  1037. }
  1038. //create the filter checkbox
  1039. if (_state.uniqueCol && priv.options.checkboxes) {
  1040. tooltip = priv.options.types.bool.filterTooltip || 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked';
  1041. headCell = $('<th></th>').appendTo(node);
  1042. elem = $('<input class="filter indeterminate" checked type="checkbox" />').appendTo(headCell);
  1043. $.map(_state.filters.filterCols, function (colProps, col) {
  1044. if (col == "unique") {
  1045. if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
  1046. else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
  1047. else if (colProps.filter == '') elem.addClass('indeterminate');
  1048. }
  1049. });
  1050. if (tooltip) {
  1051. elem.tooltip({
  1052. title: tooltip.trim(),
  1053. html: true,
  1054. container: 'body',
  1055. trigger: 'hover',
  1056. placement: 'top',
  1057. delay: {
  1058. show: 500,
  1059. hide: 100
  1060. }
  1061. });
  1062. }
  1063. elem.on('click', {column: "unique"}, priv.filterChanged);
  1064. }
  1065. //create the column filters
  1066. for (var i = 0; i < _state.colsSorted.length; i++) {
  1067. var column = _state.colsSorted[i];
  1068. var props = _data.cols[column];
  1069. tooltip = props.filterTooltip === true ? undefined : props.filterTooltip === false ? '' : props.filterTooltip;
  1070. placeHolder = props.placeHolder === true ? undefined : props.placeHolder === false ? '' : props.placeHolder;
  1071. if (!props.hidden) {
  1072. headCell = $('<th></th>').appendTo(node);
  1073. headCell.css({padding: '0'});
  1074. if (i == 1) headCell.addClass('stickyCol2');
  1075. // @mark MarkTableAjaxFilterColType
  1076. switch (props.type || 'string') {
  1077. case "number":
  1078. if (placeHolder == undefined) placeHolder = priv.options.types.number.placeHolder;
  1079. placeHolder = (placeHolder === true || placeHolder == undefined) ? '10..20 =50' : placeHolder === false ? '' : placeHolder;
  1080. if (tooltip == undefined) tooltip = priv.options.types.number.filterTooltip;
  1081. tooltip = (tooltip === true || tooltip == undefined) ? 'Values 10 to 20:<br/>10..20<br/>Values exactly 50:<br/>=50' : tooltip === false ? '' : tooltip;
  1082. elem = $('<input placeholder="{0}" class="filter" type="text" />'.f(placeHolder));
  1083. elem.on('keyup', {column: column}, priv.filterChanged);
  1084. break;
  1085. case "date":
  1086. if (placeHolder == undefined) placeHolder = priv.options.types.date.placeHolder;
  1087. placeHolder = (placeHolder === true || placeHolder == undefined) ? '-7..0' : placeHolder === false ? '' : placeHolder;
  1088. if (tooltip == undefined) tooltip = priv.options.types.date.filterTooltip;
  1089. tooltip = (tooltip === true || tooltip == undefined) ? 'Today:<br/>0..1<br/>A week today excluded:<br/>-7..0' : tooltip === false ? '' : tooltip;
  1090. elem = $('<div><input placeholder="{0}" class="filter" type="text" /></div>'.f(placeHolder));
  1091. if (priv.options.types.date.datePicker === true || priv.options.types.date.datePicker == undefined)
  1092. {
  1093. if ($().datepicker)
  1094. {
  1095. elem.addClass('date-wrap');
  1096. var today = 0;//new priv.ext.XDate(false).setHours(0, 0, 0, 0).toString('yyyy-MM-dd');
  1097. var dp = $('<div style="float:right" class="date" data-date="{0}" data-date-format="{1}" />'.f(today, 'yyyy-mm-dd')).appendTo(elem);
  1098. $('<input style="display:none" type="text" />').appendTo(dp);
  1099. $('<span class="add-on"><i class="glyphicon glyphicon-chevron-right"></i></span>').on('click', {op: "l"}, priv.dpOpChanged).appendTo(dp);
  1100. $('<span class="add-on"><i class="glyphicon glyphicon-chevron-left"></i></span>').on('click', {op: "r"}, priv.dpOpChanged).appendTo(dp);
  1101. dp.datepicker({weekStart:1});
  1102. dp.on('changeDate', {column: column, input: $('input.filter', elem)}, priv.dpClicked);
  1103. }
  1104. else
  1105. if (priv.options.debug) console.log('datepicker plugin not found');
  1106. }
  1107. elem.on('keyup', 'input.filter', {column: column}, priv.filterChanged);
  1108. break;
  1109. case "bool":
  1110. if (tooltip == undefined) tooltip = priv.options.types.bool.filterTooltip;
  1111. tooltip = (tooltip === true || tooltip == undefined) ? 'Toggle between:<br/>indeterminate,<br/>checked,<br/>unchecked' : tooltip === false ? '' : tooltip;
  1112. elem = $('<input class="filter indeterminate" checked type="checkbox" />');
  1113. elem.on('click', {column: column}, priv.filterChanged);
  1114. break;
  1115. case "string":
  1116. if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
  1117. placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
  1118. if (tooltip == undefined) tooltip = priv.options.types.string.filterTooltip;
  1119. tooltip = (tooltip === true || tooltip == undefined) ? 'Find str: str<br/>Find all but str: !str<br/>Find str inside: %str%' : tooltip === false ? '' : tooltip;
  1120. elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
  1121. elem.on('keyup', {column: column}, priv.filterChanged);
  1122. break;
  1123. case "special":
  1124. elem = $('<div>&nbsp;</div>');
  1125. break;
  1126. case "simpleLink":
  1127. elem = $('<div>&nbsp;</div>');
  1128. break;
  1129. case "geom":
  1130. if (placeHolder == undefined) placeHolder = priv.options.types.string.placeHolder;
  1131. placeHolder = (placeHolder === true || placeHolder == undefined) ? '%' : placeHolder === false ? '' : placeHolder;
  1132. elem = $('<input placeholder="{0}" class="filter" type="text" size="8" />'.f(placeHolder));
  1133. elem.on('keyup', {column: column}, priv.filterChanged);
  1134. break;
  1135. case "none":
  1136. elem = $('<div>&nbsp;</div>');
  1137. break;
  1138. }
  1139. if (false) {// tooltip OFF - (tooltip)
  1140. elem.tooltip({
  1141. title: tooltip.trim(),
  1142. html: true,
  1143. container: 'body',
  1144. trigger: 'focus',
  1145. placement: 'top',
  1146. delay: {
  1147. show: 500,
  1148. hide: 100
  1149. }
  1150. });
  1151. }
  1152. if (elem && props.filter) {
  1153. $.map(_state.filters.filterCols, function (colProps, col) {
  1154. if (col == column) {
  1155. var columnSettings = _data.cols[col];
  1156. if (columnSettings.type == 'bool') {
  1157. if (colProps.filter) elem.prop('checked', true).removeClass('indeterminate');
  1158. else if (!colProps.filter) elem.prop('checked', false).removeClass('indeterminate');
  1159. else if (colProps.filter == '') elem.addClass('indeterminate');
  1160. }
  1161. else elem.val(colProps.filter);
  1162. }
  1163. });
  1164. if (priv.options.forceFilterInit && undefined !== priv.options.forceFilterInit[column]) {
  1165. elem.prop('disabled', true);
  1166. }
  1167. elem.appendTo(headCell);
  1168. _filterFields[column] = elem;
  1169. }
  1170. }
  1171. }
  1172. currentNode.replaceWith(node);
  1173. };
  1174. priv.renderTableTfoot = function() {
  1175. _uiNode$Table.find('tfoot').remove();
  1176. _foot = $('<tfoot></tfoot>').insertAfter(_body);
  1177. //$(_uiNodeCont).next('.foot').replaceWith(_foot);
  1178. };
  1179. priv.renderFooter = function() {
  1180. priv.renderFooterInfo();
  1181. priv.renderFooterPagination();
  1182. priv.renderFooterPageSizes();
  1183. priv.renderFooterColumnPicker();
  1184. priv.renderFooterFunctions();
  1185. priv.renderFooterExport();
  1186. };
  1187. priv.renderFooterInfo = function() {
  1188. var nodeClass = 'tblAjax__' + 'footer__toolbar__info',
  1189. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1190. node;
  1191. if (priv.options.debug) console.log('Render: ', nodeClass);
  1192. node = $('<div class="foot-info ' + nodeClass + '"></div>');
  1193. //console.log('renderFooterInfo total', _data.total, 'page', _state.page, 'priv.options.pageSize', priv.options.pageSize);
  1194. var fromRow = Math.max(_state.page - 1, 0) * _state.pageSize;
  1195. var total = _data.total;
  1196. var toRow = Math.min(fromRow + _state.pageSize, total);
  1197. if (_data.total > 0) {
  1198. $('<p>Wiersze od {0} do {1} z {2}</p>'.f(fromRow + 1, toRow, total)).appendTo(node);
  1199. } else {
  1200. $('<p>Brak wierszy pasujących do kryteriów wyszukiwania</p>').appendTo(node);
  1201. }
  1202. currentNode.replaceWith(node);
  1203. };
  1204. priv.renderFooterPagination = function() {
  1205. var nodeClass = 'tblAjax__' + 'footer__toolbar__pagination',
  1206. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1207. node;
  1208. var currPage = _state.page;
  1209. var totalPages = Math.ceil(_data.total / _state.pageSize);
  1210. if (priv.options.debug) console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage);
  1211. /// console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage, '_state.page', _state.page);
  1212. if (_data.total > 0) {
  1213. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  1214. //create the pager.
  1215. var lowerPage = currPage - 2;
  1216. var upperPage = currPage + 2;
  1217. if (upperPage > totalPages) {
  1218. var diff = upperPage - totalPages;
  1219. upperPage = totalPages;
  1220. lowerPage -= diff;
  1221. }
  1222. if (lowerPage < 1) lowerPage = 1;
  1223. if (upperPage < 5) upperPage = 5;
  1224. //$('<li class="{0}"><a href="#">&lt;&lt;</a></li>'.f(currPage == 1 ? 'disabled' : ''))
  1225. $('<button type="button" class="btn btn-default{0}">&lt;&lt;</button>'.f(currPage == 1 ? ' disabled' : ''))
  1226. .on('click', {pageIndex: 1}, priv.pageChanged)
  1227. .appendTo(node);
  1228. //$('<li class="{0}"><a href="#">&lt;</a></li>'.f(currPage == 1 ? 'disabled' : ''))
  1229. $('<button type="button" class="btn btn-default{0}">&lt;</button>'.f(currPage == 1 ? ' disabled' : ''))
  1230. .on('click', {pageIndex: currPage - 1}, priv.pageChanged)
  1231. .appendTo(node);
  1232. for (var i = lowerPage; i <= upperPage; i++) {
  1233. var link;
  1234. //if (i != currPage) link = $('<li class="{1}"><a href="#">{0}</a></li>'.f(i, i > totalPages ? 'disabled' : ''));
  1235. if (i != currPage) link = $('<button type="button" class="btn btn-default{1}">{0}</button>'.f(i, i > totalPages ? 'disabled' : ''));
  1236. //if (i == currPage) link = $('<li class="active"><a href="#">{0}</a></li>'.f(i));
  1237. if (i == currPage) link = $('<button type="button" class="btn btn-default active">{0}</button>'.f(i));
  1238. if (link) {
  1239. link.on('click', {pageIndex: i}, priv.pageChanged);
  1240. link.appendTo(node);
  1241. }
  1242. }
  1243. //$('<li class="{0}"><a href="#">&gt;</a></li>'.f(currPage == totalPages ? 'disabled' : ''))
  1244. $('<button type="button" class="btn btn-default{0}">&gt;</button>'.f(currPage == totalPages ? ' disabled' : ''))
  1245. .on('click', {pageIndex: currPage + 1}, priv.pageChanged)
  1246. .appendTo(node);
  1247. //$('<li class="{0}"><a href="#">&gt;&gt;</a></li>'.f(currPage == totalPages ? 'disabled' : ''))
  1248. $('<button type="button" class="btn btn-default{0}">&gt;&gt;</button>'.f(currPage == totalPages ? ' disabled' : ''))
  1249. .on('click', {pageIndex: totalPages}, priv.pageChanged)
  1250. .appendTo(node);
  1251. } else {
  1252. node = $('<span class="' + nodeClass + '"></span>');
  1253. }
  1254. currentNode.replaceWith(node);
  1255. };
  1256. priv.renderFooterPageSizes = function() {
  1257. var nodeClass = 'tblAjax__' + 'footer__toolbar__pagesizes',
  1258. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1259. node;
  1260. if (priv.options.debug) console.log('Render: ', nodeClass);
  1261. if (_data.total > 0 && priv.options.pageSizes.length > 0) {
  1262. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  1263. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Liczba wierszy&nbsp;</button>').appendTo(node);
  1264. var span = $('<span class="caret"></span>').appendTo(btn);
  1265. var ul = $('<ul class="dropdown-menu">').appendTo(node);
  1266. $.each(priv.options.pageSizes, function (index, val) {
  1267. var li = $('<li></li>').appendTo(ul);
  1268. if (val == priv.options.pageSize) {
  1269. $('<a style="color:#337AB7;">{0}</a>'.f(val)).appendTo(li);
  1270. } else {
  1271. $('<a href="#">{0}</a>'.f(val)).appendTo(li);
  1272. }
  1273. });
  1274. node.on('click', 'a', priv.pageSizeChanged);
  1275. } else {
  1276. node = $('<span class="' + nodeClass + '"></span>');
  1277. }
  1278. currentNode.replaceWith(node);
  1279. };
  1280. priv.renderFooterColumnPicker = function() {
  1281. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  1282. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1283. node;
  1284. if (priv.options.debug) console.log('Render: ', nodeClass);
  1285. if (priv.options.columnPicker) {
  1286. node = $('<div class="btn-group dropup columnpicker ' + nodeClass + '"></div>');
  1287. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Kolumny&nbsp;</button>').appendTo(node);
  1288. var span = $('<span class="caret"></span>').appendTo(btn);
  1289. var ul = $('<ul class="dropdown-menu">').appendTo(node);
  1290. $.each(_data.cols, function (col, props) {
  1291. if (props.type != "unique" && col != 'ID') {
  1292. var li = $('<li></li>').appendTo(ul),
  1293. label = props.friendly || col;
  1294. label = label.replace(/<br\/?>/g, ' ');
  1295. $('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>'.f((props.hidden) ? '' : 'checked', col, label)).appendTo(li);
  1296. }
  1297. });
  1298. node.on('click', 'input', priv.columnPickerClicked);
  1299. } else {
  1300. node = $('<span class="' + nodeClass + '"></span>');
  1301. }
  1302. currentNode.replaceWith(node);
  1303. };
  1304. priv.renderFooterFunctions = function() {
  1305. var nodeClass = 'tblAjax__' + 'footer__toolbar__functions',
  1306. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1307. node;
  1308. if (priv.options.debug) console.log('Render: ', nodeClass);
  1309. if (priv.options.tblFunctions) {
  1310. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  1311. $.map(priv.options.tblFunctions, function(funObj, funName){
  1312. var funHtml = $('<button class="btn btn-sm btn-default"></button>');
  1313. if (funObj.title) funHtml.attr('title', funObj.title);
  1314. if (funObj.method) funHtml.on('click', priv[funObj.method]);
  1315. else if (funObj.href) funHtml.on('click', {hash:funObj.href}, priv.routeChanged);
  1316. var funIconHtml = $('<i></i>');
  1317. if (funObj.icon) funIconHtml.attr('class', 'glyphicon glyphicon-' + funObj.icon);
  1318. funIconHtml.prependTo(funHtml);
  1319. funHtml.addClass('btn');
  1320. funHtml.appendTo(node);
  1321. });
  1322. } else {
  1323. node = $('<span class="' + nodeClass + '"></span>');
  1324. }
  1325. currentNode.replaceWith(node);
  1326. };
  1327. priv.renderFooterExport = function() {
  1328. var nodeClass = 'tblAjax__' + 'footer__toolbar__export',
  1329. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  1330. node;
  1331. if (priv.options.debug) console.log('Render: ', nodeClass);
  1332. if (priv.options.exportFields.length) {
  1333. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  1334. var btn = $('<button class="btn btn-sm dropdown-toggle" data-toggle="dropdown" href="#">Export&nbsp;</button>').appendTo(node);
  1335. var span = $('<span class="caret"></span>').appendTo(btn);
  1336. var ul = $('<ul class="dropdown-menu">').appendTo(node);
  1337. $.each(_data.cols, function (col, props) {
  1338. if (-1 !== priv.options.exportFields.indexOf(col)) {
  1339. var li = $('<li></li>').appendTo(ul);
  1340. $('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>'.f((_exportFieldsSelect[col])? 'checked' : '', col, props.friendly || col)).appendTo(li);
  1341. li.on('click', 'input', priv.exportFieldChanged);
  1342. }
  1343. });
  1344. var li = $('<li></li>').appendTo(ul);
  1345. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
  1346. li.on('click', 'a', priv.exportToHTML);
  1347. var li = $('<li></li>').appendTo(ul);
  1348. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
  1349. li.on('click', 'a', priv.exportToCSV);
  1350. } else {
  1351. node = $('<span class="' + nodeClass + '"></span>');
  1352. }
  1353. currentNode.replaceWith(node);
  1354. };
  1355. priv.renderInlineEditBox = function() {
  1356. var nodeClass = 'tblAjax__' + 'inlineEditBox',
  1357. currentNode = $(_uiNodeCont).parent().children('.' + nodeClass),
  1358. node;
  1359. var node = $('<div class="' + nodeClass + ' modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
  1360. /// console.log('L.<?php echo __LINE__; ?> Render: priv.renderInlineEditBox, currentNode.html:', currentNode.html(), currentNode);
  1361. var modalWrap = $('<div class="modal-dialog"></div>').appendTo(node);
  1362. var modalWrap = $('<div class="modal-content"></div>').appendTo(modalWrap);
  1363. var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(modalWrap);
  1364. var iebHead = $('<div class="modal-header" style="cursor:pointer">').appendTo(frmInlineEdit);
  1365. $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove" style="color:red"></i></button>').appendTo(iebHead);
  1366. $('<h4 id="myModalLabel">Edytuj</h4>').appendTo(iebHead);
  1367. var iebBodyWrap = $('<div class="modal-body" style="padding:0"></div>').appendTo(frmInlineEdit);
  1368. var iebBody = $('<div style="padding:15px"></div>').appendTo(iebBodyWrap);
  1369. $('<input type="hidden" name="ID" value="">').appendTo(iebBody);
  1370. $('<input type="hidden" name="col" value="">').appendTo(iebBody);
  1371. $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
  1372. var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
  1373. $('<button class="btn" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
  1374. var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
  1375. frmInlineEdit.on('submit', function() {
  1376. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  1377. var data = inlineEditBox$Node.find('form').serialize();
  1378. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  1379. function notifyAjaxCallback(data) {
  1380. var notify = {};
  1381. notify.type = (data && data.type)? data.type : '';
  1382. notify.msg = (data && data.msg)? data.msg : '';
  1383. switch (notify.type) {
  1384. case 'success':
  1385. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  1386. break;
  1387. case 'info':
  1388. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  1389. break;
  1390. case 'error':
  1391. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1392. break;
  1393. case 'warning':
  1394. notify.type = 'warn';
  1395. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1396. break;
  1397. default:
  1398. notify.msg = 'Nieznany błąd';
  1399. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  1400. notify.type = '';
  1401. }
  1402. jQuery.notify(notify.msg, notify.type);
  1403. }
  1404. $.ajax({
  1405. data: data,
  1406. dataType: 'json',
  1407. type: "POST",
  1408. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE_SAVE'
  1409. })
  1410. .done(function(data, textStatus, jqXHR){
  1411. notifyAjaxCallback(data);
  1412. publ.refresh();
  1413. inlineEditBox$Node.modal('hide');
  1414. })
  1415. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  1416. if (jqXHR.responseJSON) {
  1417. notifyAjaxCallback(jqXHR.responseJSON);
  1418. }
  1419. else {
  1420. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  1421. if (jqXHR.status == 404) {
  1422. jQuery.notify(jqXHR.responseText, 'error');
  1423. } else {
  1424. jQuery.notify(jqXHR.responseText, 'warn');
  1425. }
  1426. }
  1427. inlineEditBox$Node.modal('hide');
  1428. });
  1429. return false;
  1430. });
  1431. currentNode.replaceWith(node);
  1432. };
  1433. priv.exportFieldChanged = function (e) {
  1434. e.stopPropagation();
  1435. var column = $(this).val();
  1436. _exportFieldsSelect[column] = !_exportFieldsSelect[column];
  1437. };
  1438. priv.exportToHTML = function (e) {
  1439. priv.exportData('html', $(this), e);
  1440. };
  1441. priv.exportToCSV = function (e) {
  1442. priv.exportData('csv', $(this), e);
  1443. };
  1444. priv.exportData = function (format, node, e) {
  1445. var exportFields = [];
  1446. $.each(_exportFieldsSelect, function (col, selected) {
  1447. if (selected) {
  1448. exportFields.push(col);
  1449. }
  1450. });
  1451. if (!exportFields.length) {
  1452. alert('Nie wybrano żadnych pól do eksportu.');
  1453. e.preventDefault();
  1454. return false;
  1455. }
  1456. var limit = 10000;
  1457. if (!_data.total || _data.total <= 0) {
  1458. alert('Brak rekordów do eksportu.');
  1459. e.preventDefault();
  1460. return false;
  1461. }
  1462. if (_data.total > limit) {
  1463. if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) {
  1464. e.preventDefault();
  1465. return false;
  1466. }
  1467. }
  1468. var exportUrl = 'index.php?MENU_INIT=VIEWTABLE_AJAX_EXPORT&ZASOB_ID=<?php echo $this->_zasobID; ?>';
  1469. if ('csv' == format) exportUrl += '&HEADER_NOT_INIT=YES';
  1470. exportUrl += '&format=' + format;
  1471. exportUrl += '&flds=' + exportFields.join(',');
  1472. exportUrl += '&sortCol=' + (_state.filters.currSortCol || '');
  1473. exportUrl += '&sortDir=' + (_state.filters.currSortFlip ? "desc" : "asc");
  1474. if (Object.keys(_state.filters.filterCols).length > 0) {
  1475. $.each(_state.filters.filterCols, function (col, colProps) {
  1476. if (colProps.filter && colProps.filter.length > 0) {
  1477. exportUrl += '&f_' + col + '=' + colProps.filter;
  1478. }
  1479. });
  1480. }
  1481. // specialFilters
  1482. $.each(_state.specialFilters, function(groupName, btnValue) {
  1483. if (btnValue.length > 0) {
  1484. exportUrl += '&sf_' + groupName + '=' + btnValue;
  1485. }
  1486. });
  1487. if (priv.options.forceFilterInit) {
  1488. $.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
  1489. exportUrl += '&sf_' + fltr + '=' + fltrProps;
  1490. });
  1491. }
  1492. node.attr('href', exportUrl);
  1493. };
  1494. /*
  1495. calls the webservice(if defined).
  1496. used only inside priv.init
  1497. */
  1498. priv.update = function (callback) {
  1499. var skipCols, resetChecked;// undefined
  1500. if (!priv.options.url) {
  1501. if (priv.options.debug) console.log('no url found L.<?php echo __LINE__; ?>');
  1502. return;
  1503. }
  1504. if (priv.options.debug) console.log('requesting data from url:{0} data:{1} L.<?php echo __LINE__; ?>'.f(priv.options.url, JSON.stringify(priv.options.urlData) || ''));
  1505. var initUrlAdd = '',
  1506. reqData = {},
  1507. filtersInitSet = false;
  1508. initUrlAdd += '&currSortCol=' + _state.filters.currSortCol;
  1509. initUrlAdd += '&currSortFlip=' + ((_state.filters.currSortCol)? "desc" : "asc");
  1510. if (Object.keys(_state.filters.filterCols).length > 0) {
  1511. $.each(_state.filters.filterCols, function (col, colProps) {
  1512. if (colProps.filter && colProps.filter.length > 0) {
  1513. initUrlAdd += '&f_' + col + '=' + colProps.filter;
  1514. filtersInitSet = true;
  1515. }
  1516. });
  1517. }
  1518. $.each(_state.specialFilters, function(groupName, btnValue) {
  1519. if (btnValue.length > 0) {
  1520. initUrlAdd += '&sf_' + groupName + '=' + btnValue;
  1521. filtersInitSet = true;
  1522. }
  1523. });
  1524. if (priv.options.forceFilterInit) {
  1525. $.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
  1526. reqData['f_' + fltr] = fltrProps;
  1527. filtersInitSet = true;
  1528. });
  1529. }
  1530. $.ajax({
  1531. url: priv.options.url + initUrlAdd,
  1532. type: priv.options.urlPost ? 'POST' : 'GET',
  1533. dataType: 'json',
  1534. contentType: "application/json; charset=utf-8",
  1535. data: reqData,
  1536. async: true,
  1537. success: function (data) {
  1538. if (priv.options.debug) console.log('request finished L.<?php echo __LINE__; ?>');
  1539. // assign the new data
  1540. if (data && data.cols) {
  1541. priv.setStateCols(data.cols);
  1542. }
  1543. // set initial filters (_state.filters.filterCols)
  1544. if (filtersInitSet && _data && _data.cols) {
  1545. $.map(reqData, function(fltrValue, fltr){
  1546. var colName = null;
  1547. if (fltr.substr(0, 3) == 'sf_') {
  1548. colName = fltr.substr(3);
  1549. }
  1550. else if (fltr.substr(0, 2) == 'f_') {
  1551. colName = fltr.substr(2);
  1552. }
  1553. if (colName && _data.cols[colName]) {
  1554. //add the filter to the filter array
  1555. _state.filters.filterCols[colName] = {
  1556. filter: fltrValue,
  1557. colName: colName
  1558. };
  1559. }
  1560. });
  1561. }
  1562. // assign the new state (data)
  1563. state = {data: {}};
  1564. if (!skipCols) state.data.cols = data.cols || {};
  1565. state.data.rows = data.rows || [];
  1566. state.data.total = data.total || 0;
  1567. state.page = data.page || 0;
  1568. state.pageSize = data.pageSize || priv.options.pageSize;
  1569. state.filters = data.filters || {};
  1570. priv.setState(state);
  1571. if (typeof callback == "function")
  1572. callback.call(this);
  1573. },
  1574. error: function (err) {
  1575. //console.log('request error: {0}'.f(JSON.stringify(err)));
  1576. if (typeof callback == "function")
  1577. callback.call(this);
  1578. }
  1579. });
  1580. };
  1581. /*
  1582. assigns the new data.
  1583. */
  1584. priv.setState = function (state) {
  1585. var oldState = _state,// TODO: use to check what really changed (use extend!)
  1586. renderParts = {};
  1587. if (state.data) {
  1588. if (state.data.cols && state.data.cols.length > 0) {
  1589. priv.setStateCols(state.data.cols);
  1590. priv.setStateData(state.data);
  1591. renderParts['head'] = true;
  1592. } else {
  1593. priv.setStateData(state.data, true);
  1594. }
  1595. renderParts['body'] = true;
  1596. renderParts['foot_pagination'] = true;
  1597. }
  1598. if (state.hasOwnProperty('specialFilters')) {
  1599. _state.specialFilters = state.specialFilters;
  1600. renderParts['head__specialFilters'] = true;
  1601. }
  1602. if (state.hasOwnProperty('page')) {
  1603. if (state.page != _state.page) {
  1604. _state.page = state.page;
  1605. renderParts['foot_pagination'] = true;
  1606. }
  1607. }
  1608. if (state.hasOwnProperty('pageSize')) {
  1609. if (state.pageSize != _state.pageSize) {
  1610. _state.pageSize = state.pageSize;
  1611. renderParts['foot_pagination'] = true;
  1612. }
  1613. }
  1614. if (state.hasOwnProperty('filters')) {
  1615. /// console.log('L.<?php echo __LINE__; ?> setState::state.filters: ', state.filters);//TODO:DBG:RMME
  1616. priv.setStateFilters(state.filters);
  1617. // TODO: if state diff's
  1618. renderParts['head__specialFilters'] = true;
  1619. renderParts['foot_pagination'] = true;
  1620. }
  1621. renderParts = Object.keys(renderParts);
  1622. if (priv.options.debug) console.log('setState::renderParts: ', renderParts);//TODO:DBG:RMME
  1623. ///console.log('L.<?php echo __LINE__; ?> setState::renderParts: ', renderParts);//TODO:DBG:RMME
  1624. if (renderParts.length > 0) {
  1625. jQuery(_uiNodeCont).trigger('TableAjax:render', renderParts);
  1626. }
  1627. };
  1628. priv.setStateCols = function (cols) {
  1629. _state.cols = cols;
  1630. _state.uniqueCol = undefined;
  1631. // fix col name - props.column
  1632. $.each(_state.cols, function (col, props) {
  1633. props.column = col;
  1634. });
  1635. // fix col types - default 'string'
  1636. $.each(_state.cols, function (col, props) {
  1637. if (!props.type) cols[col].type = "string";
  1638. });
  1639. // fix props.unique - set false if not set
  1640. // set _state.uniqueCol - first column defined as unique
  1641. $.each(_state.cols, function (col, props) {
  1642. //if several unique columns is defined, use the first.
  1643. if (props.unique) {
  1644. if (!_state.uniqueCol) _state.uniqueCol = col;
  1645. else props.unique = false;
  1646. }
  1647. });
  1648. // fix props.filter - set true if not set - TODO: allow filter this col?
  1649. $.each(_state.cols, function (col, props) {
  1650. if (props.filter == undefined) props.filter = true;
  1651. });
  1652. if (_state.uniqueCol) {
  1653. //create a unique column definition
  1654. _state.cols["unique"] = {
  1655. column: "unique",
  1656. type: "unique",
  1657. index: -1,
  1658. hidden: true
  1659. };
  1660. }
  1661. _state.colsSorted = Object.keys(_state.cols).sort(function (a, b) {
  1662. return _state.cols[a].index - _state.cols[b].index;
  1663. });
  1664. };
  1665. priv.setStateFilters = function(stateFilters) {
  1666. var newFilterCols = {},
  1667. newSpecialFilters = {};
  1668. $.map(stateFilters, function (fltrProps, fltr) {
  1669. switch (fltr) {
  1670. case 'currSortCol': _state.filters.currSortCol = fltrProps; break;
  1671. case 'currSortFlip': _state.filters.currSortFlip = (fltrProps == 'desc')? true : false; break;
  1672. default:
  1673. if (fltr.substr(0, 2) == 'f_') {
  1674. newFilterCols[fltr.substr(2)] = {
  1675. filter: fltrProps,
  1676. colName: fltr.substr(2)
  1677. };
  1678. }
  1679. else if (fltr.substr(0, 3) == 'sf_') {
  1680. var groupName = fltr.substr(3);
  1681. if (priv.options.specialFilterFunctions.hasOwnProperty(groupName)) {
  1682. newSpecialFilters[groupName] = fltrProps;
  1683. }
  1684. }
  1685. }
  1686. });
  1687. _state.filters.filterCols = newFilterCols;
  1688. _state.specialFilters = newSpecialFilters;
  1689. };
  1690. priv.setStateData = function (pData, skipCols, resetChecked) {
  1691. var data = $.extend(true, {}, pData);
  1692. data.cols = _state.cols;// always use old cols - change cols mved to priv.setStateCols
  1693. _data = data;
  1694. _data.rowsOrg = _data.rows;
  1695. //we might have more/less data now. Recalculate stuff.
  1696. if (_state.page > 1) {
  1697. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  1698. }
  1699. //keep any previously checked rows around?
  1700. if (resetChecked === true || resetChecked === undefined)
  1701. _uniqueCols = {};
  1702. else {
  1703. for (var key in _uniqueCols)
  1704. _uniqueCols[key] = priv.getRow(key);
  1705. }
  1706. if (_state.uniqueCol) {
  1707. //add rows that needs to be pre-checked
  1708. $.each(_data.rows, function (index, row) {
  1709. if (row["checked"] === true)
  1710. _uniqueCols[row[_state.uniqueCol]] = row;
  1711. });
  1712. }
  1713. };
  1714. /**
  1715. * Filters the data.
  1716. */
  1717. priv.filter = function () {
  1718. if (!priv.options.filter) return;
  1719. if (Object.keys(_state.filters.filterCols).length == 0) return;
  1720. publ.loadPage(0);
  1721. };
  1722. /*
  1723. sorts the data on the current sorting column
  1724. */
  1725. priv.sort = function () {
  1726. if (!_data.cols[_state.filters.currSortCol]) _state.filters.currSortCol = "";
  1727. if (!_state.filters.currSortCol) return;
  1728. publ.loadPage(0);
  1729. };
  1730. /*
  1731. helper that returns the underlying data by the unique value
  1732. */
  1733. priv.getRow = function (uniqueValue) {
  1734. var row;
  1735. $.each(_data.rowsOrg, function (i, r) {
  1736. if (r[_state.uniqueCol] == uniqueValue) {
  1737. row = r;
  1738. return false;
  1739. }
  1740. });
  1741. return row;
  1742. };
  1743. /*
  1744. when: typing a filter
  1745. what: triggers filtering on the value
  1746. */
  1747. priv.filterChanged = function (e) {
  1748. //clear old timer if we're typing fast enough
  1749. if (priv.options.debug) console.log('filterChanged L.<?php echo __LINE__; ?>');
  1750. if (_filterTimeout) {
  1751. clearTimeout(_filterTimeout);
  1752. if (priv.options.debug) console.log('filtering cancelled');
  1753. }
  1754. var filter = this.value
  1755. , fltr = $(this)
  1756. , col = _data.cols[e.data.column]
  1757. , timeout = 300;
  1758. if (this.value) {
  1759. if (!fltr.hasClass('filter-active')) {
  1760. fltr.addClass('filter-active');
  1761. }
  1762. } else {
  1763. if (fltr.hasClass('filter-active')) {
  1764. fltr.removeClass('filter-active');
  1765. }
  1766. }
  1767. //boolean filters needs some special care
  1768. if (col.type == "bool" || col.type == "unique") {
  1769. timeout = 0;
  1770. var elem = $(this);
  1771. var cssClass = 'indeterminate';
  1772. if (elem.hasClass(cssClass)) {
  1773. e.preventDefault();
  1774. elem.removeClass(cssClass);
  1775. filter = true;
  1776. } else {
  1777. if (!elem.is(':checked')) {
  1778. filter = false;
  1779. } else {
  1780. elem.addClass(cssClass);
  1781. filter = '';
  1782. }
  1783. }
  1784. }
  1785. //add the filter to the filter array
  1786. _state.filters.filterCols[col.column] = {
  1787. filter: filter,
  1788. colName: col.column
  1789. };
  1790. //wait a few deciseconds before filtering
  1791. _filterTimeout = setTimeout(function () {
  1792. _filterTimeout = undefined;
  1793. priv.filter();
  1794. }, timeout);
  1795. };
  1796. priv.filtersClean = function (e) {
  1797. if (_filterTimeout) {
  1798. clearTimeout(_filterTimeout);
  1799. if (priv.options.debug) console.log('filtering cancelled - filtersClean');
  1800. }
  1801. var filtersActive = false;
  1802. $.map(_state.filters.filterCols, function (colProps, col) {
  1803. if (colProps.filter.length > 0) {
  1804. filtersActive = true;
  1805. colProps.filter = '';
  1806. }
  1807. });
  1808. if (filtersActive) {
  1809. // TODO: dont remove value from forceFilterInit fields - no field names in search fields?
  1810. /// TODO: rerender _head (thead.filter)
  1811. var elems = _uiNode$Table.find('thead').find('.filter').find('input');
  1812. elems.val('').prop('disabled', false);
  1813. elems.removeClass('filter-active');
  1814. priv.filter();
  1815. }
  1816. return false;
  1817. },
  1818. /**
  1819. * Filters the data by specialFilter.
  1820. * when: click on special filter
  1821. * what: triggers filtering on the value
  1822. */
  1823. priv.specialFilterChanged = function (e) {
  1824. if (priv.options.debug) console.log('specialFilterChanged e.data:', e.data);
  1825. var state = {};
  1826. state.specialFilters = _state.specialFilters;
  1827. state.specialFilters[e.data.group] = e.data.value;
  1828. priv.setState(state);
  1829. publ.loadPage(0);
  1830. };
  1831. priv.longTextChanged = function(e) {
  1832. priv.options.longDesc = !priv.options.longDesc;
  1833. _body.find('td').each(function(ind, el){
  1834. var $el = jQuery(el);
  1835. if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
  1836. //console.log(el.attr('class') + ': ' + el.text());
  1837. if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
  1838. if (priv.options.longDesc) {
  1839. $el.addClass('tbl-short-txt');
  1840. var $elSpan = jQuery(el.firstChild);
  1841. $elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
  1842. } else {
  1843. $el.removeClass('tbl-short-txt');
  1844. }
  1845. }
  1846. }
  1847. });
  1848. return false;
  1849. };
  1850. priv.mapEditorHide = function() {
  1851. priv.options.mapEditor = false;
  1852. if ('window' == priv.options.mapEditorContainer) {
  1853. //_mapEditorDialog.dialog("close");
  1854. _mapEditorDialog.dialog("destroy");
  1855. }
  1856. _mapEditorWrap.hide();
  1857. _mapEditor.hide();
  1858. };
  1859. priv.mapEditorShow = function() {
  1860. //console.log('TODO:mapEditorShow():', priv.options.mapEditorContainer, 'visible:', priv.options.mapEditor);
  1861. priv.options.mapEditor = true;
  1862. _mapEditor.show();
  1863. _mapEditorWrap.show();
  1864. _mapEditor.TableAjaxMap({
  1865. //debug: true,
  1866. wpsUrl: 'http://biuro.biall-net.pl/wps',
  1867. wfsUrl: 'http://biuro.biall-net.pl/wps',
  1868. showAddLayerWidget: <?php echo ($this->hasAdditionalLayers())? 'true' : 'false'; ?>,
  1869. zoomStrategyActivate: 14,
  1870. layerName: '<?php echo $this->getLabelHtml(); ?>',
  1871. addBtn: {
  1872. title: 'Przenieś mapę do okna',
  1873. displayClass: 'mapEditor-btnBackToWindow',
  1874. trigger: function() {
  1875. priv.mapEditorHide();
  1876. priv.options.mapEditorContainer = 'window';
  1877. priv.mapEditorShow();
  1878. priv.resizableMapDockNode('destroy');
  1879. }
  1880. },
  1881. onSaveFeature: function(selectedRecordId, selectedFeatureExtent) {
  1882. if (priv.options.debug) console.log('onSaveFeature (',selectedRecordId,'/',selectedFeatureExtent,') ', this);
  1883. if (!selectedRecordId) {
  1884. alert('Brak zaznaczonego rekordu - wybierz rekord z tabeli');
  1885. return;
  1886. }
  1887. function notifyAjaxCallback(data) {
  1888. var notify = {};
  1889. notify.type = (data && data.type)? data.type : '';
  1890. notify.msg = (data && data.msg)? data.msg : '';
  1891. switch (notify.type) {
  1892. case 'success':
  1893. if (!notify.msg) notify.msg = 'Aktualizacja danych dla rekordu ' + selectedRecordId;
  1894. break;
  1895. case 'info':
  1896. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  1897. break;
  1898. case 'error':
  1899. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1900. break;
  1901. case 'warning':
  1902. notify.type = 'warn';
  1903. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1904. break;
  1905. default:
  1906. notify.msg = 'Nieznany błąd';
  1907. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  1908. notify.type = '';
  1909. }
  1910. jQuery.notify(notify.msg, notify.type);
  1911. }
  1912. $.ajax({
  1913. data: {polygon: selectedFeatureExtent},
  1914. dataType: 'json',
  1915. type: "POST",
  1916. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=THE_GEOM_SAVE&ID=' + selectedRecordId
  1917. })
  1918. .done(function(data, textStatus, jqXHR){
  1919. notifyAjaxCallback(data);
  1920. //jQuery.notify('Aktualizacja danych dla rekordu ' + selectedRecordId, 'success');
  1921. publ.loadPage(0);// TODO: reload table data
  1922. })
  1923. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  1924. if (jqXHR.responseJSON) {
  1925. notifyAjaxCallback(jqXHR.responseJSON);
  1926. }
  1927. else {
  1928. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  1929. if (jqXHR.status == 404) {
  1930. jQuery.notify(jqXHR.responseText, 'error');
  1931. } else {
  1932. jQuery.notify(jqXHR.responseText, 'warn');
  1933. }
  1934. }
  1935. });
  1936. },
  1937. onSelectBox: function(bounds) {
  1938. if (undefined !== OpenLayers.Bounds && bounds instanceof OpenLayers.Bounds) {
  1939. var column = 'the_geom';
  1940. if (undefined !== _filterFields['the_geom']) {
  1941. var filter = 'BBOX:' + bounds.top + ',' + bounds.right + ',' + bounds.bottom + ',' + bounds.left;
  1942. _filterFields[column].val(filter);
  1943. _state.filters.filterCols[column] = {
  1944. filter: filter,
  1945. colName: column
  1946. };
  1947. priv.filter();
  1948. }
  1949. }
  1950. }
  1951. });
  1952. priv.mapEditorShowElement();
  1953. };
  1954. priv.mapEditorShowElement = function() {
  1955. if ('window' == priv.options.mapEditorContainer) {
  1956. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  1957. if (!mapEditor || !mapEditor.length) {
  1958. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  1959. var mapEditor = tblCont.children('.AjaxTableCont-mapEditorContainer').children('.mapEditor-map');
  1960. if (!mapEditor || !mapEditor.length) {
  1961. // TODO: create new map
  1962. }
  1963. _mapEditorWrap.append(mapEditor);
  1964. }
  1965. _mapEditorWrap.css({padding:'5px'});
  1966. _mapEditorDialog = _mapEditorWrap.dialog({
  1967. width: 540,
  1968. minWidth: 400,
  1969. minHeight: 400,
  1970. open: function(e, ui) {
  1971. var n = jQuery(this),
  1972. mapWrap = n.children(":first"),
  1973. map = mapWrap.children(":first");
  1974. map.css({width: n.width() - 5, height: n.height() - 5});
  1975. _mapEditor.TableAjaxMapUpdateSize();
  1976. },
  1977. resizeStart: function(e, ui) {
  1978. jQuery(this).children(":first").children(":first").css({display:'none'});
  1979. },
  1980. resizeStop: function(e, ui){
  1981. var n = jQuery(this),
  1982. map = n.children(":first").children(":first");
  1983. n.css({width: n.parent().width()});
  1984. map.css({display: 'block', height: n.height(), width: n.width()});
  1985. _mapEditor.TableAjaxMapUpdateSize();
  1986. },
  1987. dragStop: function(e, ui){
  1988. _mapEditor.TableAjaxMapUpdateSize();// to prevent drag-zoom error
  1989. }
  1990. });
  1991. _mapEditorWrap.bind('dialogclose', function(e) {
  1992. priv.options.mapEditor = false;
  1993. });
  1994. var dialogTitleBar = _mapEditorDialog.parent().parent().find('.ui-dialog-titlebar');
  1995. var dialogTitleBarCloseBtn = dialogTitleBar.find('.ui-dialog-titlebar-close');
  1996. if (dialogTitleBarCloseBtn) {
  1997. var btnToggle = jQuery('<span style="width:18px;height:18px;position:absolute;top:50%;right:25px;margin-top:-9px;" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only"><i style="margin-top:3px;" class="glyphicon glyphicon-fullscreen"></i></span>');
  1998. btnToggle.on('click', function(e) {
  1999. priv.options.mapEditorContainer = 'dock';
  2000. _mapEditorWrap.dialog('close');
  2001. priv.mapEditorShowElement();
  2002. });
  2003. btnToggle.insertBefore(dialogTitleBarCloseBtn);
  2004. }
  2005. }
  2006. else if ('dock' == priv.options.mapEditorContainer) {
  2007. priv.resizableMapDockNode('prepare');
  2008. _mapEditor.TableAjaxMapUpdateSize();
  2009. }
  2010. };
  2011. priv.resizableMapDockNode = function(task) {
  2012. if ('prepare' == task) {
  2013. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2014. if (mapEditor && mapEditor.length) {// map is inside _mapEditorWrap (window)
  2015. var mapDockNode = jQuery('<div class="AjaxTableCont-mapEditorContainer"></div>');
  2016. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2017. tblCont.children('.AjaxTableCont-mapEditorContainer').remove();
  2018. var breadcrumb = tblCont.children('.breadcrumb');
  2019. if (!breadcrumb || !breadcrumb.length) {
  2020. tblCont.prepend(mapDockNode);
  2021. } else {
  2022. mapDockNode.insertAfter(breadcrumb);
  2023. }
  2024. mapDockNode.append(mapEditor);
  2025. }
  2026. var mapDockResizable = mapEditor.parent();
  2027. mapDockResizable.resizable({handles: 's', minHeight: 300, minWidth: 300});
  2028. var resizeLineHeigth = 6;
  2029. mapDockResizable.children(":first").css({height: 'auto'});
  2030. mapDockResizable.css({marginBottom: resizeLineHeigth+'px'});
  2031. mapEditor.css({marginBottom: resizeLineHeigth+'px'});
  2032. mapEditor.children(":first").css({width: mapEditor.width()});
  2033. mapDockResizable.find('.ui-resizable-s').css({height:resizeLineHeigth+'px', bottom: '-'+resizeLineHeigth+'px'});
  2034. mapDockResizable.on('resizestart', function(event, ui) {
  2035. ui.element.children(":first").children(":first").css({display:'none'})
  2036. });
  2037. mapDockResizable.on('resizestop', function(event, ui) {
  2038. ui.element.children(":first").children(":first").css({display:'block', height: ui.element.height()});
  2039. });
  2040. } else if ('destroy' == task) {
  2041. var mapDockResizable = jQuery(_uiNodeCont).parent('.AjaxTableCont').children('.AjaxTableCont-mapEditorContainer');
  2042. mapDockResizable.resizable('destroy');
  2043. mapDockResizable.remove();
  2044. }
  2045. };
  2046. priv.mapEditorChanged = function(e) {
  2047. if (priv.options.debug) console.log('mapEditorChanged option(',priv.options.mapEditor,')');
  2048. priv.options.mapEditor = !priv.options.mapEditor;
  2049. if (priv.options.mapEditor) {
  2050. priv.mapEditorShow();
  2051. }
  2052. else {
  2053. priv.mapEditorHide();
  2054. }
  2055. return false;
  2056. };
  2057. /*
  2058. when: changing page in pager
  2059. what: triggers table to be created with new page
  2060. */
  2061. priv.pageChanged = function (e) {
  2062. e.preventDefault();
  2063. var totalPages = Math.ceil(_data.total / _state.pageSize);
  2064. if (e.data.pageIndex < 1 || e.data.pageIndex > totalPages) return;
  2065. //set the new page
  2066. _state.page = e.data.pageIndex;
  2067. publ.loadPage(_state.page);
  2068. };
  2069. /*
  2070. when: changing pagesize in pagesize dropdown
  2071. what: triggers table to be created with new pagesize
  2072. */
  2073. priv.pageSizeChanged = function (e) {
  2074. e.preventDefault();
  2075. var val = $(this).text();
  2076. if (priv.options.debug) console.log('pagesize changed to:{0}'.f(val));
  2077. if (parseInt(val) == priv.options.pageSize) {
  2078. return false;
  2079. }
  2080. priv.options.pageSize = parseInt(val);
  2081. publ.loadPage(1, priv.options.pageSize);
  2082. jQuery(_uiNodeCont).trigger('TableAjax:render', ['body', 'foot_pagination']);
  2083. priv.saveProfilePageSize(priv.options.pageSize);
  2084. };
  2085. /*
  2086. when: clicking a column
  2087. what: triggers table to be sorted by the column
  2088. */
  2089. priv.columnClicked = function (e) {
  2090. e.preventDefault();
  2091. if (priv.options.debug) console.log('col:{0} clicked'.f(e.data.column));
  2092. //set the new sorting column
  2093. if (_state.filters.currSortCol == e.data.column) _state.filters.currSortFlip = !_state.filters.currSortFlip;
  2094. _state.filters.currSortCol = e.data.column;
  2095. /// TODO: var state = {}; state.currSortCol = ''; state.currSortFlip = ''; priv.setState(state);
  2096. _headSort = undefined;
  2097. _body = undefined;
  2098. priv.sort();
  2099. };
  2100. priv.saveProfilePageSize = function(pageSize) {
  2101. var reqData = {};
  2102. reqData.pageSize = pageSize;
  2103. $.ajax({
  2104. data: reqData,
  2105. type: "POST",
  2106. dataType: 'json',
  2107. // async: true,
  2108. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PAGE_SIZE_SAVE'
  2109. })
  2110. .done(function(data, textStatus, jqXHR){
  2111. if (data && data.type && data.type == 'info') {
  2112. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2113. } else {
  2114. jQuery.notify('Zapisano ustawienia', 'success');
  2115. }
  2116. })
  2117. .fail(function(){
  2118. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2119. });
  2120. };
  2121. priv.saveHiddenCols = function() {
  2122. var reqData = {};
  2123. $.each(_data.cols, function (col, props) {
  2124. if (props.type != "unique" && col != 'unique' && col != 'ID') {
  2125. reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
  2126. }
  2127. });
  2128. $.ajax({
  2129. data: reqData,
  2130. type: "POST",
  2131. dataType: 'json',
  2132. // async: true,
  2133. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIDDEN_COLS_SAVE'
  2134. })
  2135. .done(function(data, textStatus, jqXHR){
  2136. if (data && data.type && data.type == 'info') {
  2137. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  2138. } else {
  2139. jQuery.notify('Zapisano ustawienia', 'success');
  2140. }
  2141. })
  2142. .fail(function(){
  2143. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  2144. });
  2145. };
  2146. /*
  2147. when: clicking a column in columnpicker
  2148. what: triggers table to show/hide the column
  2149. */
  2150. priv.columnPickerClicked = function (e) {
  2151. e.stopPropagation();
  2152. var column = $(this).val();
  2153. //toggle column visibility
  2154. _data.cols[column].hidden = !_data.cols[column].hidden;
  2155. priv.saveHiddenCols();
  2156. //_data.cols[column].index = new priv.ext.XDate();
  2157. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  2158. };
  2159. priv.columnHideClicked = function (e) {
  2160. e.stopPropagation();
  2161. var column;
  2162. if (e.data && e.data.column) {
  2163. column = e.data.column;
  2164. } else {
  2165. return;
  2166. }
  2167. //toggle column visibility
  2168. _data.cols[column].hidden = !_data.cols[column].hidden;
  2169. priv.saveHiddenCols();
  2170. //_data.cols[column].index = new priv.ext.XDate();
  2171. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  2172. };
  2173. /*
  2174. when: clicking a row checkbox
  2175. what: toggles checked state on row, and add/removes it from checked array
  2176. */
  2177. priv.rowChecked = function (e) {
  2178. var elem = $(this);
  2179. //get the row's unique value
  2180. var unique = elem.closest('tr').data('unique');
  2181. if (priv.options.debug) console.log('row({0}) {1}'.f(unique, elem.is(':checked') ? 'checked' : 'unchecked'));
  2182. //store the row in checked array
  2183. if (elem.is(':checked')) _uniqueCols[unique] = priv.getRow(unique);
  2184. else delete _uniqueCols[unique];
  2185. };
  2186. /*
  2187. when: clicking anywhere on a row
  2188. what: row data and other info is returned to caller
  2189. */
  2190. priv.rowClicked = function (e) {
  2191. if (!_state.uniqueCol) {
  2192. if (priv.options.debug) console.log('no unique column specified');
  2193. return;
  2194. }
  2195. //gather callback data
  2196. var elem = $(this);
  2197. var column = _data.cols[elem.data('column')];
  2198. var unique = elem.closest('tr').data('unique');
  2199. var row = priv.getRow(unique);
  2200. var isChecked = elem.closest('tr').find('.unique').is(':checked');
  2201. //trigger callback
  2202. if (typeof priv.options.rowClicked == 'function') {
  2203. priv.options.rowClicked.call(e.target, {
  2204. event: e,
  2205. row: row,
  2206. column: column,
  2207. checked: isChecked
  2208. });
  2209. }
  2210. };
  2211. /**
  2212. * Inline edit.
  2213. */
  2214. priv.rowDblClicked = function (e) {
  2215. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  2216. // hide popover for typespecial fld on click
  2217. if (_popoverCellCurrent) {
  2218. _popoverCellCurrent.popover('hide');
  2219. }
  2220. // e.clientX: 1002; e.clientY: 245
  2221. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2222. inlineEditBox$Node.modal();
  2223. inlineEditBox$Node.show();
  2224. inlineEditBox$Node.on('shown.bs.modal', function(e) {
  2225. var dialogBox = jQuery(this).find('.modal-dialog'),
  2226. modalBody = dialogBox.find('.modal-body'),
  2227. boudingRect = dialogBox.get(0).getBoundingClientRect();
  2228. dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
  2229. modalBody.css({overflow: 'scroll'});
  2230. dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
  2231. dialogBox.draggable({handle: '.modal-header'});
  2232. });
  2233. inlineEditBox$Node.on('hidden.bs.modal', function(e) {
  2234. var dialogBox = jQuery(this).find('.modal-dialog'),
  2235. modalBody = dialogBox.find('.modal-body');
  2236. dialogBox.removeAttr('style');
  2237. modalBody.removeAttr('style');
  2238. modalBody.css({padding: '0'});
  2239. dialogBox.resizable();
  2240. dialogBox.draggable();
  2241. dialogBox.resizable('destroy');
  2242. dialogBox.draggable('destroy');
  2243. });
  2244. inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
  2245. inlineEditBox$Node.find('input[name=col]').val(e.data.col);
  2246. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  2247. $.ajax({
  2248. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_INLINE&ID=' + e.data.id + '&col=' + e.data.col,
  2249. type: 'GET',
  2250. dataType: 'text',
  2251. data: '',
  2252. async: true,
  2253. success: function (data) {
  2254. inlineEditBox$Node.find('.inlineEditBox-cnt').html(data);
  2255. inlineEditBox$Node.find('.btn-save').show();
  2256. initDateTimePicker(inlineEditBox$Node);
  2257. inlineEditBox$Node.find('textarea').autosize();
  2258. var fld = inlineEditBox$Node.find('input[id^="f"]');
  2259. if (fld && !fld.hasClass('se_type-date')) {
  2260. fld.focus();
  2261. fld.keydown(function(event) {
  2262. if (event.which == 13) {
  2263. event.preventDefault();
  2264. inlineEditBox$Node.find('form').submit();
  2265. }
  2266. });
  2267. }
  2268. },
  2269. error: function (err) {
  2270. if (priv.options.debug) console.log('err');
  2271. }
  2272. });
  2273. } else {
  2274. if (priv.options.debug) console.log('NO data');
  2275. return false;
  2276. }
  2277. };
  2278. priv.ajaxLoadTypeSpeciallCell = function(id, col) {
  2279. if (_popoverCellAjaxXhr) {
  2280. _popoverCellAjaxXhr.abort();
  2281. }
  2282. var _popoverCellAjaxXhr = $.ajax({
  2283. type: 'GET',
  2284. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=TYPESPECIALL_CELL&ID=' + id + '&col=' + col,
  2285. dataType: 'json',
  2286. contentType: "application/json; charset=utf-8",
  2287. data: '',
  2288. success: function(req){
  2289. if (req.data && req.data.tbl_id > 0) {
  2290. var addHtml = '';
  2291. for(var i in req.data.items){
  2292. var url = 'index.php?MENU_INIT=VIEWTABLE_AJAX';
  2293. url += '&ZASOB_ID=' + req.data.tbl_id;
  2294. url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
  2295. url += '&_hash=' + Math.random().toString(36).substring(2);
  2296. addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
  2297. addHtml += '<br>';
  2298. }
  2299. _popoverCell.append(addHtml);
  2300. jQuery('#popoverCellContent').append(addHtml);
  2301. }
  2302. }
  2303. });
  2304. };
  2305. priv.popoverCell = function (e) {
  2306. e.preventDefault();
  2307. e.stopPropagation();
  2308. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  2309. var lastId = _popoverCell.data('rowid'),
  2310. lastCol = _popoverCell.data('col');
  2311. if (lastId == e.data.id && lastCol == e.data.col) {
  2312. //_popoverCellCurrent.popover('toggle');
  2313. }
  2314. else {
  2315. if (_popoverCellCurrent) {
  2316. _popoverCellCurrent.popover('destroy');
  2317. }
  2318. _popoverCell.data('rowid', e.data.id);
  2319. _popoverCell.data('col', e.data.col);
  2320. _popoverCell.html(e.data.value + '<div id="popoverCellContent" style="white-space:normal"></div>');
  2321. if (_data.cols[e.data.col]) {
  2322. if (_data.cols[e.data.col]._tsRetId > 0) {
  2323. priv.ajaxLoadTypeSpeciallCell(e.data.id, e.data.col);
  2324. }
  2325. }
  2326. _popoverCellCurrent = jQuery(e.currentTarget);
  2327. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  2328. var opts = {
  2329. placement: 'left'
  2330. , trigger: 'click'
  2331. // , title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>'
  2332. , title: '<div style="display:block;position:relative;padding:0 20px 0 0;">' + (e.data.friendly || e.data.col) + ' <button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:0;top:0;">&times;</button>' + '</div>'
  2333. , html: true
  2334. , content: _popoverCell.html()
  2335. }
  2336. _popoverCellCurrent.popover(opts);
  2337. _popoverCellCurrent.popover('show');
  2338. }
  2339. } else {
  2340. if (priv.options.debug) console.log('NO data');
  2341. return false;
  2342. }
  2343. return;
  2344. };
  2345. priv.routeChanged = function(e) {
  2346. hash = e.data.hash || '';
  2347. if (hash.length == 0) {
  2348. return;
  2349. }
  2350. if (hash.substring(0, 1) != '#') {
  2351. hash = '#' + hash;
  2352. }
  2353. location.hash = hash;
  2354. };
  2355. priv.refresh = function (e) {
  2356. e.preventDefault();
  2357. publ.loadPage(_state.page);
  2358. };
  2359. publ.init = function (options) {
  2360. if (priv.options.debug) console.log('TableAjax initialization...');
  2361. //merge supplied options with defaults
  2362. $.extend(priv.options, defaults, options);
  2363. priv.init();
  2364. return publ;
  2365. };
  2366. publ.refresh = function () {
  2367. publ.loadPage(_state.page);
  2368. };
  2369. publ.loadPage = function(page, pageSize) {
  2370. var skipCols = true, // skipCols = true - prevent columns delete
  2371. resetChecked = false;
  2372. var reqData = {
  2373. page: page,
  2374. pageSize: (pageSize || priv.options.pageSize),
  2375. currSortCol: (_state.filters.currSortCol || ''),
  2376. currSortFlip: _state.filters.currSortFlip ? "desc" : "asc"
  2377. };
  2378. if (Object.keys(_state.filters.filterCols).length > 0) {
  2379. $.each(_state.filters.filterCols, function (col, colProps) {
  2380. if (colProps.filter && colProps.filter.length > 0) {
  2381. reqData['f_' + col] = colProps.filter;
  2382. }
  2383. });
  2384. skipCols = true;
  2385. }
  2386. // specialFilters
  2387. $.each(_state.specialFilters, function(groupName, btnValue) {
  2388. if (btnValue.length > 0) {
  2389. reqData['sf_' + groupName] = btnValue;
  2390. }
  2391. });
  2392. if (priv.options.forceFilterInit) {
  2393. $.map(priv.options.forceFilterInit, function (fltrProps, fltr) {
  2394. reqData['f_' + fltr] = fltrProps;
  2395. filtersInitSet = true;
  2396. });
  2397. }
  2398. _uiNode$Table.parent().parent().addClass('AjaxTable-loading');
  2399. $.ajax({
  2400. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
  2401. type: 'GET',
  2402. dataType: 'json',
  2403. contentType: "application/json; charset=utf-8",
  2404. data: reqData,
  2405. async: true,
  2406. success: function (data) {
  2407. state = {data: {}};
  2408. state.data.rows = data.rows || [];
  2409. state.data.total = data.total || 0;
  2410. state.page = data.page || 0;
  2411. state.pageSize = data.pageSize || priv.options.pageSize;
  2412. state.filters = data.filters || {};
  2413. priv.setState(state);
  2414. _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
  2415. },
  2416. error: function (err) {
  2417. if (priv.options.debug) console.log('request error: {0}'.f(JSON.stringify(err)));
  2418. }
  2419. });
  2420. };
  2421. publ.getCurrentPage = function() {
  2422. return _state.page;
  2423. };
  2424. publ.popoverCellRemove = function () {
  2425. if (_popoverCellCurrent) {
  2426. _popoverCellCurrent.popover('destroy');
  2427. }
  2428. _popoverCell.data('rowid', -1);
  2429. _popoverCell.data('col', -1);
  2430. _popoverCell.html('');
  2431. };
  2432. return publ;
  2433. }
  2434. $.fn.TableAjax = function (options) {
  2435. options = options || {};
  2436. return this.each(function () {
  2437. options.id = this;
  2438. $(this).data('TableAjax', new TableAjax().init(options));
  2439. });
  2440. };
  2441. $.fn.TableAjaxLoadPage = function (page, pageSize) {
  2442. return this.each(function () {
  2443. var tblAjax = jQuery(this).data('TableAjax');
  2444. var curPage = page || tblAjax.getCurrentPage();
  2445. if (tblAjax) tblAjax.loadPage(curPage, pageSize);
  2446. });
  2447. };
  2448. $.fn.TableAjaxRefresh = function (page, pageSize) {
  2449. return this.each(function () {
  2450. var tblAjax = jQuery(this).data('TableAjax');
  2451. if (tblAjax) tblAjax.refresh();
  2452. });
  2453. };
  2454. String.prototype.format = String.prototype.f = function () {
  2455. var s = this;
  2456. i = arguments.length;
  2457. while (i--) s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
  2458. return s;
  2459. };
  2460. })(jQuery);
  2461. </script>
  2462. <?php
  2463. $filterInit = $this->_filterInit;
  2464. $forceFilterInit = $this->_forceFilterInit;
  2465. $pageSizes = $this->_pageSizes;
  2466. $pageSize = $this->_pageSize;
  2467. $rowFunctions = $this->_showRowFunctionsJson();
  2468. $exportFields = $this->_showExportFieldsJson();
  2469. ?>
  2470. <script>
  2471. jQuery(document).ready(function(){
  2472. jQuery('#<?php echo $this->_htmlID; ?>').TableAjax({
  2473. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>',
  2474. columnPicker: true,
  2475. filter: true,
  2476. filterInit: <?php echo json_encode($filterInit); ?>,
  2477. forceFilterInit: <?php echo json_encode($forceFilterInit); ?>,
  2478. debug: false,
  2479. height: 400,
  2480. sorting: true,
  2481. paging: true,
  2482. pageSize: <?php echo $pageSize; ?>,
  2483. pageSizes: <?php echo json_encode($pageSizes); ?>,
  2484. tblFunctions: {
  2485. shortdesc: {
  2486. icon: 'align-left',
  2487. title: 'Long desc',
  2488. method: 'longTextChanged'
  2489. },
  2490. <?php if ($hasGeomFlds) : ?>
  2491. mapeditor: {
  2492. icon: 'map-marker',
  2493. title: 'Mapa',
  2494. method: 'mapEditorChanged'
  2495. },
  2496. <?php endif; ?>
  2497. create: {
  2498. href: '#CREATE',
  2499. icon: 'plus',
  2500. title: 'Dodaj nowy rekord'
  2501. },
  2502. refresh: {
  2503. icon: 'refresh',
  2504. title: 'Odśwież dane',
  2505. method: 'refresh'
  2506. }
  2507. },
  2508. rowFunctions: <?php echo json_encode($rowFunctions); ?>,
  2509. exportFields: <?php echo json_encode($exportFields); ?>,
  2510. specialFilterFunctions: <?php
  2511. $fltrs = $this->_acl->getSpecialFilters();
  2512. if (!empty($fltrs)) {
  2513. echo json_encode($fltrs);
  2514. } else {
  2515. echo 'false';
  2516. }
  2517. echo ',';
  2518. ?>
  2519. router: function () {
  2520. var routes = {
  2521. EDIT: function (args) {
  2522. var recordID = args;
  2523. if (typeof args == 'object') {
  2524. recordID = args.shift();
  2525. recordID = parseInt(recordID);
  2526. }
  2527. if (typeof recordID !== 'number' || recordID <= 0) {
  2528. // TODO: msg
  2529. return false;
  2530. }
  2531. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2532. cont.hide();
  2533. // remove previous task content
  2534. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2535. taskCnt.parent().remove();
  2536. taskCnt.remove();
  2537. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2538. jQuery('<ul class="breadcrumb">' +
  2539. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2540. '<li class="active">Edytuj rekord</li>' +
  2541. '</ul>').appendTo(taskCont);
  2542. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2543. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2544. jQuery.ajax({
  2545. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT&ID=' + recordID,
  2546. type: 'GET',
  2547. dataType: 'text',
  2548. data: '',
  2549. async: true,
  2550. success: function (data) {
  2551. taskCnt.removeClass('AjaxTable-loading');
  2552. jQuery(data).appendTo(taskCnt);
  2553. initDateTimePicker(taskCnt);
  2554. },
  2555. error: function (err) {
  2556. taskCnt.removeClass('AjaxTable-loading');
  2557. //console.log('request error: {0}'.f(err));
  2558. }
  2559. });
  2560. //return false;
  2561. },
  2562. HIST: function (args) {
  2563. var recordID = args;
  2564. if (typeof args == 'object') {
  2565. recordID = args.shift();
  2566. recordID = parseInt(recordID);
  2567. }
  2568. if (typeof recordID !== 'number' || recordID <= 0) {
  2569. // TODO: msg
  2570. return false;
  2571. }
  2572. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2573. cont.hide();
  2574. // remove previous task content
  2575. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2576. taskCnt.parent().remove();
  2577. taskCnt.remove();
  2578. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2579. jQuery('<ul class="breadcrumb">' +
  2580. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2581. '<li class="active">Historia rekordu</li>' +
  2582. '</ul>').appendTo(taskCont);
  2583. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2584. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2585. jQuery.ajax({
  2586. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=HIST&ID=' + recordID,
  2587. type: 'GET',
  2588. dataType: 'text',
  2589. data: '',
  2590. async: true,
  2591. success: function (data) {
  2592. taskCnt.removeClass('AjaxTable-loading');
  2593. //console.log('request finished L.<?php echo __LINE__; ?>');
  2594. jQuery(data).appendTo(taskCnt);
  2595. },
  2596. error: function (err) {
  2597. taskCnt.removeClass('AjaxTable-loading');
  2598. //console.log('request error: {0}'.f(err));
  2599. }
  2600. });
  2601. //return false;
  2602. },
  2603. FILES: function tableAjaxFiles(args) {
  2604. var recordID = args;
  2605. if (typeof args == 'object') {
  2606. recordID = args.shift();
  2607. recordID = parseInt(recordID);
  2608. }
  2609. if (typeof recordID !== 'number' || recordID <= 0) {
  2610. // TODO: msg
  2611. return false;
  2612. }
  2613. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2614. cont.hide();
  2615. // remove previous task content
  2616. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2617. taskCnt.parent().remove();
  2618. taskCnt.remove();
  2619. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2620. jQuery('<ul class="breadcrumb">' +
  2621. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2622. '<li class="active">Pliki</li>' +
  2623. '</ul>').appendTo(taskCont);
  2624. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
  2625. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2626. jQuery.ajax({
  2627. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
  2628. type: 'GET',
  2629. dataType: 'text',
  2630. data: '',
  2631. async: true,
  2632. success: function (data) {
  2633. taskCnt.removeClass('AjaxTable-loading');
  2634. //console.log('request finished L.<?php echo __LINE__; ?>', data);
  2635. jQuery(data).appendTo(taskCnt);
  2636. },
  2637. error: function (jqXHR, textStatus, errorThrown) {
  2638. //console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
  2639. taskCnt.removeClass('AjaxTable-loading');
  2640. var txt = jqXHR.responseText || 'Error';
  2641. if (jqXHR.status == 404) {
  2642. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  2643. } else {
  2644. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  2645. }
  2646. }
  2647. });
  2648. //return false;
  2649. },
  2650. CREATE: function tableAjaxCreate() {
  2651. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2652. cont.hide();
  2653. // remove previous task content
  2654. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  2655. taskCnt.parent().remove();
  2656. taskCnt.remove();
  2657. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  2658. jQuery('<ul class="breadcrumb">' +
  2659. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  2660. '<li class="active">Dodaj nowy rekord</li>' +
  2661. '</ul>').appendTo(taskCont);
  2662. taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  2663. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  2664. var reqData = {};
  2665. var forceFilterInit = <?php echo json_encode($forceFilterInit);// TODO: read from TableAjax ?>;
  2666. if (forceFilterInit) {
  2667. $.map(forceFilterInit, function (fltrProps, fltr) {
  2668. reqData['ff_' + fltr] = fltrProps;
  2669. });
  2670. }
  2671. jQuery.ajax({
  2672. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE',
  2673. type: 'GET',
  2674. dataType: 'text',
  2675. data: reqData,
  2676. async: true,
  2677. success: function (data) {
  2678. taskCnt.removeClass('AjaxTable-loading');
  2679. //console.log('request finished L.<?php echo __LINE__; ?>');
  2680. jQuery(data).appendTo(taskCnt);
  2681. initDateTimePicker(taskCnt);
  2682. },
  2683. error: function (err) {
  2684. taskCnt.removeClass('AjaxTable-loading');
  2685. //console.log('request error: {0}'.f(err));
  2686. }
  2687. });
  2688. //return false;
  2689. }
  2690. };
  2691. var routePath = location.hash;
  2692. //console.log('location.hash: ' + routePath);
  2693. if (location.hash == '' || location.hash == '#') {
  2694. return false;
  2695. }
  2696. if (routePath.charAt(0) == '#') {
  2697. routePath = routePath.substr(1);
  2698. }
  2699. //console.log('routePath: ' + routePath);
  2700. var parts = routePath.split('/');
  2701. var task = parts.shift();
  2702. //console.log('task(' + task + ') parts:');
  2703. //console.log(parts);
  2704. if (task in routes && typeof routes[task] == 'function') {
  2705. routes[task](parts);
  2706. } else {
  2707. return false;
  2708. }
  2709. },
  2710. filtersClean: true,
  2711. longDesc: true
  2712. });
  2713. });
  2714. function tableAjaxBackToTable() {
  2715. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2716. cont.show();
  2717. var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
  2718. taskCont.remove();
  2719. // reload first page
  2720. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2721. con.TableAjaxLoadPage();// TODO: load current page
  2722. }
  2723. function tableAjaxCopy(args) {
  2724. var recordID = args;
  2725. if (typeof args == 'object') {
  2726. recordID = args.shift();
  2727. recordID = parseInt(recordID);
  2728. }
  2729. if (typeof recordID !== 'number' || recordID <= 0) {
  2730. // TODO: msg
  2731. return false;
  2732. }
  2733. if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
  2734. return false;
  2735. }
  2736. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  2737. function notifyAjaxCallback(data) {
  2738. var notify = {};
  2739. notify.type = (data && data.type)? data.type : '';
  2740. notify.msg = (data && data.msg)? data.msg : '';
  2741. switch (notify.type) {
  2742. case 'success':
  2743. if (!notify.msg) notify.msg = 'OK';
  2744. break;
  2745. case 'info':
  2746. if (!notify.msg) notify.msg = '';
  2747. break;
  2748. case 'error':
  2749. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2750. break;
  2751. case 'warning':
  2752. notify.type = 'warn';
  2753. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2754. break;
  2755. default:
  2756. notify.msg = 'Nieznany błąd';
  2757. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  2758. notify.type = '';
  2759. }
  2760. jQuery.notify(notify.msg, notify.type);
  2761. }
  2762. var reqData = {};
  2763. jQuery.ajax({
  2764. data: reqData,
  2765. dataType: 'json',
  2766. type: "GET",
  2767. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
  2768. })
  2769. .done(function(data, textStatus, jqXHR){
  2770. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2771. con.TableAjaxRefresh();
  2772. notifyAjaxCallback(data);
  2773. })
  2774. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  2775. if (jqXHR.responseJSON) {
  2776. notifyAjaxCallback(jqXHR.responseJSON);
  2777. }
  2778. else {
  2779. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  2780. if (jqXHR.status == 404) {
  2781. jQuery.notify(jqXHR.responseText, 'error');
  2782. } else {
  2783. jQuery.notify(jqXHR.responseText, 'warn');
  2784. }
  2785. }
  2786. });
  2787. return false;
  2788. }
  2789. function hidePopover() {
  2790. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  2791. if (con) {
  2792. var tblAjax = con.data('TableAjax');
  2793. if (tblAjax) {
  2794. tblAjax.popoverCellRemove();
  2795. }
  2796. }
  2797. return false;
  2798. }
  2799. function <?php echo $jsToogleFiltrProcesuFunctionName; ?>(n) {
  2800. var $n = jQuery(n);
  2801. var $ul = $n.next();
  2802. if ($n.data('fetched')) return false;
  2803. function parseProcesInitData(pInitData) {
  2804. var procesInitMapHtml = '';
  2805. if (!pInitData) {
  2806. return '<li><a href="#">' + "Brak danych" + '</a></li>';
  2807. } else {
  2808. function _viewProcesInitListItem(pInitId, gotoIds, pInitList) {
  2809. var label = pInitList[pInitId];
  2810. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + pInitId + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  2811. var out = '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + pInitId + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + pInitId + "} " + label + '">';
  2812. out += ' <i class="glyphicon glyphicon-info-sign"';
  2813. out += ' onclick="' + jsInfo + '"';
  2814. out += ' style="color:#aaa;"';
  2815. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  2816. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  2817. out += " {" + pInitId + "} " + label;
  2818. out += '</a>';
  2819. return out;
  2820. }
  2821. function _viewProcesGotoAndRetListItem(gotoId, pInitList) {
  2822. var label = pInitList[gotoId];
  2823. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + gotoId + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  2824. var out = '';
  2825. out += '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + gotoId + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + gotoId + "} " + label + '">';
  2826. out += ' <span style="padding:10px;"></span>';
  2827. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  2828. out += ' <i class="glyphicon glyphicon-info-sign"';
  2829. out += ' onclick="' + jsInfo + '"';
  2830. out += ' style="color:#aaa;"';
  2831. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  2832. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  2833. out += " {" + gotoId + "} " + label;
  2834. out += '</a>';
  2835. return out;
  2836. }
  2837. function _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitList) {
  2838. var label = pInitList[gotoLvl2Id];
  2839. var jsInfo = "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=" + gotoLvl2Id + "&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;";
  2840. var out = '';
  2841. out += '<a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=' + gotoLvl2Id + '&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="' + "{" + gotoLvl2Id + "} " + label + '">';
  2842. out += ' <span style="padding:20px;"></span>';
  2843. out += ' <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>';
  2844. out += ' <i class="glyphicon glyphicon-info-sign"';
  2845. out += ' onclick="' + jsInfo + '"';
  2846. out += ' style="color:#aaa;"';
  2847. out += ' onmouseover="' + "this.style.color='#337AB7'" + '"';
  2848. out += ' onmouseout="' + "this.style.color='#aaa'" + '"></i>';
  2849. out += " {" + gotoLvl2Id + "} " + label;
  2850. out += '</a>';
  2851. return out;
  2852. }
  2853. var sel = '',
  2854. liStyle = "white-space:nowrap; overflow:hidden; max-width:500px; /* text-overflow:ellipsis; */";
  2855. $.map(pInitData.mapTree, function(gotoIds, vInitId) {
  2856. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  2857. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  2858. procesInitMapHtml += _viewProcesInitListItem(vInitId, gotoIds, pInitData.pInitList);
  2859. procesInitMapHtml += '</li>' + "\n";
  2860. $.map(gotoIds, function(gotoLvl2Ids, gotoId) {
  2861. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  2862. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  2863. procesInitMapHtml += _viewProcesGotoAndRetListItem(gotoId, pInitData.pInitList);
  2864. procesInitMapHtml += '</li>' + "\n";
  2865. $.map(gotoLvl2Ids, function(vBool, gotoLvl2Id) {
  2866. sel = (pInitData.pInitListSelected && pInitData.pInitListSelected == vInitId)? ' class="disabled"' : '';
  2867. procesInitMapHtml += '<li' + sel + ' style="' + liStyle + '">';
  2868. procesInitMapHtml += _viewProcesGotoAndRetLvl2ListItem(gotoLvl2Id, pInitData.pInitList);
  2869. procesInitMapHtml += '</li>' + "\n";
  2870. });
  2871. });
  2872. });
  2873. }
  2874. return procesInitMapHtml;
  2875. }
  2876. jQuery.ajax({
  2877. data: null,
  2878. dataType: 'json',
  2879. type: "GET",
  2880. async: true,
  2881. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=PROCES_INIT_FILTR',
  2882. })
  2883. .always(function(data, textStatus, jqXHR) {
  2884. var type = data.type || null,
  2885. msg = data.msg || "Error",
  2886. pInitData = data.pInitData || null;
  2887. if (type) {
  2888. if ('success' == type) {
  2889. $ul.html(parseProcesInitData(pInitData));
  2890. } else if ('error' == type) {
  2891. $ul.html('<li><a href="#">' + msg + '</a></li>');
  2892. } else {
  2893. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  2894. }
  2895. } else {
  2896. $ul.html('<li><a href="#">Wystapił błąd podczas pobierania listy procesów</a></li>');
  2897. }
  2898. $n.data('fetched', true);
  2899. });
  2900. return false;
  2901. }
  2902. </script>
  2903. <?php
  2904. $out = ob_get_contents();
  2905. ob_end_clean();
  2906. return $out;
  2907. }
  2908. public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
  2909. $vLabel = $pInitList[$vInitId];
  2910. $kId = $vInitId;
  2911. ?>
  2912. <a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>">
  2913. <i class="glyphicon glyphicon-info-sign"
  2914. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  2915. style="color:#aaa;"
  2916. onmouseover="this.style.color='#337AB7'"
  2917. onmouseout="this.style.color='#aaa'"></i>
  2918. <?php echo "{{$kId}} {$vLabel}"; ?>
  2919. </a>
  2920. <?php
  2921. }
  2922. public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
  2923. $vLabel = $pInitList[$vGotoId];
  2924. $kId = $vGotoId;
  2925. // TODO:?: prevent to execute procedure
  2926. ?>
  2927. <a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>">
  2928. <span style="padding:10px;"></span>
  2929. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  2930. <i class="glyphicon glyphicon-info-sign"
  2931. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  2932. style="color:#aaa;"
  2933. onmouseover="this.style.color='#337AB7'"
  2934. onmouseout="this.style.color='#aaa'"></i>
  2935. <?php echo "{{$kId}} {$vLabel}"; ?>
  2936. </a>
  2937. <?php
  2938. }
  2939. public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
  2940. $vLabel = $pInitList[$vGotoLvl2Id];
  2941. $kId = $vGotoLvl2Id;
  2942. // TODO:?: prevent to execute procedure
  2943. ?>
  2944. <a href="index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces=<?php echo $kId; ?>&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID=<?php echo $this->_zasobID; ?>" title="<?php echo htmlspecialchars("{{$kId}} {$vLabel}"); ?>">
  2945. <span style="padding:20px;"></span>
  2946. <i class="glyphicon glyphicon-arrow-right" style="color:#aaa"></i>
  2947. <i class="glyphicon glyphicon-info-sign"
  2948. onclick="window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces=<?php echo $kId; ?>&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;"
  2949. style="color:#aaa;"
  2950. onmouseover="this.style.color='#337AB7'"
  2951. onmouseout="this.style.color='#aaa'"></i>
  2952. <?php echo "{{$kId}} {$vLabel}"; ?>
  2953. </a>
  2954. <?php
  2955. }
  2956. public function hasAdditionalLayers() {
  2957. $layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
  2958. return !empty($layers);
  2959. }
  2960. public function ajaxTask($task) {
  2961. switch ($task) {
  2962. case 'EDIT': {
  2963. $id = V::get('ID', 0, $_REQUEST, 'int');
  2964. if ($id > 0) {
  2965. $this->sendAjaxEdit($id, $_REQUEST);
  2966. } else {
  2967. echo '404';
  2968. }
  2969. break;
  2970. }
  2971. case 'EDIT_SAVE': {
  2972. $this->sendAjaxResponseJson('ajaxEditSave', $_REQUEST);
  2973. break;
  2974. }
  2975. case 'EDIT_INLINE': {
  2976. $id = V::get('ID', 0, $_REQUEST, 'int');
  2977. $col = V::get('col', '', $_REQUEST);
  2978. if ($id > 0 && !empty($col)) {
  2979. $this->sendAjaxEditInline($id, $col, $_REQUEST);
  2980. } else {
  2981. echo '404';
  2982. }
  2983. break;
  2984. }
  2985. case 'EDIT_INLINE_SAVE': {
  2986. $this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
  2987. break;
  2988. }
  2989. case 'COPY': {
  2990. $this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
  2991. break;
  2992. }
  2993. case 'CREATE': {
  2994. $this->sendAjaxCreate($_REQUEST);
  2995. break;
  2996. }
  2997. case 'CREATE_SAVE': {
  2998. $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
  2999. break;
  3000. }
  3001. case 'HIST': {
  3002. $id = V::get('ID', 0, $_REQUEST, 'int');
  3003. if ($id > 0) {
  3004. $this->sendAjaxHistory($id, $_REQUEST);
  3005. } else {
  3006. echo '404';
  3007. }
  3008. break;
  3009. }
  3010. case 'FILES': {
  3011. $id = V::get('ID', 0, $_REQUEST, 'int');
  3012. if ($id > 0) {
  3013. $this->sendAjaxFiles($id, $_REQUEST);
  3014. } else {
  3015. echo '404';
  3016. }
  3017. break;
  3018. }
  3019. case 'FILES_UPLOAD': {
  3020. $id = V::get('ID', 0, $_REQUEST, 'int');
  3021. if ($id > 0) {
  3022. $this->sendAjaxFilesUpload($id, $_REQUEST);
  3023. } else {
  3024. echo '404';
  3025. }
  3026. break;
  3027. }
  3028. case 'FILES_LIST': {
  3029. $id = V::get('ID', 0, $_REQUEST, 'int');
  3030. if ($id > 0) {
  3031. $this->sendAjaxFilesList($id, $_REQUEST);
  3032. } else {
  3033. echo '404';
  3034. }
  3035. break;
  3036. }
  3037. case 'FILE_REMOVE': {
  3038. $id = V::get('ID', 0, $_REQUEST, 'int');
  3039. if ($id > 0) {
  3040. $this->sendAjaxFileRemove($id, $_REQUEST);
  3041. } else {
  3042. echo '404';
  3043. }
  3044. break;
  3045. }
  3046. case 'filePermsRefresh': {
  3047. $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
  3048. break;
  3049. }
  3050. case 'FILES_CONN_TBL_LIST': {
  3051. $id = V::get('ID', 0, $_REQUEST, 'int');
  3052. if ($id > 0) {
  3053. $this->sendAjaxFilesConnTblList($id, $_REQUEST);
  3054. } else {
  3055. echo '404';
  3056. }
  3057. break;
  3058. }
  3059. case 'TYPESPECIAL': {
  3060. $fldID = V::get('fldID', 0, $_REQUEST, 'int');
  3061. if ($fldID > 0) {
  3062. $this->sendTypeSpecial($fldID, $_REQUEST);
  3063. } else {
  3064. echo '404';
  3065. }
  3066. break;
  3067. }
  3068. case 'TYPESPECIALL_CELL': {
  3069. $id = V::get('ID', 0, $_REQUEST, 'int');
  3070. $col = V::get('col', '', $_REQUEST);
  3071. if ($id > 0 && !empty($col)) {
  3072. $this->sendTypeSpecialCell($id, $col, $_REQUEST);
  3073. } else {
  3074. echo '404';
  3075. }
  3076. break;
  3077. }
  3078. case 'HIDDEN_COLS_SAVE': {
  3079. $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
  3080. break;
  3081. }
  3082. case 'PAGE_SIZE_SAVE': {
  3083. $this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
  3084. break;
  3085. }
  3086. case 'THE_GEOM_SAVE': {
  3087. $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
  3088. break;
  3089. }
  3090. case 'THE_GEOM_REMOVE': {
  3091. $this->sendAjaxResponseJson('ajaxTheGeomRemove', $_REQUEST);
  3092. break;
  3093. }
  3094. case 'PROCES_INIT_FILTR': {
  3095. $this->sendAjaxResponseJson('ajaxProcesInitFiltr', $_REQUEST);
  3096. break;
  3097. }
  3098. default:
  3099. $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
  3100. }
  3101. }
  3102. /**
  3103. * ajax url: &_task=EDIT_INLINE
  3104. * @param $rowID - $_GET['ID']
  3105. * @param $fieldName - $_GET['col']
  3106. */
  3107. private function sendAjaxEditInline($rowID, $fieldName, $args) {
  3108. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3109. header("Content-type: text/plain");
  3110. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3111. if (!$fieldID) {
  3112. echo "404: No field by name ({$fieldName})";
  3113. exit;
  3114. }
  3115. if ($DBG) echo "fieldID: {$fieldID}\n";
  3116. $row = $this->_acl->getItem($rowID);
  3117. if (!$row) {
  3118. echo "404: No item ID({$rowID})";
  3119. exit;
  3120. }
  3121. if (!$this->_acl->isAllowed($fieldID, 'R', $row)) {
  3122. if ($DBG) echo " R not allowed\n";
  3123. } else {
  3124. if ($DBG) echo " R allowed\n";
  3125. }
  3126. if (!$this->_acl->isAllowed($fieldID, 'W', $row)) {
  3127. if ($DBG) echo " W not allowed\n";
  3128. } else {
  3129. if ($DBG) echo " W allowed\n";
  3130. }
  3131. $fieldVal = '';
  3132. if ($this->_acl->isAllowed($fieldID, 'R', $row)) {
  3133. $fieldVal = V::get($fieldName, $fieldVal, $row);
  3134. } else {
  3135. $fieldVal = '*****';
  3136. }
  3137. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  3138. $vCol = $this->_acl->getField($fieldID);
  3139. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3140. $tsValues = array();
  3141. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  3142. if ($typeSpecial) {
  3143. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  3144. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $row->ID, $fieldName, V::get($fieldName, $fieldVal, $row));
  3145. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$fieldID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  3146. if (!empty($specialValues)) {
  3147. $tsValues[$row->ID] = implode('<br>', $specialValues);
  3148. }
  3149. }
  3150. ?>
  3151. <label for="<?php echo "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  3152. <strong title="<?php echo "[{$fieldID}] {$fieldName}"; ?>"><?php echo "{$vCol['label']}"; ?></strong>
  3153. <?php if (!empty($vCol['opis'])) : ?>
  3154. <em><?php echo $vCol['opis']; ?></em>
  3155. <?php $perms = $this->_acl->getFieldPerms($fieldID); SE_Layout::hotKeyDBG($perms); ?>
  3156. <?php endif; ?>
  3157. </label>
  3158. <?php
  3159. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  3160. if (!empty($tsValues[$row->ID])) {
  3161. $fieldParams['typespecialValue'] = $tsValues[$row->ID];
  3162. }
  3163. $vDefault = $this->_acl->getColDefault($fieldName);
  3164. if (!empty($vDefault)) {
  3165. $fieldParams['default'] = $vDefault;
  3166. }
  3167. echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $row);
  3168. if ($typeSpecial
  3169. || $this->_acl->isDateField($fieldName)
  3170. || $this->_acl->isDateTimeField($fieldName)
  3171. ) {
  3172. echo '<p style="padding:120px 0;"></p>';
  3173. }
  3174. exit;
  3175. }
  3176. private function ajaxEditInlineSave($args) {
  3177. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  3178. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  3179. $fieldName = V::get('col', '', $_REQUEST);
  3180. if (empty($primaryKey) || empty($fieldName)) {
  3181. throw new HttpException("Wrong param id or col!", 400);
  3182. }
  3183. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  3184. if (!$fieldID) {
  3185. throw new HttpException("Field not exists!", 404);
  3186. }
  3187. $item = $this->_acl->getItem($primaryKey);
  3188. if (!$item) {
  3189. throw new HttpException("Item not exists!", 404);
  3190. }
  3191. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3192. if (!isset($itemFromUser[$fieldName])) {
  3193. throw new HttpException("Field not set!", 400);
  3194. }
  3195. $itemPatch = array();
  3196. $itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
  3197. $itemPatch[$primaryKeyField] = $primaryKey;
  3198. $response = new stdClass();
  3199. try {
  3200. $affected = $this->_acl->updateItem($itemPatch);
  3201. if ($affected > 0) {
  3202. $response->type = 'success';
  3203. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  3204. } else if ($affected == 0) {
  3205. $response->type = 'info';
  3206. $response->msg = "Nie wprowadzono żadnych zmian";
  3207. }
  3208. $response->record = $this->_acl->getItem($primaryKey);
  3209. }
  3210. catch (Exception $e) {
  3211. $response->type = 'error';
  3212. $response->msg = $e->getMessage();
  3213. }
  3214. return $response;
  3215. }
  3216. private function sendAjaxEdit($id, $args) {
  3217. header("Content-type: text/plain");
  3218. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3219. $cols = array();
  3220. $record = $this->_acl->getItem($id);
  3221. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  3222. echo '<div class="alert alert-danger">';
  3223. echo "Brak dostępu do rekordu";// TODO: more info - reason
  3224. echo '</div>';
  3225. return;
  3226. }
  3227. $fieldsList = $this->_acl->getFields();
  3228. foreach ($fieldsList as $kID => $vCol) {
  3229. if ($vCol['name'] == 'ID') {
  3230. unset($fieldsList[$kID]);
  3231. continue;
  3232. }
  3233. $cols[$kID] = '';
  3234. if ($this->_acl->isAllowed($kID, 'R', $record)) {
  3235. $cols[$kID] = V::get($vCol['name'], '', $record);
  3236. } else {
  3237. $cols[$kID] = '*****';
  3238. }
  3239. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  3240. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : str_replace('_', ' ', $vCol['name']);
  3241. }
  3242. $tsValues = array();
  3243. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fieldsList (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fieldsList);echo'</pre>';}
  3244. if (!empty($fieldsList)) {
  3245. foreach ($fieldsList as $vColID => $vCol) {
  3246. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  3247. if ($typeSpecial) {
  3248. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  3249. $colValue = V::get($vCol['name'], '', $record);
  3250. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">V::get('.$vCol['name'].', "", $record) (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($colValue);echo'</pre>';}
  3251. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record->ID, $vCol['name'], $colValue);
  3252. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  3253. if (!empty($specialValues)) {
  3254. $tsValues[$vColID] = implode('<br>', $specialValues);
  3255. }
  3256. }
  3257. }
  3258. }
  3259. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">tsValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($tsValues);echo'</pre>';}
  3260. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('edit', 'cp'), true);
  3261. ?>
  3262. <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
  3263. <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?php echo $this->_htmlID; ?>">
  3264. <fieldset>
  3265. <legend>Edycja rekordu Nr <?php echo $record->ID; ?><span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span></legend>
  3266. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  3267. <?php if ($this->_acl->isAllowed($kID, 'W', $record)) : ?>
  3268. <div class="form-group">
  3269. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3270. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  3271. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3272. </label>
  3273. <div class="col-xs-12 col-sm-9 col-md-10">
  3274. <?php
  3275. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  3276. if (!empty($tsValues[$kID])) {
  3277. $fieldParams['typespecialValue'] = $tsValues[$kID];
  3278. }
  3279. echo $this->_acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
  3280. ?>
  3281. </div>
  3282. </div>
  3283. <?php elseif ($this->_acl->isAllowed($kID, 'R', $record)) : ?>
  3284. <div class="form-group">
  3285. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3286. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  3287. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3288. </label>
  3289. <div class="col-xs-12 col-sm-9 col-md-10">
  3290. <p style="margin-top:5px;">
  3291. <?php
  3292. //echo $this->_acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
  3293. if (!empty($tsValues[$kID])) {
  3294. echo $tsValues[$kID];
  3295. } else if (!empty($record->{$vCol['name']})) {
  3296. echo $record->{$vCol['name']};
  3297. }
  3298. ?>
  3299. </p>
  3300. </div>
  3301. </div>
  3302. <?php endif; ?>
  3303. <?php endforeach; ?>
  3304. <div class="form-group">
  3305. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  3306. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Zapisz</button>
  3307. </div>
  3308. </div>
  3309. </fieldset>
  3310. </form>
  3311. <p style="padding:100px 0;"></p>
  3312. </div>
  3313. <script>
  3314. jQuery(document).ready(function(){
  3315. jQuery('textarea').autosize();
  3316. jQuery('.frm-help').popover({trigger:'hover'});
  3317. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  3318. var data = jQuery(this).serialize();
  3319. // TODO: change Edit btn to return to edit record with fields -> show form
  3320. var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
  3321. //taskCont.empty();
  3322. taskCont.children().fadeOut('slow');
  3323. var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
  3324. , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
  3325. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> zapisywanie ... </div></div>').appendTo(alertCnt);
  3326. function notifyAjaxCallback(data) {
  3327. var notify = {}, outMsg = '';
  3328. notify.type = (data && data.type)? data.type : '';
  3329. notify.msg = (data && data.msg)? data.msg : '';
  3330. switch (notify.type) {
  3331. case 'success':
  3332. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  3333. break;
  3334. case 'info':
  3335. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  3336. break;
  3337. case 'error':
  3338. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3339. break;
  3340. case 'warning':
  3341. notify.type = 'warn';
  3342. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3343. break;
  3344. default:
  3345. notify.msg = 'Nieznany błąd';
  3346. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3347. notify.type = '';
  3348. }
  3349. jQuery.notify(notify.msg, notify.type);
  3350. var alertType = ('error' == notify.type) ? 'danger' : notify.type;
  3351. outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
  3352. return outMsg;
  3353. }
  3354. $.ajax({
  3355. data: data,
  3356. dataType: 'json',
  3357. type: "POST",
  3358. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=EDIT_SAVE&ID=<?php echo $record->ID; ?>',
  3359. })
  3360. .done(function(data, textStatus, jqXHR){
  3361. var outMsg = notifyAjaxCallback(data);
  3362. alertCntWrap.removeClass('AjaxTable-loading');
  3363. //console.log('request finished L.<?php echo __LINE__; ?>');
  3364. alertCnt.empty();
  3365. var out = '';
  3366. out += outMsg;
  3367. out += '<div class="breadcrumb">' +
  3368. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  3369. ' <a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord <?php echo $id; ?></a>' +
  3370. '</div>';
  3371. jQuery(out).appendTo(alertCnt);
  3372. })
  3373. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  3374. if (jqXHR.responseJSON) {
  3375. notifyAjaxCallback(jqXHR.responseJSON);
  3376. }
  3377. else {
  3378. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  3379. if (jqXHR.status == 404) {
  3380. jQuery.notify(jqXHR.responseText, 'error');
  3381. } else {
  3382. jQuery.notify(jqXHR.responseText, 'warn');
  3383. }
  3384. }
  3385. alertCntWrap.removeClass('AjaxTable-loading');
  3386. //console.log('Request Error: {0}: {1}'.f(textStatus, errorThrown));
  3387. alertCnt.empty();
  3388. jQuery(errorTxt).appendTo(alertCnt);
  3389. var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
  3390. jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
  3391. var backToEditBtn = jQuery('<a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-small"> <i class="icon-pencil"></i> Popraw dane <?php echo $id; ?></a>').appendTo(errLinks);
  3392. backToEditBtn.on('click', function(){
  3393. alertCnt.remove();
  3394. taskCont.children().fadeIn('slow');
  3395. return false;
  3396. });
  3397. });
  3398. return false;
  3399. });
  3400. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
  3401. var input, btn, btnIco;
  3402. input = jQuery(e.target);
  3403. btn = input.next('.button-appendBack');
  3404. btnIco = btn.find('.glyphicon');
  3405. //console.log('title',btn.attr('title'),'val',input.val(),'input', input, 'btn', btn);
  3406. if (btn.attr('title') != input.val()) {
  3407. btnIco.show();
  3408. } else {
  3409. btnIco.hide();
  3410. }
  3411. });
  3412. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value').find('.button-appendBack').on('click', function(e) {
  3413. var input, btn, btnIco;
  3414. btn = jQuery(this);
  3415. btnIco = btn.find('.glyphicon');
  3416. input = btn.prev();
  3417. //console.log('title',btn.attr('title'),'val',input.val(),'input', input, 'btn', btn);
  3418. if (input.is('input')) {
  3419. if (btn.attr('title') != input.val()) {
  3420. input.val(btn.attr('title'));
  3421. btnIco.hide();
  3422. }
  3423. }
  3424. });
  3425. });
  3426. </script>
  3427. <?php
  3428. exit;
  3429. }
  3430. private function ajaxEditSave($args) {
  3431. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  3432. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  3433. if (empty($primaryKey)) {
  3434. throw new HttpException("Wrong param id!", 400);
  3435. }
  3436. $item = $this->_acl->getItem($primaryKey);
  3437. if (!$item) {
  3438. throw new HttpException("Item not exists!", 404);
  3439. }
  3440. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3441. $response = new stdClass();
  3442. try {
  3443. $itemFromUser[$primaryKeyField] = $primaryKey;
  3444. $affected = $this->_acl->updateItem($itemFromUser);
  3445. if ($affected > 0) {
  3446. $response->type = 'success';
  3447. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  3448. } else if ($affected == 0) {
  3449. $response->type = 'info';
  3450. $response->msg = "Nie wprowadzono żadnych zmian";
  3451. }
  3452. $response->record = $this->_acl->getItem($primaryKey);
  3453. }
  3454. catch (Exception $e) {
  3455. $response->type = 'error';
  3456. $response->msg = "Wystąpiły błędy!";
  3457. $response->msg .= $e->getMessage();
  3458. }
  3459. return $response;
  3460. }
  3461. private function sendAjaxCreate($args) {
  3462. header("Content-type: text/plain");
  3463. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3464. if (!$this->_acl->hasCreatePerms()) {
  3465. ?>
  3466. <div class="container">
  3467. <div class="alert alert-danger">
  3468. Brak uprawnień do utworzenia nowego rekordu.
  3469. </div>
  3470. </div>
  3471. <?php
  3472. return;
  3473. }
  3474. $cols = array();
  3475. $forceFilterInit = array();
  3476. $defaultAclGroup = User::getDefaultAclGroup();
  3477. if ($defaultAclGroup) {
  3478. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  3479. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  3480. }
  3481. foreach ($_GET as $k => $v) {
  3482. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  3483. $fldName = substr($k, 3);
  3484. $forceFilterInit[$fldName] = $v;
  3485. }
  3486. }
  3487. $fieldsList = $this->_acl->getFields();
  3488. foreach ($fieldsList as $kID => $vCol) {
  3489. $defaultValue = '';
  3490. if ($vCol['name'] == 'ID') {
  3491. unset($fieldsList[$kID]);
  3492. continue;
  3493. }
  3494. if (!empty($forceFilterInit[$vCol['name']])) {
  3495. $defaultValue = $forceFilterInit[$vCol['name']];
  3496. }
  3497. // TODO: read from session cache
  3498. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  3499. $fieldsList[$kID]['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  3500. }
  3501. ?>
  3502. <div class="container AjaxFrmHorizontalEdit">
  3503. <form class="form-horizontal" action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
  3504. <fieldset>
  3505. <legend>Dodaj nowy rekord</legend>
  3506. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  3507. <?php if ($this->_acl->isAllowed($kID, 'C')) : ?>
  3508. <div class="form-group">
  3509. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?php echo "f{$kID}"; ?>"><?php echo $vCol['label']; ?>
  3510. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars($vCol['opis']); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  3511. <?php $perms = $this->_acl->getFieldPerms($kID); SE_Layout::hotKeyDBG($perms); ?>
  3512. </label>
  3513. <div class="col-xs-12 col-sm-9 col-md-10">
  3514. <?php
  3515. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  3516. echo $this->_acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
  3517. ?>
  3518. </div>
  3519. </div>
  3520. <?php endif; ?>
  3521. <?php endforeach; ?>
  3522. <div class="form-group">
  3523. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  3524. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
  3525. </div>
  3526. </div>
  3527. </fieldset>
  3528. </form>
  3529. </div>
  3530. <script>
  3531. jQuery(document).ready(function(){
  3532. jQuery('textarea').autosize();
  3533. jQuery('.frm-help').popover({trigger:'hover'});
  3534. jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  3535. var data = jQuery(this).serialize();
  3536. var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
  3537. taskCont = taskContLast.parent();
  3538. taskContLast.fadeOut('slow');
  3539. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  3540. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> save ... </div></div>').appendTo(taskCnt);
  3541. function notifyAjaxCallback(data) {
  3542. var notify = {};
  3543. notify.type = (data && data.type)? data.type : '';
  3544. notify.msg = (data && data.msg)? data.msg : '';
  3545. switch (notify.type) {
  3546. case 'success':
  3547. if (!notify.msg) notify.msg = 'OK';
  3548. break;
  3549. case 'info':
  3550. if (!notify.msg) notify.msg = '';
  3551. break;
  3552. case 'error':
  3553. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3554. break;
  3555. case 'warning':
  3556. notify.type = 'warn';
  3557. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  3558. break;
  3559. default:
  3560. notify.msg = 'Nieznany błąd';
  3561. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  3562. notify.type = '';
  3563. }
  3564. jQuery.notify(notify.msg, notify.type);
  3565. }
  3566. $.ajax({
  3567. data: data,
  3568. dataType: 'json',
  3569. type: "POST",
  3570. async: true,
  3571. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
  3572. })
  3573. .always(function(dataOrJqXHR){
  3574. var data;
  3575. if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
  3576. if ('responseJSON' in dataOrJqXHR) {
  3577. data = dataOrJqXHR.responseJSON;
  3578. } else {
  3579. data = {};
  3580. data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
  3581. if (dataOrJqXHR.status == 404) {
  3582. data.type = 'error';
  3583. } else {
  3584. data.type = 'warning';
  3585. }
  3586. }
  3587. }
  3588. else {
  3589. data = dataOrJqXHR;
  3590. }
  3591. notifyAjaxCallback(data);
  3592. taskCnt.removeClass('AjaxTable-loading');
  3593. taskCnt.empty();
  3594. if (data.type == 'error' || data.type == 'warning') {
  3595. var out = '<div class="container">' +
  3596. '<div class="alert alert-danger">' +
  3597. '<h4>Wystąpiły błędy!</h4>' + data.msg +
  3598. (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
  3599. '</div>';
  3600. out += '<div class="breadcrumb">' +
  3601. ' <a class="create-fix" href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do formularza i popraw dane</a></li>' +
  3602. '</div>' +
  3603. '</div>';
  3604. jQuery(out).appendTo(taskCnt);
  3605. var taskContLastNode = taskContLast
  3606. , taskCntNode = taskCnt;
  3607. taskCnt.find('.create-fix').click(function(){
  3608. taskCntNode.remove();
  3609. taskContLastNode.fadeIn('slow');
  3610. return false;
  3611. });
  3612. }
  3613. else if (data.type == 'success') {
  3614. var msg = '';
  3615. if (data.id && data.id > 0) {
  3616. msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
  3617. } else if (data.msg) {
  3618. msg = data.msg;
  3619. } else {
  3620. msg = 'OK';
  3621. }
  3622. var out = '<div class="container">';
  3623. out += '<div class="alert alert-success">' + msg + '</div>';
  3624. out += '<div class="breadcrumb">' +
  3625. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  3626. ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
  3627. ' <a href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-plus"></i> Dodaj nowy rekord</a></li>' +
  3628. '</div>';
  3629. out += '</div>';
  3630. jQuery(out).appendTo(taskCnt);
  3631. }
  3632. });
  3633. return false;
  3634. });
  3635. });
  3636. </script>
  3637. <?php
  3638. exit;
  3639. }
  3640. private function ajaxCreateSave($args) {
  3641. $response = new stdClass();
  3642. $createdId = null;
  3643. try {
  3644. $item = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  3645. $createdId = $this->_acl->addItem($item);
  3646. if ($createdId) {
  3647. $response->type = 'success';
  3648. $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
  3649. $response->id = $createdId;
  3650. $response->record = $this->_acl->getItem($createdId);
  3651. }
  3652. else {
  3653. $response->type = 'error';
  3654. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  3655. }
  3656. }
  3657. catch (Exception $e) {
  3658. $response->type = 'error';
  3659. $response->msg = "Wystąpiły błędy!";
  3660. $response->msg = $e->getMessage();
  3661. }
  3662. return $response;
  3663. }
  3664. private function ajaxCopy($args) {
  3665. $id = V::get('ID', 0, $_REQUEST, 'int');
  3666. if ($id <= 0) {
  3667. throw new HttpException("Wrong param ID!", 404);
  3668. }
  3669. $item = $this->_acl->getItem($id);
  3670. if (!$item) {
  3671. throw new HttpException("Item '{$id}' not exists!", 404);
  3672. }
  3673. $response = new stdClass();
  3674. $itemCopy = $this->_acl->createItemCopy($item);
  3675. $createdId = null;
  3676. try {
  3677. $createdId = $this->_acl->addItem($itemCopy);
  3678. if ($createdId) {
  3679. $response->type = 'success';
  3680. $response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
  3681. $response->id = $createdId;
  3682. $response->record = $this->_acl->getItem($createdId);
  3683. }
  3684. else {
  3685. $response->type = 'error';
  3686. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  3687. }
  3688. }
  3689. catch (Exception $e) {
  3690. $response->type = 'error';
  3691. $response->msg = "Wystąpiły błędy!";
  3692. $response->msg = $e->getMessage();
  3693. }
  3694. return $response;
  3695. }
  3696. private function sendAjaxHistory($id, $args) {
  3697. header("Content-type: text/plain");
  3698. $record = $this->_acl->getItem($id);
  3699. if (!$record) {
  3700. header('HTTP/1.0 404 Not Found');
  3701. echo "404: No item ID({$rowID})";
  3702. exit;
  3703. }
  3704. $visibleCols = $this->_acl->getRealFieldList();
  3705. $rowsHist = $this->_acl->getHistItems($id);
  3706. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('hist', 'cp'), true);
  3707. $visibleColsWithIds = array();
  3708. $visibleColsLabels = array();
  3709. foreach ($visibleCols as $vColName) {
  3710. $fldId = $this->_acl->getFieldIdByName($vColName);
  3711. if ($fldId) {
  3712. $visibleColsWithIds[$fldId] = $vColName;
  3713. $label = $this->_acl->getFieldLabel($fldId);
  3714. $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
  3715. $visibleColsLabels[$fldId] = $label;
  3716. }
  3717. }
  3718. ?>
  3719. <fieldset>
  3720. <legend>Historia rekordu Nr <?php echo $id; ?>
  3721. <span class="pull-right valign-btns-bottom"><?php echo $rowFunctionsOut; ?></span>
  3722. </legend>
  3723. </fieldset>
  3724. <?php if (empty($rowsHist)) : ?>
  3725. <div class="alert alert-info">
  3726. <h4>Brak danych</h4>
  3727. </div>
  3728. <?php else: ?>
  3729. <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
  3730. <thead>
  3731. <tr>
  3732. <th>Data</th>
  3733. <th>User</th>
  3734. <th>Zmiany</th>
  3735. </tr>
  3736. </thead>
  3737. <tbody>
  3738. <?php foreach ($rowsHist as $row) : ?>
  3739. <tr>
  3740. <td style="white-space:nowrap"><?php echo $row->_created; ?></td>
  3741. <td><?php echo $row->_author; ?></td>
  3742. <td>
  3743. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  3744. <?php if (in_array($colName, array('ID', 'A_RECORD_UPDATE_DATE', 'A_RECORD_UPDATE_AUTHOR', 'A_RECORD_CREATE_DATE', 'A_RECORD_CREATE_AUTHOR'))) continue; ?>
  3745. <?php if ($row->$colName == 'N/S;') continue; ?>
  3746. <p><em><?php echo $visibleColsLabels[$fldId]; ?></em>:
  3747. <?php if ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
  3748. <?php echo $row->$colName; ?>
  3749. <?php else : ?>
  3750. <span title="Brak uprawnień do odczytu tego pola">*****</span>
  3751. <?php endif; ?>
  3752. </p>
  3753. <?php endforeach; ?>
  3754. </td>
  3755. </tr>
  3756. <?php endforeach; ?>
  3757. </tbody>
  3758. </table>
  3759. <div style="overflow-x:scroll; overflow-y:visible; padding-bottom:1px; margin:10px 0;">
  3760. <table class="table table-striped table-hover table-bordered table-condensed AjaxTableHist">
  3761. <thead>
  3762. <tr>
  3763. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  3764. <th><?php echo str_replace('_', ' ', $visibleColsLabels[$fldId]); ?></th>
  3765. <?php endforeach; ?>
  3766. </tr>
  3767. </thead>
  3768. <tbody>
  3769. <?php foreach ($rowsHist as $row) : ?>
  3770. <tr>
  3771. <?php foreach ($visibleColsWithIds as $fldId => $colName) : ?>
  3772. <td>
  3773. <?php if ($row->$colName == 'N/S;') : ?>
  3774. <em>N/S;</em>
  3775. <?php elseif ($this->_acl->isAllowed($fldId, 'R', $record)) : ?>
  3776. <?php echo $row->$colName; ?>
  3777. <?php else : ?>
  3778. <span title="Brak uprawnień do odczytu tego pola">*****</span>
  3779. <?php endif; ?>
  3780. </td>
  3781. <?php endforeach; ?>
  3782. </tr>
  3783. <?php endforeach; ?>
  3784. </tbody>
  3785. </table>
  3786. </div>
  3787. <?php endif; ?>
  3788. <?php
  3789. exit;
  3790. }
  3791. /**
  3792. * Returns text/plain with type at first line: ERROR, WARNING, INFO, SUCCESS
  3793. */
  3794. private function sendAjaxFilesUpload($id, $args) {
  3795. // http://www.sitepoint.com/html5-ajax-file-upload/
  3796. //$ajaxFileName = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
  3797. //header("Content-type: text/plain");
  3798. header("Content-type: application/json");
  3799. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3800. $dbID = $this->_acl->getDB();
  3801. $db = DB::getDB($dbID);
  3802. if (!$db) {
  3803. header('HTTP/1.0 406 Not Acceptable');
  3804. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  3805. exit;
  3806. }
  3807. $record = $this->_acl->getItem($id);
  3808. if (!$record) {
  3809. header('HTTP/1.0 404 Not Found');
  3810. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  3811. exit;
  3812. }
  3813. $tblName = $this->_acl->getName();
  3814. $confTblName = "{$tblName}_COLUMN";
  3815. $folderConfAll = FoldersConfig::getRawData();
  3816. if (!FoldersConfig::hasConfig($confTblName)) {
  3817. header('HTTP/1.0 404 Not Found');
  3818. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych(' . $tblName . ')"}';
  3819. exit;
  3820. }
  3821. $folderConf = FoldersConfig::getAll($confTblName);
  3822. $uploader = new FileUploader($confTblName, $record);
  3823. $errMsg = '';
  3824. if (!$uploader->setConfig($folderConf, $errMsg)) {
  3825. header('HTTP/1.0 404 Not Found');
  3826. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych(' . $tblName . ') <br>' . $errMsg . '"}';
  3827. exit;
  3828. }
  3829. $uploader->findFolder();
  3830. $errorMsg = '';
  3831. if (!empty($_POST['SCANS_COLUMN_ADD'])) {
  3832. $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  3833. }
  3834. else {
  3835. $uploaded = $uploader->tryUploadAjax($errorMsg);
  3836. }
  3837. if ($uploaded) {
  3838. $uploadedFileName = '';
  3839. $uploadedFile = $uploader->getLastUploadedFile();
  3840. if ($uploadedFile) {
  3841. $uploadedFileName = explode('/', $uploadedFile);
  3842. $uploadedFileName = end($uploadedFileName);
  3843. }
  3844. echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
  3845. if (!empty($uploadedFileName)) {
  3846. $sqlObj = new stdClass();
  3847. $sqlObj->ID = $record->ID;
  3848. $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
  3849. $db->UPDATE_OBJ($this->_tbl, $sqlObj);
  3850. }
  3851. } else {
  3852. echo '{"type":"ERROR", "string": "' . $errorMsg . '"}';
  3853. }
  3854. exit;
  3855. }
  3856. private function sendAjaxFileRemove($id, $args) {
  3857. header("Content-type: application/json");
  3858. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  3859. if (empty($_POST['filename'])) {
  3860. echo '{"type":"ERROR", "string": "Nie wybrano pliku do usunięcia"}';
  3861. exit;
  3862. }
  3863. $dbID = $this->_acl->getDB();
  3864. $db = DB::getDB($dbID);
  3865. if (!$db) {
  3866. header('HTTP/1.0 406 Not Acceptable');
  3867. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  3868. exit;
  3869. }
  3870. $record = $this->_acl->getItem($id);
  3871. if (!$record) {
  3872. header('HTTP/1.0 404 Not Found');
  3873. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  3874. exit;
  3875. }
  3876. $tblName = $this->_acl->getName();
  3877. $confTblName = "{$tblName}_COLUMN";
  3878. $folderConfAll = FoldersConfig::getRawData();
  3879. if (!FoldersConfig::hasConfig($confTblName)) {
  3880. header('HTTP/1.0 404 Not Found');
  3881. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  3882. exit;
  3883. }
  3884. $folderConf = FoldersConfig::getAll($confTblName);
  3885. $uploader = new FileUploader($confTblName, $record);
  3886. if (!$uploader->setConfig($folderConf)) {
  3887. header('HTTP/1.0 404 Not Found');
  3888. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  3889. exit;
  3890. }
  3891. $uploader->findFolder();
  3892. $errorMsg = '';
  3893. $removed = $uploader->tryRemoveFromAjax($_POST['filename'], $errorMsg);
  3894. if (!$removed) {
  3895. echo '{"type":"ERROR", "string": "{' . $errorMsg . '}"}';
  3896. } else {
  3897. echo '{"type":"SUCCESS","string":"Plik został poprawnie usunięty"}';
  3898. }
  3899. exit;
  3900. }
  3901. private function sendAjaxFilesList($id, $args) {
  3902. header("Content-type: application/json");
  3903. $dbID = $this->_acl->getDB();
  3904. $db = DB::getDB($dbID);
  3905. if (!$db) {
  3906. header('HTTP/1.0 406 Not Acceptable');
  3907. echo '{"type":"ERROR", "string": "No DB (' . $dbID . ')"}';
  3908. exit;
  3909. }
  3910. $record = $this->_acl->getItem($id);
  3911. if (!$record) {
  3912. header('HTTP/1.0 404 Not Found');
  3913. echo '{"type":"ERROR", "string": "No item ID(' . $rowID . ')"}';
  3914. exit;
  3915. }
  3916. $tblName = $this->_acl->getName();
  3917. $confTblName = "{$tblName}_COLUMN";
  3918. $folderConfAll = FoldersConfig::getRawData();
  3919. if (!FoldersConfig::hasConfig($confTblName)) {
  3920. header('HTTP/1.0 404 Not Found');
  3921. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  3922. exit;
  3923. }
  3924. $folderConf = FoldersConfig::getAll($confTblName);
  3925. $uploader = new FileUploader($confTblName, $record);
  3926. if (!$uploader->setConfig($folderConf)) {
  3927. header('HTTP/1.0 404 Not Found');
  3928. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  3929. exit;
  3930. }
  3931. $uploader->findFolder();
  3932. $mainFolder = $uploader->getDestFolder();
  3933. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  3934. $localPath = $uploader->getLocalPath();
  3935. $folderWeb = $uploader->getFolderWeb();
  3936. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  3937. echo json_encode($jsonFiles);
  3938. exit;
  3939. }
  3940. private function ajaxFilePermsRefresh($args) {
  3941. header("Content-type: application/json");
  3942. $id = V::get('ID', 0, $args, 'int');
  3943. if ($id <= 0) throw new HttpException("Wrong param ID", 404);
  3944. $dbID = $this->_acl->getDB();
  3945. $db = DB::getDB($dbID);
  3946. if (!$db) throw new HttpException("No DB", 406);
  3947. $record = $this->_acl->getItem($id);
  3948. if (!$record) throw new Exception("No item ID({$rowID})", 404);
  3949. $tblName = $this->_acl->getName();
  3950. // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
  3951. $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
  3952. $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
  3953. $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
  3954. $mainDB = DB::getDB();
  3955. if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
  3956. $sql = "insert into `_SYNC_FILE_PERMS` (
  3957. `ID_PROJECT`,
  3958. `A_SYNCHRONIZED`
  3959. )
  3960. values (
  3961. '{$record->ID}'
  3962. , 0
  3963. )
  3964. ON DUPLICATE KEY UPDATE
  3965. `A_SYNCHRONIZED`=0
  3966. ";
  3967. }
  3968. else if ('IN7_DZIENNIK_KORESP' == $tblName) {
  3969. $sql = "insert into `_SYNC_FILE_PERMS` (
  3970. `ID_PROJECT`,
  3971. `A_SYNCHRONIZED`
  3972. )
  3973. values (
  3974. '{$record->ID_PROJECT}'
  3975. , 0
  3976. )
  3977. ON DUPLICATE KEY UPDATE
  3978. `A_SYNCHRONIZED`=0
  3979. ";
  3980. }
  3981. else {
  3982. $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
  3983. `TBL_NAME`,
  3984. `TBL_ID`,
  3985. `L_APPOITMENT_USER`,
  3986. `A_ADM_COMPANY`,
  3987. `A_CLASSIFIED`,
  3988. `A_SYNCHRONIZED`
  3989. )
  3990. values (
  3991. '{$tblName}'
  3992. , '{$id}'
  3993. , '{$sql_L_APPOITMENT_USER}'
  3994. , '{$sql_A_ADM_COMPANY}'
  3995. , '{$sql_A_CLASSIFIED}'
  3996. , 0
  3997. )
  3998. ON DUPLICATE KEY UPDATE
  3999. `A_SYNCHRONIZED`=0
  4000. ";
  4001. }
  4002. $res = $mainDB->query($sql);
  4003. if ($mainDB->has_errors()) {
  4004. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
  4005. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainDB->get_errors());echo'</pre>';
  4006. throw new Exception("Nie udało się dodać zadania");
  4007. }
  4008. // TODO: this blocks browser ajax query
  4009. //$limit = 3;
  4010. //while ($limit--) {
  4011. // sleep(10);
  4012. // TODO: check if task is done
  4013. //}
  4014. $confTblName = "{$tblName}_COLUMN";
  4015. $folderConfAll = FoldersConfig::getRawData();
  4016. if (!FoldersConfig::hasConfig($confTblName)) {
  4017. throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
  4018. }
  4019. $folderConf = FoldersConfig::getAll($confTblName);
  4020. $uploader = new FileUploader($confTblName, $record);
  4021. if (!$uploader->setConfig($folderConf)) {
  4022. throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
  4023. }
  4024. $uploader->findFolder();
  4025. $mainFolder = $uploader->getDestFolder();
  4026. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4027. $localPath = $uploader->getLocalPath();
  4028. $folderWeb = $uploader->getFolderWeb();
  4029. $jsonData = new stdClass();
  4030. $jsonData->msg = 'Zadanie dodane';
  4031. $jsonData->type = 'success';
  4032. $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4033. return $jsonData;
  4034. }
  4035. private function sendAjaxFilesConnTblList($id, $args) {
  4036. header("Content-type: application/json");
  4037. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4038. $dbID = $this->_acl->getDB();
  4039. $db = DB::getDB($dbID);
  4040. if (!$db) {
  4041. header('HTTP/1.0 406 Not Acceptable');
  4042. echo 'No DB (' . $dbID . ')';
  4043. exit;
  4044. }
  4045. $record = $this->_acl->getItem($id);
  4046. if (!$record) {
  4047. header('HTTP/1.0 404 Not Found');
  4048. echo 'No item ID(' . $rowID . ')';
  4049. exit;
  4050. }
  4051. $connTblName = '';
  4052. $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
  4053. if ($connTblID <= 0) {
  4054. header('HTTP/1.0 406 Not Acceptable');
  4055. echo 'No conn Table ID';
  4056. exit;
  4057. }
  4058. $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
  4059. if (empty($connTblTypespecials)) {
  4060. header('HTTP/1.0 406 Not Acceptable');
  4061. echo "No conn Table (ID={$connTblID})";
  4062. exit;
  4063. }
  4064. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">connTblTypespecials (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($connTblTypespecials);echo'</pre>';}
  4065. if(1) {
  4066. header('HTTP/1.0 404 Not Found');
  4067. echo 'TODO: ...';
  4068. exit;
  4069. }
  4070. $tblName = $this->_acl->getName();
  4071. $confTblName = "{$tblName}_COLUMN";
  4072. $folderConfAll = FoldersConfig::getRawData();
  4073. if (!FoldersConfig::hasConfig($confTblName)) {
  4074. header('HTTP/1.0 404 Not Found');
  4075. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  4076. exit;
  4077. }
  4078. $folderConf = FoldersConfig::getAll($confTblName);
  4079. $uploader = new FileUploader($confTblName, $record);
  4080. if (!$uploader->setConfig($folderConf)) {
  4081. header('HTTP/1.0 404 Not Found');
  4082. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  4083. exit;
  4084. }
  4085. $uploader->findFolder();
  4086. $mainFolder = $uploader->getDestFolder();
  4087. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4088. $localPath = $uploader->getLocalPath();
  4089. $folderWeb = $uploader->getFolderWeb();
  4090. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4091. echo json_encode($jsonFiles);
  4092. exit;
  4093. }
  4094. public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
  4095. $jsonFiles = array();
  4096. if (!is_array($files) || empty($files)) {
  4097. return $jsonFiles;
  4098. }
  4099. sort($files);
  4100. foreach ($files as $vFilePath) {
  4101. $file = new stdClass();
  4102. $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
  4103. //$file->name = explode('/', $vFilePath);
  4104. //$file->name = end($file->name);
  4105. $file->size = filesize($vFilePath);
  4106. $file->sizeStr = round($file->size, 2) . "B";
  4107. if ($file->size > 1024 * 1024) {
  4108. $file->sizeStr = round(($file->size / (1024 * 1024)), 2) . "M";
  4109. } else if ($file->size > 1024) {
  4110. $file->sizeStr = round(($file->size / 1024), 2) . "K";
  4111. }
  4112. $file->type = '';
  4113. $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
  4114. $file->web = str_replace($localPath, $folderWeb, $vFilePath);
  4115. $jsonFiles[] = $file;
  4116. }
  4117. return $jsonFiles;
  4118. }
  4119. private function getConnectedTables() {
  4120. $connTbls = array();
  4121. return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
  4122. $fields = $this->_acl->getVisibleFieldList();
  4123. if (!empty($fields)) {
  4124. foreach ($fields as $vColID => $vCol) {
  4125. $typeSpecial = Typespecial::getInstance($vColID);
  4126. if ($typeSpecial) {
  4127. $tsConnTbls = $typeSpecial->getTblAliasList();
  4128. if (!empty($tsConnTbls)) {
  4129. foreach ($tsConnTbls as $kID => $vName) {
  4130. $connTbls[$kID] = $vName;
  4131. }
  4132. }
  4133. }
  4134. }
  4135. }
  4136. return $connTbls;
  4137. }
  4138. private function getConnectedTblTypespecials($connTblID) {
  4139. $connTblTypespecials = array();
  4140. $fields = $this->_acl->getVisibleFieldList();
  4141. if (!empty($fields)) {
  4142. foreach ($fields as $vColID => $vCol) {
  4143. $typeSpecial = Typespecial::getInstance($vColID);
  4144. if ($typeSpecial) {
  4145. $tsConnTbls = $typeSpecial->getTblAliasList();
  4146. if (array_key_exists($connTblID, $tsConnTbls)) {
  4147. $connTblTypespecials[] = $typeSpecial;
  4148. }
  4149. }
  4150. }
  4151. }
  4152. return $connTblTypespecials;
  4153. }
  4154. private function sendAjaxFiles($id, $args) {
  4155. header("Content-type: text/plain");
  4156. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4157. $dbID = $this->_acl->getDB();
  4158. $db = DB::getDB($dbID);
  4159. if (!$db) {
  4160. header('HTTP/1.0 406 Not Acceptable');
  4161. exit;
  4162. }
  4163. $record = $this->_acl->getItem($id);
  4164. if (!$record) {
  4165. header('HTTP/1.0 404 Not Found');
  4166. echo "404: No item ID({$rowID})";
  4167. exit;
  4168. }
  4169. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  4170. echo '<div class="alert alert-danger">';
  4171. echo "Brak dostępu do rekordu";// TODO: more info - reason
  4172. echo '</div>';
  4173. return;
  4174. }
  4175. $tblName = $this->_acl->getName();
  4176. $confTblName = "{$tblName}_COLUMN";
  4177. $folderConfAll = FoldersConfig::getRawData();
  4178. if (!FoldersConfig::hasConfig($confTblName)) {
  4179. header('HTTP/1.0 404 Not Found');
  4180. echo "Brak danych konfiguracyjnych";
  4181. exit;
  4182. }
  4183. $folderConf = FoldersConfig::getAll($confTblName);
  4184. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
  4185. $uploader = new FileUploader($confTblName, $record);
  4186. $errMsg = '';
  4187. if (!$uploader->setConfig($folderConf, $errMsg)) {
  4188. header('HTTP/1.0 404 Not Found');
  4189. echo "Błąd danych konfiguracyjnych ({$tblName})";
  4190. echo '<br>' . "\n" . $errMsg;
  4191. exit;
  4192. }
  4193. $uploader->findFolder();
  4194. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">uploader (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($uploader);echo'</pre>'; }
  4195. $mainFolder = $uploader->getDestFolder();
  4196. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">mainFolder (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainFolder);echo'</pre>'; }
  4197. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  4198. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">files (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($files);echo'</pre>'; }
  4199. $sharePoint = V::get('share_point', null, $folderConf);
  4200. if ($sharePoint) {
  4201. $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
  4202. }
  4203. $localPath = $uploader->getLocalPath();
  4204. $folderWeb = $uploader->getFolderWeb();
  4205. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  4206. if($DBG){ echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">jsonFiles (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonFiles);echo'</pre>'; }
  4207. $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
  4208. $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
  4209. $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
  4210. $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
  4211. $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
  4212. sort($skanyFiles);
  4213. $fileTypes = FoldersConfig::getAll('m_dist_files_types');
  4214. $rowFunctionsOut = $this->_showRowFunctions($record->ID, array('files', 'cp'), true);
  4215. $fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
  4216. $fileIndex = V::get($fileIndexField, $record->ID, $record);
  4217. ?>
  4218. <script src="stuff/jquery.form.js"></script>
  4219. <div class="container">
  4220. <h4 style="margin:20px 0 3px 0;">Pliki w katalogu
  4221. <?php if ($sharePoint) : ?>
  4222. <a href="<?php echo $sharePoint; ?>"><span class="glyphicon glyphicon-folder-open"></span><code><?php echo $mainFolder; ?></code></a>
  4223. <?php else : ?>
  4224. <code><?php echo $mainFolder; ?></code>
  4225. <?php endif; ?>
  4226. <span class="pull-right valign-btns-bottom">
  4227. <span id="FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>"></span>
  4228. <?php echo $rowFunctionsOut; ?>
  4229. </span>
  4230. </h4>
  4231. <div style="clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">
  4232. <table class="table table-bordered table-hover">
  4233. <colgroup>
  4234. <col style="">
  4235. <col style="width:30px;">
  4236. <?php if ($sharePoint) : ?>
  4237. <col style="width:30px;">
  4238. <?php endif; ?>
  4239. <col style="width:80px;">
  4240. <col style="width:140px;">
  4241. </colgroup>
  4242. <tbody id="FILES_LIST_<?php echo $this->_htmlID; ?>">
  4243. <?php if (empty($mainFolder)) : ?>
  4244. <tr>
  4245. <td colspan="5">
  4246. <div class="alert alert-warning">
  4247. <h4>Brak folderu!</h4>
  4248. Folder dla tego rekordu nie został utworzony.
  4249. </div>
  4250. </td>
  4251. </tr>
  4252. <?php elseif (empty($files)) : ?>
  4253. <tr>
  4254. <td colspan="5">
  4255. <div class="alert alert-info">
  4256. <h4>Brak plików</h4>
  4257. </div>
  4258. </td>
  4259. </tr>
  4260. <?php endif; ?>
  4261. </tbody>
  4262. </table>
  4263. </div>
  4264. <br>
  4265. <br>
  4266. <div id="FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>"></div>
  4267. <form enctype="multipart/form-data" method="POST" action="" id="FILES_FRM_<?php echo $this->_htmlID; ?>" class="form-inline">
  4268. <input type="hidden" name="M_DIST_UPLOAD_SOURCE" value="local">
  4269. <ul id="FILES_TAB_<?php echo $this->_htmlID; ?>" class="nav nav-tabs" style="margin:0;">
  4270. <li class="active"><a href="#local" data-toggle="local">Wybierz plik lokalny</a></li>
  4271. <li><a href="#scan" data-toggle="scan">Wybierz plik ze skanów</a></li>
  4272. </ul>
  4273. <div id="myTabContent" class="tab-content">
  4274. <div class="tab-pane fade in active" id="local" style="text-align: center;">
  4275. <input name="M_DIST_FILES_NAME" type="file" size="60" class="field-upload btn" style="width:86%;margin:10px auto;padding:10px 4%;background:#eee;text-align:center;" ondragover="this.style.backgroundColor='#D9EDF7'" ondragleave="this.style.backgroundColor='#eee'" ondragend="this.style.backgroundColor='#eee'">
  4276. </div>
  4277. <div class="tab-pane fade" id="scan">
  4278. <?php if (empty($skanyFiles)) : ?>
  4279. <div class="alert alert-info">
  4280. <h4>Brak plików</h4>
  4281. <?php if(!empty($skanyFolderWeb)) echo "skonfiguruj urządzenie biurowe aby wysyłało skany na ftp://skaner:(h*a*s*l*o)@".$_SERVER['SERVER_NAME']." <br> lub <a href=".FoldersConfig::getNfsOsPath().$skanySharePoint.">".FoldersConfig::getNfsOsPath().$skanySharePoint."</a>"; ?>
  4282. </div>
  4283. <?php else : ?>
  4284. <div style="max-height:150px; overflow:auto; border-bottom:1px solid #ddd;">
  4285. <table class="table table-bordered table-hover">
  4286. <colgroup>
  4287. <col style="width:30px;">
  4288. <col style="">
  4289. <col style="width:30px;">
  4290. <col style="width:80px;">
  4291. <col style="width:140px;">
  4292. </colgroup>
  4293. <tbody>
  4294. <?php foreach ($skanyFiles as $vFilePath) : ?>
  4295. <tr>
  4296. <?php
  4297. $vFileName = explode('/', $vFilePath);
  4298. $vFileName = end($vFileName);
  4299. $vFileSize = filesize($vFilePath);
  4300. $vFileSizeOut = round($vFileSize, 2) . "B";
  4301. if ($vFileSize > 1024 * 1024) {
  4302. $vFileSizeOut = round(($vFileSize / (1024 * 1024)), 2) . "M";
  4303. } else if ($vFileSize > 1024) {
  4304. $vFileSizeOut = round(($vFileSize / 1024), 0) . "K";
  4305. }
  4306. ?>
  4307. <td><input style="margin:0;" type="radio" name="SCANS_COLUMN_ADD" value="<?php echo $vFileName; ?>"></td>
  4308. <td><div style="overflow:hidden; white-space:nowrap;" title="<?php echo $vFileName; ?>"><?php echo $vFileName; ?></div></td>
  4309. <td style="white-space:nowrap; text-align:center;"><a href="<?php echo str_replace($skanyLocalPath, $skanyFolderWeb, $vFilePath); ?>" target="_blank" class="glyphicon glyphicon-download-alt"></a></td>
  4310. <td style="white-space:nowrap;"><?php echo $vFileSizeOut; ?></td>
  4311. <td style="white-space:nowrap;"><?php echo date("Y-m-d H:i:s", filectime($vFilePath)); ?></td>
  4312. </tr>
  4313. <?php endforeach; ?>
  4314. </tbody>
  4315. </table>
  4316. </div>
  4317. <?php endif; ?>
  4318. </div>
  4319. </div>
  4320. <br>
  4321. <h4>Ustal nazwę pliku zgodną z obiegiem dokumentów
  4322. <?php //TODO: link do procesu o obiegu dokumentów <i class="glyphicon glyphicon-question-sign" style="cursor:help" title="działa w nowszych przeglądarkach jak Firefox, Chrome"></i> ?>
  4323. </h4>
  4324. <table style="width:100%" class="table table-bordered">
  4325. <tr>
  4326. <th>Nr</th>
  4327. <th>Typ</th>
  4328. <th style="width:40%;">Opis <i class="glyphicon glyphicon-question-sign" title="kogo dotyczy / czego / sprawa / nazwa_firmy itp"></i></th>
  4329. <th style="width:16%">Data wersji</th>
  4330. <th style="width:12%">Numer wersji</th>
  4331. </tr>
  4332. <tr>
  4333. <td>
  4334. <?php echo $fileIndex; ?>
  4335. </td>
  4336. <td>
  4337. <select class="form-control" name="M_DIST_FILES_TYPE">
  4338. <?php foreach ($fileTypes as $kType => $vLabel) : ?>
  4339. <option value="<?php echo $kType; ?>"<?php if ($kType == 'TODO') { echo ' selected="selected"'; } ?> ><?php echo $vLabel; ?></option>
  4340. <?php endforeach; ?>
  4341. </select>
  4342. <br>
  4343. <label class="checkbox">
  4344. <input type="checkbox" name="M_DIST_FILES_TYPE_AUTO">
  4345. Wykrycie automatyczne typu z wysylanego pliku
  4346. </label>
  4347. <label class="checkbox">
  4348. <input type="checkbox" name="M_DIST_FILES_TEMP">
  4349. Plik tymczasowy / roboczy / nieoficjalny (_TEMP)
  4350. </label>
  4351. </td>
  4352. <td>
  4353. <input class="form-control" style="width:100%" type="text" name="M_DIST_FILES_DESCRIPTION" value="" maxlength="50">
  4354. <br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>
  4355. </td>
  4356. <td>
  4357. <div class="input-group">
  4358. <input name="M_DIST_FILES_DATE" type="text" value="<?php echo date('Y-m-d');?>" class="se_type-date form-control" data-format="yyyy-MM-dd" maxlength="10"><span class="input-group-addon">
  4359. <span class="glyphicon glyphicon-calendar"></span>
  4360. </span>
  4361. </div>
  4362. <!--
  4363. <input class="form-control" type="date" name="M_DIST_FILES_DATE" value="<?php echo date('Y-m-d');?>" maxlength="10">
  4364. -->
  4365. <br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (<?php echo date('Y-m-d');?>)</label>
  4366. </td>
  4367. <td>
  4368. <input class="form-control" style="width:100%" type="number" name="M_DIST_FILES_VERSION">
  4369. <br>
  4370. <label class="checkbox">
  4371. <input type="checkbox" name="M_DIST_FILES_VERSION_AUTO">
  4372. Automatycznie dodaj wersje
  4373. </label>
  4374. </td>
  4375. </tr>
  4376. <tr>
  4377. <td colspan="5">
  4378. <div id="FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>"></div>
  4379. <p>
  4380. <input type="submit" value="Wyślij" class="btn btn-primary"> wybrany plik do folderu:
  4381. </p>
  4382. <p>
  4383. <code><b><?php echo $uploader->getDestPathShare(true); ?></b></code>
  4384. <br><i style="color:#777">(Jeśli folder nie istnieje to zostanie utworzony automatycznie)</i>
  4385. </p>
  4386. </td>
  4387. </tr>
  4388. </table>
  4389. </form>
  4390. </div>
  4391. <script>
  4392. function fileListUpdateAjax<?php echo $this->_htmlID; ?>() {
  4393. var postData = {};
  4394. jQuery.ajax({
  4395. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_LIST&ID=<?php echo $record->ID; ?>',
  4396. type: 'POST',
  4397. //dataType: 'json',
  4398. //contentType: "application/json; charset=utf-8",
  4399. data: postData,
  4400. async: true,
  4401. success: function (data) {
  4402. fileListUpdate<?php echo $this->_htmlID; ?>(data);
  4403. },
  4404. error: function (jhr, textStatus, errorThrown) {
  4405. if (priv.options.debug) console.log('request error: ', errorThrown, ' textStatus: ', textStatus);
  4406. }
  4407. });
  4408. }
  4409. function fileListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  4410. var fileListNode = jQuery('#FILES_LIST_<?php echo $this->_htmlID; ?>');
  4411. fileListNode.empty();
  4412. fileListJson.map(function(file){
  4413. var node = $('<tr></tr>');
  4414. var fFun = $('<i class="glyphicon glyphicon-remove" style="cursor:pointer" data-filename="' + file.name + '"></i>');
  4415. var fNameCell = $('<td style="overflow: hidden;"></td>');
  4416. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  4417. fName.append(fFun);
  4418. fName.append(file.name);
  4419. fName.appendTo(fNameCell);
  4420. node.append(fNameCell);
  4421. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="glyphicon glyphicon-download-alt"></a>' + '</td>');
  4422. <?php if ($sharePoint) : ?>
  4423. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="<?php echo $sharePoint; ?>/' + file.name + '" target="_blank" class="glyphicon glyphicon-folder-open"></a>' + '</td>');
  4424. <?php endif; ?>
  4425. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  4426. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  4427. node.appendTo(fileListNode);
  4428. $(fFun).click(function(e){
  4429. var n = $(e.target);
  4430. var fname= n.data('filename');
  4431. if (!fname) {
  4432. return false;
  4433. }
  4434. if (confirm('Czy jesteś pewien, że chcesz usunąć plik o nazwie ' + fname + '?')) {
  4435. var postData = {filename: fname};
  4436. jQuery.ajax({
  4437. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILE_REMOVE&ID=<?php echo $record->ID; ?>',
  4438. type: 'POST',
  4439. //dataType: 'json',
  4440. //contentType: "application/json; charset=utf-8",
  4441. data: postData,
  4442. async: true,
  4443. success: function (data) {
  4444. if (data && data.type) {
  4445. if (data.type == 'SUCCESS') {
  4446. n.parents('tr').remove();
  4447. //console.log('TODO: SUCCESS msg: ', data.string);
  4448. }
  4449. else if (data.type == 'ERROR') {
  4450. //console.log('TODO: ERROR msg: ', data.string);
  4451. }
  4452. } else {
  4453. if (priv.options.debug) console.log('TODO: ??? data: ', data);
  4454. }
  4455. },
  4456. error: function (jhr, textStatus, errorThrown) {
  4457. if (priv.options.debug) console.log('rm error: ', errorThrown, ' textStatus: ', textStatus);
  4458. }
  4459. });
  4460. }
  4461. });
  4462. });
  4463. }
  4464. function connTblListUpdateAjax<?php echo $this->_htmlID; ?>(connTblID) {
  4465. var postData = {};
  4466. // clear current file list
  4467. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').empty();
  4468. jQuery.ajax({
  4469. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_CONN_TBL_LIST&ID=<?php echo $record->ID; ?>&connTblID=' + connTblID,
  4470. type: 'POST',
  4471. //dataType: 'json',
  4472. //contentType: "application/json; charset=utf-8",
  4473. data: postData,
  4474. async: true,
  4475. success: function (data) {
  4476. connTblListUpdate<?php echo $this->_htmlID; ?>(data);
  4477. },
  4478. error: function (jqXHR, textStatus, errorThrown) {
  4479. var txt = jqXHR.responseText || 'Error';
  4480. jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list').html('<tr><td colspan="6"><div class="alert alert-danger">' + txt + '</div></td></tr>');
  4481. if (priv.options.debug) console.log('connTblListUpdateAjax error: ', errorThrown, ' textStatus: ', textStatus);
  4482. }
  4483. });
  4484. }
  4485. function connTblListUpdate<?php echo $this->_htmlID; ?>(fileListJson) {
  4486. var fileListNode = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>').find('.files-list');
  4487. fileListNode.empty();
  4488. fileListJson.map(function(file){
  4489. var node = $('<tr></tr>');
  4490. var fNameCell = $('<td style="overflow: hidden;"></td>');
  4491. var fName = $('<div style="overflow:hidden; white-space:nowrap;" title="' + file.name + '"></div>');
  4492. fName.append(file.name);
  4493. fName.appendTo(fNameCell);
  4494. node.append(fNameCell);
  4495. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:center;">' + '<a href="' + file.web + '" target="_blank" class="glyphicon glyphicon-download-alt"></a>' + '</td>');
  4496. node.append('<td style="overflow:hidden; white-space:nowrap; text-align:right;">' + file.sizeStr + '</td>');
  4497. node.append('<td style="overflow:hidden; white-space:nowrap;">' + file.created + '</td>');
  4498. node.appendTo(fileListNode);
  4499. });
  4500. }
  4501. function fileListActions<?php echo $this->_htmlID; ?>() {
  4502. var filePermsReload = jQuery('#FILES_LIST_ACTIONS_<?php echo $this->_htmlID; ?>');
  4503. var btnReload = jQuery('<button class="btn-link btn-sm" title="odśwież uprawnienia do plików"><span class="glyphicon glyphicon-refresh"></span>Odśwież</button>');
  4504. btnReload.on('click', function(e) {
  4505. console.log('TODO: click reload perms...');
  4506. function notifyAjaxCallback(data) {
  4507. var notify = {};
  4508. notify.type = (data && data.type)? data.type : '';
  4509. notify.msg = (data && data.msg)? data.msg : '';
  4510. switch (notify.type) {
  4511. case 'success':
  4512. if (!notify.msg) notify.msg = 'OK';
  4513. break;
  4514. case 'info':
  4515. if (!notify.msg) notify.msg = '';
  4516. break;
  4517. case 'error':
  4518. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4519. break;
  4520. case 'warning':
  4521. notify.type = 'warn';
  4522. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  4523. break;
  4524. default:
  4525. notify.msg = 'Nieznany błąd';
  4526. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  4527. notify.type = '';
  4528. }
  4529. jQuery.notify(notify.msg, notify.type);
  4530. }
  4531. var reqData = {};
  4532. jQuery.ajax({
  4533. data: reqData,
  4534. dataType: 'json',
  4535. type: "GET",
  4536. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=filePermsRefresh&ID=<?php echo $record->ID; ?>',
  4537. })
  4538. .done(function(data, textStatus, jqXHR){
  4539. notifyAjaxCallback(data);
  4540. if (data && data.files) {
  4541. fileListUpdate<?php echo $this->_htmlID; ?>(data.files);
  4542. }
  4543. })
  4544. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  4545. if (jqXHR.responseJSON) {
  4546. notifyAjaxCallback(jqXHR.responseJSON);
  4547. }
  4548. else {
  4549. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  4550. if (jqXHR.status == 404) {
  4551. jQuery.notify(jqXHR.responseText, 'error');
  4552. } else {
  4553. jQuery.notify(jqXHR.responseText, 'warn');
  4554. }
  4555. }
  4556. });
  4557. });
  4558. filePermsReload.append(btnReload);
  4559. }
  4560. jQuery(document).ready(function(){
  4561. $('#FILES_TAB_<?php echo $this->_htmlID; ?> a').click(function (e) {
  4562. e.preventDefault();
  4563. $(this).tab('show');
  4564. })
  4565. .on('shown.bs.tab', function (e) {
  4566. var fileSource = $(e.target).data('toggle')
  4567. , frm = jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').get(0);
  4568. if (frm['M_DIST_UPLOAD_SOURCE']) {
  4569. frm['M_DIST_UPLOAD_SOURCE'].value = fileSource;
  4570. }
  4571. })
  4572. jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>').ajaxForm({
  4573. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES_UPLOAD&ID=<?php echo $record->ID; ?>',
  4574. beforeSubmit: function(args, $form, options) {
  4575. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit()...');
  4576. var argsMap = [];
  4577. args.map(function(v, k) {
  4578. argsMap[v.name] = v.value;
  4579. });
  4580. // validate
  4581. if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'local') {
  4582. if (!argsMap['M_DIST_FILES_NAME']) {
  4583. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=local && !M_DIST_FILES_NAME');
  4584. return false;
  4585. }
  4586. }
  4587. else if (argsMap['M_DIST_UPLOAD_SOURCE'] == 'scan') {
  4588. if (!argsMap['SCANS_COLUMN_ADD']) {
  4589. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->beforeSubmit() M_DIST_UPLOAD_SOURCE=scan && !SCANS_COLUMN_ADD');
  4590. return false;
  4591. }
  4592. }
  4593. else {
  4594. return false;
  4595. }
  4596. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  4597. $out.html('Wysyłanie...');
  4598. },
  4599. success: function(data) {
  4600. //console.log('#FILES_FRM_<?php echo $this->_htmlID; ?>.ajaxForm->success()...');
  4601. var $out = $('#FRM_UPLOAD_RESULTS_<?php echo $this->_htmlID; ?>');
  4602. var btnClose = '<button type="button" class="close" data-dismiss="alert"><i class="glyphicon glyphicon-remove"></i></button>';
  4603. if (typeof data == 'object') {
  4604. if (data.type == 'ERROR') {
  4605. $out.html('<div class="alert alert-danger">' + btnClose + data.string + '</div>');
  4606. } else if (data.type == 'SUCCESS') {
  4607. $out.html('<div class="alert alert-success">' + btnClose + data.string + '</div>');
  4608. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  4609. }
  4610. } else {
  4611. if (data.substr(0, 7) == 'WARNING') {
  4612. data = data.substr(7);
  4613. $out.html('<div class="alert alert-warning">' + btnClose + data + '</div>');
  4614. } else if (data.substr(0, 5) == 'ERROR') {
  4615. data = data.substr(5);
  4616. $out.html('<div class="alert alert-danger">' + btnClose + data + '</div>');
  4617. } else if (data.substr(0, 7) == 'SUCCESS') {
  4618. data = data.substr(7);
  4619. $out.html('<div class="alert alert-success">' + btnClose + data + '</div>');
  4620. fileListUpdateAjax<?php echo $this->_htmlID; ?>();
  4621. } else if (data.substr(0, 4) == 'INFO') {
  4622. data = data.substr(4);
  4623. $out.html('<div class="alert alert-info">' + btnClose + data + '</div>');
  4624. }
  4625. }
  4626. }
  4627. });
  4628. fileListActions<?php echo $this->_htmlID; ?>();
  4629. var fileList = <?php echo json_encode($jsonFiles); ?>;
  4630. fileListUpdate<?php echo $this->_htmlID; ?>(fileList);
  4631. var connTbls = <?php echo json_encode($this->getConnectedTables()); ?>;
  4632. if (connTbls) {
  4633. var connTblsOut = '';
  4634. for(var key in connTbls) {
  4635. connTblsOut += '<button class="btn btn-sm btn-default conn-tbl-load" data-zasobid="' + key + '">' + connTbls[key] + '</button>';
  4636. };
  4637. if (connTblsOut) {
  4638. connTblsOut = 'Pliki w powiązanych tabelach: <div class="btn-group">' + connTblsOut + '</div>';
  4639. connTblsOut += '<div style="max-height:180px; overflow:auto; border-bottom:1px solid #ddd;">' +
  4640. '<table class="table table-bordered table-hover">' +
  4641. '<colgroup>' +
  4642. '<col style="">' +
  4643. '<col style="width:30px;">' +
  4644. <?php if ($sharePoint) : ?>
  4645. '<col style="width:30px;">' +
  4646. <?php endif; ?>
  4647. '<col style="width:80px;">' +
  4648. '<col style="width:140px;">' +
  4649. '</colgroup>' +
  4650. '<tbody class="files-list">' +
  4651. '</tbody>' +
  4652. '</table>' +
  4653. '</div>';
  4654. var _connTblsWrap = jQuery('#FILES_CONN_TBLS_<?php echo $this->_htmlID; ?>');
  4655. _connTblsWrap.css('marginBottom', '26px');
  4656. _connTblsWrap.html(connTblsOut);
  4657. _connTblsWrap.find('.conn-tbl-load').each(function(){
  4658. jQuery(this).click(function(e){
  4659. var tblID = jQuery(e.target).data('zasobid');
  4660. if (tblID) {
  4661. connTblListUpdateAjax<?php echo $this->_htmlID; ?>(tblID);
  4662. }// TODO: else show error
  4663. });
  4664. });
  4665. }
  4666. }
  4667. initDateTimePicker(jQuery('#FILES_FRM_<?php echo $this->_htmlID; ?>'));
  4668. });
  4669. </script>
  4670. <?php
  4671. exit;
  4672. }
  4673. private function sendTypeSpecial($fldID, $args) {
  4674. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4675. header("Content-type: application/json");
  4676. $fldName = '';
  4677. $fld = $this->_acl->getField($fldID);
  4678. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fld('.$fldID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fld);echo'</pre>';}
  4679. if (!$fld) {
  4680. // 404
  4681. } else {
  4682. $fldName = $fld['name'];
  4683. }
  4684. $jsonData = array();
  4685. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  4686. if ($typeSpecial) {
  4687. $query = V::get('q', '', $_REQUEST);
  4688. $rawRows = null;
  4689. $rows = $typeSpecial->getValuesWithExports($query);
  4690. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">rows('.$query.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($rows);echo'</pre>';}
  4691. foreach ($rows as $kID => $vItem) {
  4692. $itemJson = new stdClass();
  4693. $itemJson->id = $vItem->id;
  4694. $itemJson->name = $vItem->param_out;
  4695. if (!empty($vItem->exports)) {
  4696. $itemJson->exports = $vItem->exports;
  4697. }
  4698. $jsonData[] = $itemJson;
  4699. }
  4700. }
  4701. /*
  4702. MENU_INIT:VIEWTABLE_AJAX
  4703. ZASOB_ID:1188
  4704. _task:TYPESPECIAL
  4705. fldID:3866
  4706. Form Dataview sourceview URL encoded
  4707. q:te
  4708. */
  4709. echo json_encode($jsonData);
  4710. exit;
  4711. }
  4712. private function sendTypeSpecialCell($id, $fldName, $args) {
  4713. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4714. header("Content-type: application/json");
  4715. $jsonData = new stdClass();
  4716. $fldID = $this->_acl->getFieldIdByName($fldName);
  4717. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">fld('.$fldName.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($fldID);echo'</pre>';}
  4718. $item = $this->_acl->getItem($id);
  4719. if (!$this->_acl->isAllowed($fldID, 'R', $item)) {
  4720. $jsonData->msg = 'Brak dostępu';
  4721. echo json_encode($jsonData);
  4722. exit;
  4723. }
  4724. if (!$fldID) {
  4725. $jsonData->msg = 'Wrong field';
  4726. echo json_encode($jsonData);
  4727. exit;
  4728. }
  4729. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  4730. if ($typeSpecial) {
  4731. $jsonData->data = $typeSpecial->getReturnData($this->_zasobID, $id, $fldName, '');
  4732. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">specialValuesByIds('.$id.'/'.$fldName.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValuesByIds);echo'</pre>';}
  4733. }
  4734. echo json_encode($jsonData);
  4735. exit;
  4736. }
  4737. private function ajaxData($args) {
  4738. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  4739. $pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
  4740. $page = V::get('page', 0, $args, 'int');
  4741. $currSortCol = V::get('currSortCol', '', $args);
  4742. $currSortFlip = V::get('currSortFlip', '', $args);
  4743. if ($page > 0) {
  4744. $page -= 1;
  4745. }
  4746. else {
  4747. }
  4748. $params = array();
  4749. $params['limit'] = $pageSize;
  4750. $params['limitstart'] = $page * $params['limit'];
  4751. $params['order_by'] = ($currSortCol)? $currSortCol : '';
  4752. $params['order_dir'] = $currSortFlip;
  4753. $filters = new stdClass();
  4754. $filters->currSortCol = $currSortCol;
  4755. $filters->currSortFlip = $currSortFlip;
  4756. foreach ($args as $k => $v) {
  4757. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  4758. $params[$k] = $v;
  4759. $filters->{$k} = $v;
  4760. }
  4761. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  4762. $params[$k] = $v;
  4763. $filters->{$k} = $v;
  4764. }
  4765. }
  4766. $this->setFilters($filters);
  4767. $vCols = $this->_acl->getVirtualFieldList();
  4768. if (!empty($vCols)) {
  4769. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">vCols (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vCols);echo'</pre>';}
  4770. }
  4771. $visibleCols = $this->_acl->getVisibleFieldList();
  4772. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">visibleCols (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($visibleCols);echo'</pre>';}
  4773. $jsonData = new stdClass();
  4774. $jsonData->page = $page + 1;
  4775. $jsonData->pageSize = $pageSize;
  4776. $jsonData->filters = $filters;
  4777. $jsonData->cols = new stdClass();
  4778. $ind = 0;
  4779. foreach ($visibleCols as $fieldID => $col) {
  4780. $ind++;
  4781. $columnConfig = (object)array('index'=>$ind);
  4782. if ($col == 'ID') {
  4783. $columnConfig->unique = true;
  4784. }
  4785. else if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
  4786. $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
  4787. }
  4788. else if (in_array($col, array('Status'))) {
  4789. // Ahmes problems Status colors
  4790. $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
  4791. }
  4792. else if ($this->_acl->isGeomField($col)) {
  4793. $columnConfig->type = 'geom';
  4794. }
  4795. if ('' !== ($label = $this->_acl->getFieldLabel($fieldID))) {
  4796. $columnConfig->friendly = $label;
  4797. }
  4798. $colType = $this->_acl->getFieldType($col);
  4799. if ($colType) {// @see MarkTableAjaxFilterColType
  4800. if ($colType['type'] == 'date') {
  4801. //$columnConfig->type = 'date';// TODO: require datetimepicker
  4802. }
  4803. } else {// typespecial - no type
  4804. $columnConfig->type = 'special';
  4805. }
  4806. $typeSpecial = Typespecial::getInstance($fieldID, $col);
  4807. if ($typeSpecial) {
  4808. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">typeSpecial (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  4809. $columnConfig->_tsRetId = $typeSpecial->getReturnId();
  4810. if ($columnConfig->_tsRetId == 0) {
  4811. $tsParamOut = V::get('param_out', null, $typeSpecial);
  4812. if ($tsParamOut) {
  4813. $tsFormat = V::get('format', null, $tsParamOut);
  4814. $tsValues = V::get('values', null, $tsParamOut);
  4815. $tsAliases = V::get('alias', null, $tsParamOut);
  4816. if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
  4817. $tsAliasMap = array();
  4818. /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
  4819. $bugTsColsNotVisible = array();
  4820. foreach ($tsValues as $kVarName => $vIdZasob) {
  4821. if (array_key_exists($vIdZasob, $tsAliases)) {
  4822. $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
  4823. } else {
  4824. $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
  4825. }
  4826. if (!array_key_exists($vIdZasob, $visibleCols)) {
  4827. $bugTsColsNotVisible[] = $vIdZasob;
  4828. }
  4829. }
  4830. if (empty($bugTsColsNotVisible)) {
  4831. $tsSimpleLink = new stdClass();
  4832. $tsSimpleLink->format = $tsFormat;
  4833. $tsSimpleLink->aliasMap = $tsAliasMap;
  4834. $columnConfig->_tsSimpleLink = $tsSimpleLink;
  4835. $columnConfig->type = 'simpleLink';
  4836. } else {
  4837. $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
  4838. }
  4839. }
  4840. }
  4841. }
  4842. }
  4843. // @see ajaxHiddenColsSave
  4844. if (UserProfile::isHiddenColumn($this->_zasobID, $fieldID)) {
  4845. $columnConfig->hidden = true;
  4846. }
  4847. $columnConfig->description = $this->_acl->getFieldOpis($fieldID);
  4848. $jsonData->cols->{$col} = $columnConfig;
  4849. }
  4850. $jsonData->rows = array();
  4851. $jsonData->total = $this->_acl->getTotal($params);
  4852. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">get_total (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($jsonData->total);echo'</pre>';}
  4853. $items = $this->_acl->getItems($params);
  4854. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">items (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items);echo'</pre>';}
  4855. // TODO: add virtual data by Typespecial
  4856. if (!empty($vCols) && !empty($items)) {
  4857. foreach ($vCols as $vColID => $vCol) {
  4858. $colType = $this->_acl->getFieldTypeById($vColID);
  4859. if ($colType) {
  4860. continue;// pomin Typespecial dla realnych komorek w bazie danych
  4861. }
  4862. $typeSpecial = Typespecial::getInstance($vColID, $vCol);
  4863. if ($typeSpecial) {
  4864. $columnConfig = V::get($vCol, null, $jsonData->cols);
  4865. if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
  4866. // pomin simple link values - mved to js render
  4867. } else {
  4868. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vColID.') (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($typeSpecial);echo'</pre>';}
  4869. $ids = array_keys($items);
  4870. $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
  4871. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Typespecial('.$vCol.') specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($specialValues);echo'</pre>';}
  4872. if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
  4873. $tsValue = implode('<br>', $vValues);
  4874. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">Item['.$kItemID.'].'.$vCol.' specialValues (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($items[$kItemID]);echo'</pre>';}
  4875. if (!empty($items[$kItemID]->{$vCol}) && !empty($tsValue)) {
  4876. $items[$kItemID]->{$vCol} .= ": {$tsValue}";
  4877. } else {
  4878. $items[$kItemID]->{$vCol} = $tsValue;
  4879. }
  4880. }
  4881. }
  4882. }
  4883. }
  4884. }
  4885. foreach ($items as $vItem) {
  4886. // TODO: hide items without 'R'
  4887. foreach ($visibleCols as $kID => $vCol) {
  4888. // TODO: ID default 'R'
  4889. if (!$this->_acl->isAllowed($kID, 'R', $vItem)) {
  4890. $vItem->{$vCol} = '*****';
  4891. }
  4892. // null => empty string
  4893. if (!isset($vItem->{$vCol}) || (!$vItem->{$vCol} && $vItem->{$vCol} !== '0')) {
  4894. if($DBG){echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">isEmptyString['.$vCol.'] (F.' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($vItem->{$vCol});echo'</pre>';}
  4895. $vItem->{$vCol} = '';
  4896. }
  4897. }
  4898. $jsonData->rows[] = $vItem;
  4899. }
  4900. return $jsonData;
  4901. }
  4902. private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
  4903. $value = '';
  4904. $type = $this->_acl->getFieldTypeById($fieldID);
  4905. if ($type) {
  4906. if ($type['type'] == 'date') {
  4907. $value = $type['default'];
  4908. }
  4909. // fix bug when field is unique and is null allowed: change empty string to null
  4910. if ($type['null']) {
  4911. $value = 'NULL';
  4912. }
  4913. // fix bug when field is enum and is set to '0': for php '0' is empty
  4914. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  4915. if (false !== strpos($type['type'], "''")) {
  4916. // enum('', '1','2')
  4917. $value = '';
  4918. } else if (false !== strpos($type['type'], "'0'")) {
  4919. // enum('0', '1','2')
  4920. $value = '0';
  4921. } else {
  4922. $value = $type['default'];
  4923. }
  4924. }
  4925. }
  4926. return $value;
  4927. }
  4928. /**
  4929. * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
  4930. * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
  4931. */
  4932. private function ajaxHiddenColsSave($args) {
  4933. $response = new stdClass();
  4934. if (empty($args)) {
  4935. $response->type = 'info';
  4936. return $response;
  4937. }
  4938. UserProfile::load();
  4939. // clean up old, wrong values
  4940. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  4941. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  4942. }
  4943. $colVis = UserProfile::getHiddenCols($this->_zasobID);
  4944. $fields = $this->_acl->getFields();
  4945. foreach ($fields as $kFldId => $vFld) {
  4946. $vFldName = $vFld['name'];
  4947. if (isset($args[$vFldName])) {
  4948. if ($args[$vFldName] == 'SHOW') {
  4949. $colVis[$kFldId] = 1;
  4950. } else if ($args[$vFldName] == 'HIDE') {
  4951. $colVis[$kFldId] = 0;
  4952. }
  4953. }
  4954. }
  4955. UserProfile::setHiddenCols($this->_zasobID, $colVis);
  4956. UserProfile::save();
  4957. $response->type = 'success';
  4958. return $response;
  4959. }
  4960. private function ajaxPageSizeSave($args) {
  4961. $response = new stdClass();
  4962. if (empty($args)) {
  4963. $response->type = 'info';
  4964. return $response;
  4965. }
  4966. $pageSize = V::get('pageSize', 0, $args, 'int');
  4967. UserProfile::load();
  4968. // clean up old, wrong values
  4969. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  4970. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  4971. }
  4972. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  4973. $tableAjaxSettings['pageSize'] = $pageSize;
  4974. UserProfile::setTableAjaxSettings($tableAjaxSettings);
  4975. UserProfile::save();
  4976. $response->type = 'success';
  4977. return $response;
  4978. }
  4979. private function ajaxTheGeomSave($args) {
  4980. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  4981. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  4982. $polygon = V::get('polygon', 0, $args);
  4983. $geomFieldName = 'the_geom';
  4984. if ($primaryKey <= 0) {
  4985. throw new HttpException("Wrong param ID", 404);
  4986. }
  4987. // TODO: validate polygon - ex.: POLYGON((2072030.2315435 7234115.910678,2072029.4815435 7234093.660678,2072115.2315435 7234091.160678,2072115.4815435 7234113.660678,2072115.2315435 7234113.660678,2072094.2315435 7234113.910678,2072030.2315435 7234115.910678)))
  4988. $record = $this->_acl->getItem($primaryKey);
  4989. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  4990. throw new HttpException("Brak dostępu do rekordu", 403);
  4991. }
  4992. $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
  4993. if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
  4994. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  4995. }
  4996. $itemPatch = array();
  4997. $itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
  4998. $itemPatch[$primaryKeyField] = $primaryKey;
  4999. $response = new stdClass();
  5000. try {
  5001. $affected = $this->_acl->updateItem($itemPatch);
  5002. if ($affected > 0) {
  5003. $response->type = 'success';
  5004. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  5005. } else if ($affected == 0) {
  5006. $response->type = 'info';
  5007. $response->msg = "Nie wprowadzono żadnych zmian";
  5008. }
  5009. $response->record = $this->_acl->getItem($primaryKey);
  5010. }
  5011. catch (Exception $e) {
  5012. $response->type = 'error';
  5013. $response->msg = $e->getMessage();
  5014. }
  5015. return $response;
  5016. }
  5017. private function sendAjaxResponseJson($method, $args) {
  5018. try {
  5019. $response = $this->{$method}($args);
  5020. }
  5021. catch (HttpException $e) {
  5022. $response = new stdClass();
  5023. $response->type = 'error';
  5024. $response->msg = $e->getMessage();
  5025. $response->errorCode = $e->getCode();
  5026. Http::sendHeaderByCode($e->getCode());
  5027. }
  5028. catch (Exception $e) {
  5029. $response = new stdClass();
  5030. $response->type = 'error';
  5031. $response->msg = $e->getMessage();
  5032. $response->errorCode = $e->getCode();
  5033. }
  5034. header('Content-type: application/json');
  5035. if (!$response) $response = new stdClass();
  5036. echo json_encode($response);
  5037. exit;
  5038. }
  5039. private function ajaxTheGeomRemove($args) {// ajax task 'THE_GEOM_REMOVE'
  5040. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  5041. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  5042. $geomFieldName = 'the_geom';
  5043. $response = new stdClass();
  5044. if ($primaryKey <= 0) {
  5045. throw new HttpException("Wrong param ID", 404);
  5046. }
  5047. $record = $this->_acl->getItem($primaryKey);
  5048. if (!$record) {
  5049. throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  5050. }
  5051. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  5052. throw new HttpException("Brak dostępu do rekordu nr {$primaryKey}", 403);
  5053. }
  5054. $theGeomFieldId = $this->_acl->getFieldIdByName($geomFieldName);
  5055. if (!$this->_acl->isAllowed($theGeomFieldId, 'W', $record)) {
  5056. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  5057. }
  5058. if (empty($record->{$geomFieldName})) {
  5059. $response->type = 'info';
  5060. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  5061. $response->record = $record;
  5062. return $response;
  5063. }
  5064. $itemPatch = array();
  5065. $itemPatch[$geomFieldName] = "NULL";
  5066. $itemPatch[$primaryKeyField] = $primaryKey;
  5067. $response = new stdClass();
  5068. try {
  5069. $affected = $this->_acl->updateItem($itemPatch);
  5070. if ($affected > 0) {
  5071. $response->type = 'success';
  5072. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  5073. } else if ($affected == 0) {
  5074. $response->type = 'info';
  5075. $response->msg = "Nie wprowadzono żadnych zmian";
  5076. }
  5077. $response->record = $this->_acl->getItem($primaryKey);
  5078. }
  5079. catch (Exception $e) {
  5080. $response->type = 'error';
  5081. $response->msg = $e->getMessage();
  5082. }
  5083. return $response;
  5084. }
  5085. private function ajaxProcesInitFiltr($args) {// ajax task 'PROCES_INIT_FILTR'
  5086. $response = new stdClass();
  5087. $pInitList = array();// [proces_init_id] => label (DESC)
  5088. if (!$this->_showProcesInit) {
  5089. $response->type = 'error';
  5090. return $response;
  5091. }
  5092. $userAcl = User::getAcl();
  5093. $pInitList = $userAcl->getTableProcesInitList($this->_zasobID);
  5094. if (!empty($pInitList)) {
  5095. $procesIds = array_keys($pInitList);
  5096. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  5097. DBG::_('DBG_MAP', '1', "mapTree", $mapTree, __CLASS__, __FUNCTION__, __LINE__);
  5098. DBG::_('DBG_MAP', '1', "pInitList", $pInitList, __CLASS__, __FUNCTION__, __LINE__);
  5099. $pInitListSelected = $this->getProcesInitSelected();
  5100. $response->pInitData = new stdClass();
  5101. $response->pInitData->pInitList = $pInitList;
  5102. $response->pInitData->mapTree = $mapTree;
  5103. $response->pInitData->pInitListSelected = $pInitListSelected;
  5104. }
  5105. $response->type = 'success';
  5106. return $response;
  5107. }
  5108. }