TableAjax.php 168 KB

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