TableAjax.php 201 KB

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