TableAjax.php 226 KB

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