TableAjax.php 230 KB

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