TableAjax.php 201 KB

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