TableAjax.php 228 KB

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