TableAjax.php 224 KB

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