TableAjax.php 225 KB

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