TableAjax.php 182 KB

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