TableAjax.php 220 KB

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