TableAjax.php 222 KB

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