TableAjax.php 180 KB

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