TableAjax.php 229 KB

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