TableAjax.php 202 KB

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