TableAjax.php 109 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859
  1. <?php
  2. Lib::loadClass('ViewAjax');
  3. Lib::loadClass('TableAjaxMap');
  4. Lib::loadClass('Typespecial');
  5. Lib::loadClass('UI');
  6. Lib::loadClass('FoldersConfig');
  7. Lib::loadClass('FileUploader');
  8. Lib::loadClass('UserProfile');
  9. Lib::loadClass('ProcesHelper');
  10. Lib::loadClass('Router');
  11. Lib::loadClass('Route_UrlAction');
  12. Lib::loadClass('Core_AclHelper');
  13. Lib::loadClass('AntAclBase');
  14. // TODO: change all links: MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={idZasob} to _route=ViewTableAjax&typeName=p5_default_db:{tableName}
  15. class TableAjax extends ViewAjax {
  16. public $_cnf = '';// Column
  17. public $_htmlID = '';
  18. public $_rowFunctions = array();
  19. public $_pageSize = 10;
  20. public $_pageSizes = array();
  21. public $_filterInit = null;
  22. public $_forceFilterInit = null;
  23. public $showProcesInitFiltr = null;
  24. public $showTableTools = null;
  25. public $useUserTableFilter = false;
  26. public $syncUrl = null;
  27. public function __construct($tblAcl) {
  28. $this->_tbl = $tblAcl->getName();
  29. $this->_acl = $tblAcl;
  30. $this->_zasobID = $tblAcl->getID();
  31. $this->_pageSize = 10;
  32. {
  33. UserProfile::load();
  34. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  35. $this->_pageSize = V::get('pageSize', 10, $tableAjaxSettings, 'int');
  36. }
  37. $this->_pageSizes = array(10, 20, 50, 100);// default page sizes
  38. $this->_filterInit = new stdClass();
  39. $hash = V::get('_hash', '', $_GET);
  40. if ($hash) {
  41. $this->_htmlID = $hash;
  42. $this->_readState();
  43. } else {
  44. $this->_htmlID = $this->generateHtmlID();
  45. $this->_readState();
  46. }
  47. }
  48. public function setSyncUrl($syncUrl) { $this->syncUrl = $syncUrl; }
  49. public function setRootUrl($rootUrl) { $this->rootUrl = $rootUrl; }
  50. private function _hasStateFilterInit() {
  51. return array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache']) && array_key_exists('_filterInit', $_SESSION['TableAjax_Cache'][$this->_htmlID]);
  52. }
  53. // TODO: read state from cache by key $this->_htmlID
  54. // TODO: load filters and state: table, edit, add, etc.
  55. // TODO: save this data in Workspace 1, 2, 3, etc.
  56. // TODO: default filters in VIEWTABLE_AJAX
  57. // $tbl->setLabel($zasobObj->OPIS);
  58. // $tbl->setFilterInit($filterInit);
  59. // $tbl->addRowFunction('edit');
  60. // $tbl->addRowFunction('hist');
  61. // $tbl->addRowFunction('files');
  62. // $tbl->addRowFunction('cp');
  63. private function _readState() {
  64. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  65. $_SESSION['TableAjax_Cache'] = array();
  66. }
  67. //trigger_error("F." . __FUNCTION__ . " (" . (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) . ")", E_USER_NOTICE);
  68. //trigger_error("F." . __FUNCTION__ . " (".basename($_SERVER['SCRIPT_FILENAME'])."::_filterInit: " . json_encode($_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit']) . ")", E_USER_NOTICE);
  69. if (array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  70. foreach ($_SESSION['TableAjax_Cache'][$this->_htmlID] as $k => $v) {
  71. //trigger_error("F." . __FUNCTION__ . " key: ({$k})", E_USER_NOTICE);
  72. switch ($k) {
  73. case '_label':
  74. $this->_label = $v;
  75. break;
  76. case '_filterInit':
  77. $this->_filterInit = $v;
  78. break;
  79. case '_rowFunctions':
  80. $this->_rowFunctions = $v;
  81. break;
  82. default:
  83. }
  84. }
  85. }
  86. }
  87. protected function _saveState($key = null) {
  88. if (!array_key_exists('TableAjax_Cache', $_SESSION)) {
  89. $_SESSION['TableAjax_Cache'] = array();
  90. }
  91. if (!array_key_exists($this->_htmlID, $_SESSION['TableAjax_Cache'])) {
  92. $_SESSION['TableAjax_Cache'][$this->_htmlID] = array();
  93. }
  94. if (!$key) {
  95. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  96. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  97. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  98. } else if ($key == '_label') {
  99. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_label'] = $this->_label;
  100. } else if ($key == '_filterInit') {
  101. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_filterInit'] = $this->_filterInit;
  102. } else if ($key == '_rowFunctions') {
  103. $_SESSION['TableAjax_Cache'][$this->_htmlID]['_rowFunctions'] = $this->_rowFunctions;
  104. }
  105. }
  106. public function setPageSizes($pageSizes) {
  107. $this->_pageSizes = $pageSizes;
  108. }
  109. public function setBackRefFilter($backRefFilter) {
  110. $this->_backRefFilter = $backRefFilter;
  111. }
  112. public function setChildRefFilter($childRefFilter) {
  113. $this->_childRefFilter = $childRefFilter;
  114. }
  115. public function setFilterInit($filterInit) {
  116. if ($this->_hasStateFilterInit()) {
  117. return;
  118. }
  119. $this->_filterInit = (object)$filterInit;
  120. $this->_saveState();
  121. }
  122. /**
  123. * @param array $forceFilterInit
  124. */
  125. public function setForceFilterInit($forceFilterInit) {
  126. $this->_forceFilterInit = (object)$forceFilterInit;
  127. }
  128. private function setFilters($filterInit) {
  129. $this->_filterInit = (object)$filterInit;
  130. $this->_saveState();
  131. }
  132. public function setRowFunctions($functions) {
  133. $this->_rowFunctions = [];
  134. $defaultRowFunction = array();
  135. $defaultRowFunction['edit'] = [ 'href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord', 'class' => "btn btn-xs btn-link" ];
  136. $defaultRowFunction['hist'] = [ 'href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia', 'class' => "btn btn-xs btn-link" ];
  137. $defaultRowFunction['files'] = [ 'href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki', 'class' => "btn btn-xs btn-link" ];
  138. $defaultRowFunction['cp'] = [ 'href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});', 'class' => "btn btn-xs btn-link" ];
  139. $defaultRowFunction['msgs'] = [ 'href'=>"index.php?_route=TableMsgs&_task=tableRow&idTable={$this->_zasobID}&idRow={0}", 'ico'=>'glyphicon glyphicon-envelope', 'title'=>'Wiadomości', 'class' => "btn btn-xs btn-link" ];
  140. foreach ($functions as $funName => $params) {
  141. if (true === $params) {
  142. if (array_key_exists($funName, $defaultRowFunction)) {
  143. $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
  144. } else {
  145. throw new Exception("Row function not defined '{$funName}'");
  146. }
  147. }
  148. if (is_array($params)) {
  149. $this->_rowFunctions[$funName] = $params;
  150. }
  151. }
  152. $this->_saveState('_rowFunctions');
  153. }
  154. public function addRowFunction($funName, $funParams = array()) {
  155. $defaultRowFunction = array();
  156. //$defaultRowFunction['edit'] = '<a href="#EDIT/{0}" class="glyphicon glyphicon-pencil" title="Edytuj rekord"></a>';
  157. //$defaultRowFunction['hist'] = '<a href="#HIST/{0}" class="glyphicon glyphicon-book" title="Historia"></a>';
  158. //$defaultRowFunction['files'] = '<a href="#FILES/{0}" class="glyphicon glyphicon-folder-open" title="Pliki"></a>';
  159. //$defaultRowFunction['cp'] = '<a href="#" class="glyphicon glyphicon-plus-sign" title="Kopiuj rekord" onclick="return tableAjaxCopy({0});"></a>';
  160. $defaultRowFunction['edit'] = [ 'href'=>'#EDIT/{0}', 'ico'=>'glyphicon glyphicon-pencil', 'title'=>'Edytuj rekord', 'class' => "btn btn-xs btn-link" ];
  161. $defaultRowFunction['hist'] = [ 'href'=>'#HIST/{0}', 'ico'=>'glyphicon glyphicon-book', 'title'=>'Historia', 'class' => "btn btn-xs btn-link" ];
  162. $defaultRowFunction['files'] = [ 'href'=>'#FILES/{0}', 'ico'=>'glyphicon glyphicon-folder-open', 'title'=>'Pliki', 'class' => "btn btn-xs btn-link" ];
  163. $defaultRowFunction['cp'] = [ 'href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});', 'class' => "btn btn-xs btn-link" ];
  164. $defaultRowFunction['msgs'] = [ 'href'=>"index.php?_route=TableMsgs&_task=tableRow&idTable={$this->_zasobID}&idRow={0}", 'ico'=>'glyphicon glyphicon-envelope', 'title'=>'Wiadomości', 'class' => "btn btn-xs btn-link" ];
  165. if (array_key_exists($funName, $defaultRowFunction)) {
  166. $this->_rowFunctions[$funName] = $defaultRowFunction[$funName];
  167. }
  168. else {
  169. $this->_rowFunctions[$funName] = $funParams;
  170. }
  171. $this->_saveState('_rowFunctions');
  172. }
  173. private function _parseRowFunctions($idRecord = null, $pomin = array(), $showLabel = false) {
  174. $rowFunctions = array();
  175. foreach ($this->_rowFunctions as $kFunName => $vParams) {
  176. if (in_array($kFunName, $pomin)) continue;
  177. //$rowFunctionsOut .= str_replace('{0}', $idRecord, $vUrl);
  178. $attrs = array();
  179. // $defaultRowFunction['cp'] = (object)array('href'=>'#', 'ico'=>'glyphicon glyphicon-plus-sign', 'title'=>'Kopiuj rekord', 'onclick'=>'return tableAjaxCopy({0});');
  180. $label = '';
  181. $ico = '';
  182. foreach ($vParams as $kParamName => $v) {
  183. if ($kParamName == 'ico') {
  184. $ico = '<span class="' . $v . '"></span>';
  185. continue;
  186. }
  187. $attr = $v;
  188. if ($idRecord > 0) {
  189. $attr = str_replace('{0}', $idRecord, $attr);
  190. }
  191. if ($showLabel && $kParamName == 'title') {
  192. $label = $attr;
  193. }
  194. $attr = $kParamName . '="' . $attr . '"';
  195. $attrs[] = $attr;
  196. }
  197. $rowFunctions[$kFunName] = '<a ' . implode(' ', $attrs) . '>' . "{$ico} {$label} " . '</a>';
  198. }
  199. return $rowFunctions;
  200. }
  201. private function _showRowFunctions($idRecord = null, $pomin = array(), $showLabel = false) {
  202. $rowFunctionsOut = $this->_parseRowFunctions($idRecord, $pomin, $showLabel);
  203. $rowFunctionsOut = implode('', $rowFunctionsOut);
  204. return $rowFunctionsOut;
  205. }
  206. private function _showRowFunctionsJson($idRecord = null, $pomin = array(), $showLabel = false) {
  207. $rowFunctions = $this->_parseRowFunctions($idRecord, $pomin, $showLabel);
  208. $rowFunctions = (object)$rowFunctions;
  209. return $rowFunctions;
  210. }
  211. public function allowTreeView() {
  212. if ($this->_tbl == 'CRM_LISTA_ZASOBOW') return true;
  213. if ($this->_tbl == 'CRM_PROCES') return true;
  214. return false;
  215. }
  216. public function renderStatic($tblAjaxMap = null) {
  217. static $_rendered = false;
  218. if ($_rendered) return;
  219. if ($tblAjaxMap) $tblAjaxMap->printCSS();
  220. if ($tblAjaxMap) $tblAjaxMap->printJS();
  221. echo UI::h('script', ['src'=>"static/sweetalert2.min.js"]);
  222. echo UI::h('script', ['src'=>"static/jquery.doubleScroll.js"]);
  223. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"stuff/jquery-ui-smoothness/jquery-ui-1.10.4.custom.min.css"]);
  224. echo UI::h('link', ['rel'=>"stylesheet", 'type'=>"text/css", 'href'=>"static/sweetalert2.min.css"]);
  225. echo UI::h('style', ['type'=>"text/css"], "
  226. .AjaxTable{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;}
  227. .AjaxTableCont {position:relative; margin:10px 0; width:100%; overflow-x:auto; border:none;}
  228. .AjaxTable *,
  229. .AjaxTable.table {white-space:nowrap; width:auto;}
  230. .AjaxTable .popover * {white-space:normal;}
  231. .AjaxTable p {margin:0;}
  232. .AjaxTable td, .AjaxTable th {line-height:18px;}
  233. .AjaxTable i {margin: 0 0 0 2px;opacity: 0.5;}
  234. .AjaxTable span.filter {background-color:#999;}
  235. .AjaxTable .indeterminate {opacity: 0.4;-ms-filter:\"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)\";filter:alpha(opacity=40);}
  236. .AjaxTable .columnpicker li, .AjaxTable .actions li {padding-left:5px;}
  237. .AjaxTableCont .btn-toolbar {margin:2px 0 0 0;}
  238. .AjaxTableCont .btn-toolbar .btn-group {vertical-align:top;}
  239. .AjaxTable input[type=checkbox] {margin:0;padding:0;height:13px;}
  240. .AjaxTable input[type=text].filter {margin:0;padding:0 5px;box-shadow:none;width:100%;background:#eee;color:#000;}
  241. .AjaxTable input[type=text].filter {border-width:2px 0;border-color:#eee;border-style:solid;}
  242. .AjaxTable input[type=text].filter-active {border-color:#00ACCC;}
  243. .AjaxTable .date-wrap {width:100%;min-width:115px;}
  244. .AjaxTable .dateWrap .add-on {margin:0;padding:0;background:none;border:none;float:right;cursor:pointer;}
  245. .AjaxTable .actions a {padding:0;margin:0;}
  246. .AjaxTableCont .text-right {text-align:right}
  247. .AjaxTableCont .breadcrumb em {color:#bbb;}
  248. .AjaxTable-loading .head-info {background:url(./icon/loading.gif) no-repeat left top; background-position:0 6px;}
  249. .AjaxTable-loading .loading-info,
  250. .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block; padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;}
  251. .AjaxTableCont .loading-info {display:none;}
  252. .AjaxTableCont .tblAjax__inlineEditBox .loading-info {display:block;}
  253. .AjaxTableCont .table {margin-bottom:0px;}
  254. .AjaxTableCont .stickyCol1 a { color:#333; }
  255. .AjaxTableCont .stickyCol1 a:hover { color:#337AB7; text-decoration:none; }
  256. .AjaxTableTaskCnt {padding:0 10px 10px 10px;}
  257. .AjaxTable .tbl-short-txt{max-width:140px; overflow:hidden;}
  258. .AjaxTable .tbl-short-txt span{display:block; height:18px;}
  259. .AjaxTable .tooltip-inner{white-space:normal;}
  260. .AjaxTable thead .sort .ta-ordering {cursor:pointer;}
  261. .AjaxTable thead .sort .ta-ordering span {margin:0 10px 0 0; padding:0; background-repeat:no-repeat; background-position:right top;}
  262. .AjaxTable thead .sort .ta-ordering-down span:after{content:\"\\e252\";font-family:\"Glyphicons Halflings\";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
  263. .AjaxTable thead .sort .ta-ordering-up span:after{content:\"\\e253\";font-family:\"Glyphicons Halflings\";line-height:1;margin:0 0 0 3px;display:inline-block;color:#bbb;}
  264. .AjaxTable thead .sort .ta-ordering {position:relative;}
  265. .AjaxTable thead .sort th .hover-show:hover{background-color:#000; background-image:url(stuff/twitter-bootstrap/img/glyphicons-halflings-white.png);}
  266. .AjaxTable thead .sort th .hover-show{display:none;}
  267. .AjaxTable thead .sort th:hover .hover-show{display:inline;}
  268. .AjaxTable thead .sort .ta-ordering .remove-cell {position:absolute; top:6px; right:2px; display:none; color:#f00;}
  269. .AjaxTable thead .sort .ta-ordering:hover .remove-cell {display:block;}
  270. .AjaxTableCont .pagination { margin:0; }
  271. .AjaxTableCont .pagination a { line-height:16px; }
  272. .AjaxTableCont .AjaxTableEdit-label { display:block; margin:0 0 3px 0; font-size:12px !important; line-height:16px !important; }
  273. .AjaxTableCont .AjaxTableEdit-label code { padding:0; white-space:nowrap; background-color:transparent; border:none; color:#777; font-size:10px !important; line-height:14px !important; }
  274. .AjaxTableCont .AjaxTableEdit .show-last-value .button-appendBack .glyphicon,
  275. .AjaxTableCont .AjaxFrmHorizontalEdit .show-last-value .button-appendBack .glyphicon {display:none;}
  276. .AjaxTableHist em {color:silver;}
  277. .AjaxTableCont .foot * { font-size:12px !important; }
  278. .AjaxTableCont .foot { margin:10px; }
  279. .AjaxTableCont .foot .foot-info { float:left; padding:0 20px; }
  280. .AjaxTableCont .foot .foot-info p { line-height:16px; margin:5px 0; }
  281. .AjaxTable-loading .foot .foot-info {padding-left:20px; background:url(./icon/loading.gif) no-repeat left top;}
  282. .tblAjax__head__specialFilter {margin:0;padding:4px 4px 4px 127px;}
  283. .tblAjax__head__specialFilter .btn-group {margin:0 4px;padding:0;}
  284. .tblAjax__head__specialFilter .btn-group .glyphicon-remove {color:#f00;}
  285. .tblAjax__head__specialFilter .btn-group button.disabled .glyphicon-remove {color:#bbb;}
  286. /* overwrite bootstrap table border */
  287. .AjaxTable, .AjaxTableEdit,
  288. .AjaxTable td, .AjaxTableEdit td,
  289. .AjaxTable th, .AjaxTableEdit th { border-color:#999; }
  290. /* cell A_STATUS */
  291. .AjaxTable .cell-A_STATUS-NORMAL { background:#aeffae; color:#000; text-align:center; }
  292. .AjaxTable .cell-A_STATUS-WAITING { background:#ffd2ff; color:#000; text-align:center; }
  293. .AjaxTable .cell-A_STATUS-MONITOR { background:#cccaff; color:#000; text-align:center; }
  294. .AjaxTable .cell-A_STATUS-WARNING { background:#ffbaba; color:#000; text-align:center; }
  295. .AjaxTable .cell-A_STATUS-DELETED { background:#e0e0e0; color:#808080; text-align:center; }
  296. .AjaxTable .cell-A_STATUS-OFF_SOFT { background:#fce3b7; color:#808080; text-align:center; }
  297. .AjaxTable .cell-A_STATUS-OFF_HARD { background:#eee; color:#808080; text-align:center; }
  298. /* cell Status */
  299. .AjaxTable .cell-Status-U { background:rgb(0,176,80); color:#000; text-align:center; }
  300. .AjaxTable .cell-Status-NU { background:#f00; color:#000; text-align:center; }
  301. .AjaxTable .cell-Status-P { background:rgb(112,48,160); color:#000; text-align:center; }
  302. .AjaxTable .cell-Status-PT { background:rgb(127,127,127); color:#000; text-align:center; }
  303. .AjaxTable .cell-Status-O { background:rgb(0,176,240); color:#000; text-align:center; }
  304. .AjaxTable .cell-Status-DZ { background:rgb(0,112,192); color:#000; text-align:center; }
  305. .AjaxTable .cell-Status-Z {}
  306. /* map */
  307. .AjaxTable .cell-mapfld { cursor:pointer; }
  308. .AjaxTable .cell-mapfld:hover { opacity:1; }
  309. .AjaxTable .cell-mapfld-remove { display:none; }
  310. .AjaxTable .cell-mapfld-hasValue .cell-mapfld-select { color:#f00; }
  311. .AjaxTable .cell-mapfld-hasValue .cell-mapfld-remove { display:inline-block; }
  312. .AjaxTableCont .mapEditor { position:absolute; bottom:0; right:6px; width:512px; height:318px; overflow:hidden; color:#eee; border:1px solid #999; }
  313. .AjaxTableCont .mapEditor-panel { height:16px; padding:0 6px; background:#999; border-bottom:1px solid #eee; }
  314. .AjaxTableCont .mapEditor-panel a { display:block; float:right; padding:0 6px; font-weight:bold; font-size:12px; line-height:16px; color:#fff; }
  315. .AjaxTableCont .mapEditor-panel a:hover { color:#006CD7; text-decoration:none; }
  316. .AjaxTableCont .mapEditor-panel a.mapEditor-panel-close:hover { color:#f00; }
  317. .AjaxTableCont .mapEditor-map { background:#fff; height:400px; }
  318. .AjaxTableCont-mapEditorContainer .mapEditor-map { border:1px solid #999; overflow:hidden; }
  319. /* .mapEditor-btnBackToWindow \"olControlSave\",overview_replacement */
  320. .olControlEditingToolbar .mapEditor-btnBackToWindowItemInactive,
  321. .olControlEditingToolbar .mapEditor-btnBackToWindowItemActive {
  322. background-image: url(icon/map.window.png);
  323. background-position: 0 0;
  324. background-repeat: no-repeat;
  325. }
  326. /*
  327. .mapEditor-btnBackToWindowItemInactive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
  328. .mapEditor-btnBackToWindowItemActive { background-image: url(stuff/open-layers/theme/default/img/overview_replacement.gif); }
  329. */
  330. .ui-dialog-content .mapEditor-btnBackToWindowItemInactive,
  331. .ui-dialog-content .mapEditor-btnBackToWindowItemActive { display:none; }
  332. .AjaxTableCont .valign-btns-bottom .btn { vertical-align:text-bottom; font-weight:normal; font-size:12px; line-height:14px; }
  333. .ui-resizable-s { bottom:0; }
  334. .ui-resizable-e { right:0; }
  335. .AjaxTableCont-mapEditorContainer .ui-resizable-s { background-color:#ddd; }
  336. .AjaxTableCont-mapEditorContainer .ui-resizable-s:hover { background-color:#888; }
  337. ");
  338. echo UI::h('script', [ 'src' => "static/vendor.js" ]); // window.p5VendorJs: {React, ReactDOM, createReactClass, Redux}
  339. echo UI::h('script', [ 'src' => "static/p5UI/buildDom.js" ]);
  340. $_rendered = true;
  341. }
  342. public function render() {
  343. $acl = $this->_acl;
  344. $hasGeomFlds = Core_AclHelper::hasGeomFields($acl);
  345. $tblAjaxMap = ($hasGeomFlds) ? new TableAjaxMap($acl, 512, 400) : null;
  346. $hasPermCreate = Core_AclHelper::hasCreatePerms($acl);
  347. $jsToogleFiltrProcesuFunctionName = 'tableAjaxToggleFiltrProcesInit';
  348. $jsToogleTableToolsFunctionName = 'tableAjaxToggleTableTools';
  349. ob_start();
  350. $this->renderStatic($tblAjaxMap);
  351. UI::startContainer();
  352. UI::showMessagesForTable($this->_tbl);
  353. UI::endContainer();
  354. $namespace = $acl->getNamespace();
  355. echo UI::h('div', [ 'class' => "AjaxTableCont" ], [
  356. UI::h('ul', [ 'class' => "breadcrumb" ], [
  357. UI::h('li', [], [
  358. UI::h('a', [ 'href' => "#", 'onclick' => "return tableAjaxBackToTable();" ], $this->getLabelHtml() ),
  359. ]),
  360. ($hasPermCreate)
  361. ? UI::h('li', [], [
  362. UI::h('a', [ 'title' => "Dodaj nowy rekord", 'class' => "", 'href' => "#CREATE" ], [
  363. UI::h('span', [ 'class' => "glyphicon glyphicon-plus" ]),
  364. " Dodaj nowy rekord",
  365. ]),
  366. ])
  367. : '',
  368. ($this->showProcesInitFiltr)
  369. ? UI::h('div', [ 'class' => "btn-group pull-right" ], [
  370. UI::h('a', [ 'class' => "btn btn-xs btn-info dropdown-toggle",
  371. 'data-toggle' => "dropdown",
  372. 'href' => "#",
  373. 'title' => "Uruchom filtr procesu powiązanego z tabelą " . $this->getLabel(),
  374. 'onclick' => "return {$jsToogleFiltrProcesuFunctionName}(this);",
  375. ], "Filtr procesu <span class=\"caret\"></span>"),
  376. UI::h('ul', [ 'class' => "dropdown-menu pull-left", 'style' => "max-height:250px;overflow:auto;" ], [
  377. UI::h('li', [ 'class' => "disabled" ], [
  378. UI::h('a', [ 'href' => "#", 'onclick' => "return false;" ], " loading ... "),
  379. ]),
  380. ]),
  381. ])
  382. : '',
  383. ($this->showTableTools)
  384. ? UI::h('div', [ 'class' => "btn-group pull-right" ], [
  385. UI::h('a', [ 'class' => "btn btn-xs btn-default dropdown-toggle",
  386. 'style' => "margin-right:16px",
  387. 'data-toggle' => "dropdown",
  388. 'href' => "#",
  389. 'title' => "Narzędzia powiązane z tabelą " . $this->getLabel(),
  390. 'onclick' => "return {$jsToogleTableToolsFunctionName}(this);",
  391. ], "Narzędzia <span class=\"caret\"></span>"),
  392. UI::h('ul', [ 'class' => "dropdown-menu pull-left", 'style' => "max-height:250px;overflow:auto;" ], [
  393. UI::h('li', [ 'class' => "disabled" ], [
  394. UI::h('a', [ 'href' => "#", 'onclick' => "return false;" ], " loading ... "),
  395. ]),
  396. ]),
  397. ])
  398. : '',
  399. ($this->_tbl == 'IN7_MK_BAZA_DYSTRYBUCJI')
  400. ? UI::h('a', [ 'class' => "pull-right", 'style' => "padding:0 20px 0 0", 'href' => "index.php?MENU_INIT=TREEJS&ZASOB_ID={$this->_zasobID}" ], "<i class=\"glyphicon glyphicon-eye-open\"></i> Drzewo")
  401. : '',
  402. ($this->_tbl !== 'IN7_MK_BAZA_DYSTRYBUCJI' && $this->allowTreeView())
  403. ? UI::h('a', [ 'class' => "pull-right", 'style' => "padding:0 20px 0 0", 'href' => "index.php?MENU_INIT=VIEWTREE_AJAX&ZASOB_ID={$this->_zasobID}" ], "<i class=\"glyphicon glyphicon-eye-open\"></i> Drzewo")
  404. : '',
  405. ($this->_tbl == 'WMS_MAP_GEOREFERENCES')
  406. ? UI::h('a', [ 'class' => "pull-right", 'style' => "padding:0 20px 0 0", 'href' => "index.php?_route=GeoreferencesManager" ], "<i class=\"glyphicon glyphicon glyphicon-wrench\"></i> Zarządzaj punktami")
  407. : '',
  408. ]),
  409. ($this->_backRefFilter)
  410. ? UI::h('div', [ 'class' => "container" ], [
  411. UI::h('div', [ 'class' => "alert alert-info" ], [
  412. "Rekordy powiązane z rekordem {$this->_backRefFilter['primaryKey']} z ",
  413. UI::h('a', [
  414. 'href' => "index.php?_route=ViewTableAjax&namespace={$this->_backRefFilter['namespace']}",
  415. ], $this->_backRefFilter['namespace']),
  416. " - ",
  417. UI::h('a', [
  418. 'href' => $this->rootUrl,
  419. 'style' => "color:red",
  420. ], "usuń filtr"),
  421. ]),
  422. ])
  423. : '',
  424. ($this->_childRefFilter)
  425. ? UI::h('div', [ 'class' => "container" ], [
  426. UI::h('div', [ 'class' => "alert alert-info" ], [
  427. "Rekordy powiązane z rekordem {$this->_childRefFilter['primaryKey']} z ",
  428. UI::h('a', [
  429. 'href' => "index.php?_route=ViewTableAjax&namespace={$this->_childRefFilter['namespace']}",
  430. ], $this->_childRefFilter['namespace']),
  431. " - ",
  432. UI::h('a', [
  433. 'href' => $this->rootUrl,
  434. 'style' => "color:red",
  435. ], "usuń filtr"),
  436. ]),
  437. ])
  438. : '',
  439. UI::h('div', [ 'id' => $this->_htmlID ]),
  440. ]);
  441. UI::inlineJS(__FILE__ . '.generateFunctionNode.js');
  442. UI::inlineJS(__FILE__ . '.GeomField.js');
  443. if ($this->showProcesInitFiltr) {
  444. UI::inlineJS(__FILE__ . '.procesInitFiltr.js', [
  445. 'JS_FUNCTION_NAME' => $jsToogleFiltrProcesuFunctionName,
  446. 'URL_GET_PROCES_INIT_FILTR' => $this->showProcesInitFiltr,
  447. 'ID_ZASOB' => $this->_zasobID,
  448. ]);
  449. }
  450. if ($this->showTableTools) {
  451. UI::inlineJS(__FILE__ . '.tableTools.js', [
  452. 'JS_FUNCTION_NAME' => $jsToogleTableToolsFunctionName,
  453. 'URL_GET_TABLE_TOOLS' => $this->showTableTools,
  454. ]);
  455. }
  456. UI::inlineJS(__FILE__ . '.TableAjax.js', [
  457. 'SYNC_URL' => $this->syncUrl,
  458. 'HTML_ID' => $this->_htmlID,
  459. 'NAMESPACE' => $acl->getNamespace(),
  460. 'URI_BASE' => Request::getPathUri(),
  461. 'ZASOB_ID' => $this->_zasobID,
  462. 'CLASS_NAME' => __CLASS__,
  463. 'HAS_ADDITIONAL_LAYERS' => $this->hasAdditionalLayers(),
  464. 'LABEL_HTML' => $this->getLabelHtml(),
  465. ]);
  466. $filterInit = $this->_filterInit;
  467. $forceFilterInit = $this->_forceFilterInit;
  468. $pageSizes = $this->_pageSizes;
  469. $pageSize = $this->_pageSize;
  470. $rowFunctions = $this->_rowFunctions;//$this->_showRowFunctionsJson();
  471. $exportFields = Core_AclHelper::getExportFieldList($acl);
  472. UI::inlineJS(__FILE__ . '.hist.js', [
  473. 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
  474. 'TABLE_AJAX_LABEL' => $this->getLabelHtml(),
  475. 'URL_HIST_BASE' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls=" . __CLASS__ . "&_hash={$this->_htmlID}&_task=HIST", // &ID=...
  476. 'FUNCTION_HIST_ROUTE' => "TableAjax__HIST_Route",
  477. ]);
  478. UI::inlineJS(__FILE__ . '.create.js', [
  479. 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
  480. 'TABLE_AJAX_LABEL' => $this->getLabelHtml(),
  481. 'NAMESPACE' => $acl->getNamespace(),
  482. 'FIRCE_FILER_INIT' => $forceFilterInit,
  483. 'FUNCTION_CREATE_ROUTE' => "TableAjax__CREATE_Route",
  484. 'URL_CREATE_FORM_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=createFormJson",
  485. ]);
  486. UI::inlineJS(__FILE__ . '.edit.js', [
  487. 'TABLE_AJAX_NODE_ID' => $this->_htmlID,
  488. 'TABLE_AJAX_LABEL' => $this->getLabelHtml(),
  489. 'NAMESPACE' => $acl->getNamespace(),
  490. 'FUNCTION_EDIT_ROUTE' => "TableAjax__EDIT_Route",
  491. 'URL_EDIT_FORM_AJAX' => "{$this->syncUrl}&_hash={$this->_htmlID}&_task=editFormJson&_primaryKey=",
  492. ]);
  493. UI::inlineJS(__FILE__ . '.openRef.js', []); // p5UI__tableAjaxOpenRefCell
  494. $fltrs = (method_exists($acl, 'getSpecialFilters')) ? $acl->getSpecialFilters() : null;
  495. $jsonSpecialFilters = (!empty($fltrs)) ? json_encode($fltrs) : 'false';
  496. ?>
  497. <script>
  498. var TABLE_AJAX_NODE_ID = '<?= $this->_htmlID; ?>';
  499. var NAMESPACE = '<?= $acl->getNamespace(); ?>';
  500. var FUNCTION_HIST_ROUTE = window['TableAjax__HIST_Route'];
  501. var FUNCTION_EDIT_ROUTE = window['TableAjax__EDIT_Route'];
  502. var URL_LOAD_AJAX_BASE = '<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=loadDataAjax';
  503. var URL_USER_TABLE_FILTER = '<?= ($this->useUserTableFilter) ? $this->useUserTableFilter : ''; ?>';
  504. var FILER_INIT = <?= json_encode($filterInit); ?>;
  505. var FIRCE_FILER_INIT = <?= json_encode($forceFilterInit); ?>;
  506. var PAGE_SIZE = '<?= $pageSize; ?>';
  507. var PAGE_SIZES = <?= json_encode($pageSizes); ?>;
  508. jQuery(document).ready(function(){
  509. jQuery('#' + TABLE_AJAX_NODE_ID).TableAjax({
  510. namespace: NAMESPACE,
  511. url: URL_LOAD_AJAX_BASE,
  512. userTableFilterUrl: URL_USER_TABLE_FILTER,
  513. columnPicker: true,
  514. filter: true,
  515. filterInit: FILER_INIT,
  516. forceFilterInit: FIRCE_FILER_INIT,
  517. debug: false,
  518. height: 400,
  519. sorting: true,
  520. paging: true,
  521. pageSize: PAGE_SIZE,
  522. pageSizes: PAGE_SIZES,
  523. tblFunctions: {
  524. shortdesc: {
  525. icon: 'align-left',
  526. title: 'Long desc',
  527. method: 'longTextChanged'
  528. },
  529. <?php if ($hasGeomFlds) : ?>
  530. mapeditor: {
  531. icon: 'map-marker',
  532. title: 'Mapa',
  533. method: 'mapEditorChanged'
  534. },
  535. <?php endif; ?>
  536. create: {
  537. href: '#CREATE',
  538. icon: 'plus',
  539. title: 'Dodaj nowy rekord'
  540. },
  541. refresh: {
  542. icon: 'refresh',
  543. title: 'Odśwież dane',
  544. method: 'refresh'
  545. }
  546. },
  547. rowFunctions: <?php echo json_encode($rowFunctions); ?>,
  548. exportFields: <?php echo json_encode($exportFields); ?>,
  549. specialFilterFunctions: <?= $jsonSpecialFilters; ?>,
  550. router: function() {
  551. var routes = {
  552. EDIT: FUNCTION_EDIT_ROUTE,
  553. HIST: FUNCTION_HIST_ROUTE,
  554. FILES: function tableAjaxFiles(args) {
  555. var recordID = args;
  556. if (typeof args == 'object') {
  557. recordID = args.shift();
  558. recordID = parseInt(recordID);
  559. }
  560. if (typeof recordID !== 'number' || recordID <= 0) {
  561. // TODO: msg
  562. return false;
  563. }
  564. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  565. cont.hide();
  566. // remove previous task content
  567. var taskCnt = jQuery('#<?php echo $this->_htmlID; ?>_task');
  568. taskCnt.parent().remove();
  569. taskCnt.remove();
  570. var taskCont = jQuery('<div class="AjaxTableCont"></div>').insertBefore(cont);
  571. jQuery('<ul class="breadcrumb">' +
  572. '<li><a href="#" onclick="return tableAjaxBackToTable();"><?php echo $this->getLabelHtml(); ?></a></li>' +
  573. '<li class="active">Pliki</li>' +
  574. '</ul>').appendTo(taskCont);
  575. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTable-loading"></div>').appendTo(taskCont);
  576. jQuery('<span class="loading-info"> loading ...</span>').appendTo(taskCnt);
  577. jQuery.ajax({
  578. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=FILES&ID=' + recordID,
  579. type: 'GET',
  580. dataType: 'text',
  581. data: '',
  582. async: true,
  583. success: function(data) {
  584. taskCnt.removeClass('AjaxTable-loading');
  585. //console.log('request finished L.<?php echo __LINE__; ?>', data);
  586. jQuery(data).appendTo(taskCnt);
  587. },
  588. error: function(jqXHR, textStatus, errorThrown) {
  589. //console.log('request error:', jqXHR.status, 'txt:', jqXHR.responseText, 'err:', jqXHR);
  590. taskCnt.removeClass('AjaxTable-loading');
  591. var txt = jqXHR.responseText || 'Error';
  592. if (jqXHR.status == 404) {
  593. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  594. } else {
  595. jQuery('<div class="container"><div class="alert alert-danger">' + txt + '</div></div>').appendTo(taskCnt);
  596. }
  597. }
  598. });
  599. //return false;
  600. },
  601. CREATE: TableAjax__CREATE_Route,
  602. };
  603. var routePath = location.hash;
  604. //console.log('location.hash: ' + routePath);
  605. if (location.hash == '' || location.hash == '#') {
  606. return false;
  607. }
  608. if (routePath.charAt(0) == '#') {
  609. routePath = routePath.substr(1);
  610. }
  611. //console.log('routePath: ' + routePath);
  612. var parts = routePath.split('/');
  613. var task = parts.shift();
  614. //console.log('task(' + task + ') parts:');
  615. //console.log(parts);
  616. if (task in routes && typeof routes[task] == 'function') {
  617. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  618. if (con) {
  619. var tblAjax = con.data('TableAjax');
  620. if (tblAjax) {
  621. tblAjax.popoverCellRemove();
  622. }
  623. }
  624. routes[task](parts);
  625. } else {
  626. return false;
  627. }
  628. },
  629. filtersClean: true,
  630. longDesc: true
  631. });
  632. });
  633. function tableAjaxBackToTable() {
  634. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  635. cont.show();
  636. var taskCont = jQuery('#<?php echo $this->_htmlID . '_task'; ?>').parent();
  637. taskCont.remove();
  638. // reload first page
  639. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  640. con.TableAjaxLoadPage();// TODO: load current page
  641. }
  642. function tableAjaxCopy(args) {
  643. var recordID = args;
  644. if (typeof args == 'object') {
  645. recordID = args.shift();
  646. recordID = parseInt(recordID);
  647. }
  648. if (typeof recordID !== 'number' || recordID <= 0) {
  649. // TODO: msg
  650. return false;
  651. }
  652. if (!confirm('Czy na pewno chcesz utworzyc nowy rekord na podstawie danych z rekordu ID = ' + recordID + '?')) {
  653. return false;
  654. }
  655. var cont = jQuery('#<?php echo $this->_htmlID; ?>').parent();
  656. function notifyAjaxCallback(data) {
  657. var notify = {};
  658. notify.type = (data && data.type)? data.type : '';
  659. notify.msg = (data && data.msg)? data.msg : '';
  660. switch (notify.type) {
  661. case 'success':
  662. if (!notify.msg) notify.msg = 'OK';
  663. break;
  664. case 'info':
  665. if (!notify.msg) notify.msg = '';
  666. break;
  667. case 'error':
  668. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  669. break;
  670. case 'warning':
  671. notify.type = 'warn';
  672. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  673. break;
  674. default:
  675. notify.msg = 'Nieznany błąd';
  676. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  677. notify.type = '';
  678. }
  679. jQuery.notify(notify.msg, notify.type);
  680. }
  681. var reqData = {};
  682. jQuery.ajax({
  683. data: reqData,
  684. dataType: 'json',
  685. type: "GET",
  686. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=COPY&ID=' + recordID,
  687. })
  688. .done(function(data, textStatus, jqXHR){
  689. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  690. con.TableAjaxRefresh();
  691. notifyAjaxCallback(data);
  692. })
  693. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  694. if (jqXHR.responseJSON) {
  695. notifyAjaxCallback(jqXHR.responseJSON);
  696. }
  697. else {
  698. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  699. if (jqXHR.status == 404) {
  700. jQuery.notify(jqXHR.responseText, 'error');
  701. } else {
  702. jQuery.notify(jqXHR.responseText, 'warn');
  703. }
  704. }
  705. });
  706. return false;
  707. }
  708. function hidePopover() {
  709. var con = jQuery('#<?php echo $this->_htmlID; ?>');
  710. if (con) {
  711. var tblAjax = con.data('TableAjax');
  712. if (tblAjax) {
  713. tblAjax.popoverCellRemove();
  714. }
  715. }
  716. return false;
  717. }
  718. </script>
  719. <?php
  720. UI::inlineJS(__FILE__ . '.upload.js', [
  721. 'URL_UPLOAD_FILES_AJAX' => "index.php?_route=ViewTableAjax&_task=uploadFilesAjax",
  722. ]);
  723. UI::setTitle($this->_acl->getRawLabel(100) . " - " . UI::getTitle());
  724. return ob_get_clean();
  725. }
  726. public function _viewProcesInitListItem($vInitId, $gotoIds, $pInitList) {
  727. $vLabel = $pInitList[$vInitId];
  728. $kId = $vInitId;
  729. echo UI::h('a', [
  730. 'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
  731. 'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
  732. ], [
  733. UI::h('i', [
  734. 'class' => "glyphicon glyphicon-info-sign",
  735. 'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
  736. 'style' => "color:#aaa",
  737. 'onmouseover' => "this.style.color='#337AB7'",
  738. 'onmouseout' => "this.style.color='#aaa'"]),
  739. "{{$kId}} {$vLabel}"
  740. ]);
  741. }
  742. public function _viewProcesGotoAndRetListItem($vGotoId, $pInitList) {
  743. $vLabel = $pInitList[$vGotoId];
  744. $kId = $vGotoId;
  745. // TODO:?: prevent to execute procedure
  746. echo UI::h('a', [
  747. 'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
  748. 'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
  749. ], [
  750. UI::h('span', [ 'style' => "padding:10px;"]),
  751. UI::h('i', [ 'class' => "glyphicon glyphicon-arrow-right", 'style' => "color:#aaa"]),
  752. UI::h('i', [ 'class' => "glyphicon glyphicon-info-sign",
  753. 'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
  754. 'style' => "color:#aaa",
  755. 'onmouseover' => "this.style.color='#337AB7'",
  756. 'onmouseout' => "this.style.color='#aaa'"]),
  757. "{{$kId}} {$vLabel}",
  758. ]);
  759. }
  760. public function _viewProcesGotoAndRetLvl2ListItem($vGotoLvl2Id, $pInitList) {
  761. $vLabel = $pInitList[$vGotoLvl2Id];
  762. $kId = $vGotoLvl2Id;
  763. // TODO:?: prevent to execute procedure
  764. echo UI::h('a', [
  765. 'href' => "index.php?FUNCTION_INIT=MENU_SELECT_PROCES&_action=setPermsByProces&id_proces={$kId}&MENU_INIT=VIEWTABLE_AJAX&ZASOB_ID={$this->_zasobID}",
  766. 'title' => htmlspecialchars("{{$kId}} {$vLabel}"),
  767. ], [
  768. UI::h('span', [ 'style' => "padding:20px;" ]),
  769. UI::h('i', [ 'class' => "glyphicon glyphicon-arrow-right", 'style' => "color:#aaa" ]),
  770. UI::h('i', [ 'class' => "glyphicon glyphicon-info-sign",
  771. 'onclick' => "window.open('procesy5.php?task=PROCES_VIEW_LIST&id_proces={$kId}&HIDE_PANEL=0&show_big_img=1&group_stanowiska=1');return false;",
  772. 'style' => "color:#aaa",
  773. 'onmouseover' => "this.style.color='#337AB7'",
  774. 'onmouseout' => "this.style.color='#aaa'"]),
  775. "{{$kId}} {$vLabel}",
  776. ]);
  777. }
  778. public function hasAdditionalLayers() {
  779. $layers = TableAjaxMap::getAdditionalLayers($this->_zasobID);
  780. return !empty($layers);
  781. }
  782. public function ajaxTask($task) {
  783. switch ($task) {
  784. case 'EDIT_INLINE': {
  785. $this->sendAjaxResponseJson('ajaxInlineEdit', $_REQUEST);
  786. break;
  787. }
  788. case 'EDIT_INLINE_SAVE': {
  789. $this->sendAjaxResponseJson('ajaxEditInlineSave', $_REQUEST);
  790. break;
  791. }
  792. case 'COPY': {
  793. $this->sendAjaxResponseJson('ajaxCopy', $_REQUEST);
  794. break;
  795. }
  796. case 'CREATE_SAVE': { // TODO: mv to _route = ViewTableAjax & _task = createSaveAjax
  797. $this->sendAjaxResponseJson('ajaxCreateSave', $_REQUEST);
  798. break;
  799. }
  800. case 'HIST': {
  801. $this->sendAjaxResponseJson('ajaxHist', $_REQUEST);
  802. break;
  803. }
  804. case 'FILES': {
  805. try {
  806. $id = V::get('ID', 0, $_REQUEST, 'int');
  807. if ($id <= 0) throw new HttpException("404", 404);
  808. $this->sendAjaxFiles($id, $_REQUEST);
  809. } catch (HttpException $e) {
  810. Http::sendHeaderByCode($e->getCode());
  811. echo $e->getMessage();
  812. //UI::alert('danger', $e->getMessage());
  813. } catch (Exception $e) {
  814. echo '<div class="container">';
  815. UI::alert('danger', $e->getMessage());
  816. echo '</div>';
  817. }
  818. break;
  819. }
  820. case 'FILES_UPLOAD': {
  821. $this->sendAjaxResponseJson('ajaxFileUpload', $_REQUEST);
  822. break;
  823. }
  824. case 'FILES_LIST': {
  825. $this->sendAjaxResponseJson('ajaxFileList', $_REQUEST);
  826. break;
  827. }
  828. case 'filePermsRefresh': {
  829. $this->sendAjaxResponseJson('ajaxFilePermsRefresh', $_REQUEST);
  830. break;
  831. }
  832. case 'FILES_CONN_TBL_LIST': {
  833. $id = V::get('ID', 0, $_REQUEST, 'int');
  834. if ($id > 0) {
  835. $this->sendAjaxFilesConnTblList($id, $_REQUEST);
  836. } else {
  837. echo '404';
  838. }
  839. break;
  840. }
  841. case 'TYPESPECIAL': {
  842. $fldID = V::get('fldID', 0, $_REQUEST, 'int');
  843. if ($fldID > 0) {
  844. $this->sendTypeSpecial($fldID, $_REQUEST);
  845. } else {
  846. echo '404';
  847. }
  848. break;
  849. }
  850. case 'HIDDEN_COLS_SAVE': {
  851. $this->sendAjaxResponseJson('ajaxHiddenColsSave', $_POST);
  852. break;
  853. }
  854. case 'PAGE_SIZE_SAVE': {
  855. $this->sendAjaxResponseJson('ajaxPageSizeSave', $_POST);
  856. break;
  857. }
  858. case 'THE_GEOM_SAVE': {
  859. $this->sendAjaxResponseJson('ajaxTheGeomSave', $_REQUEST);
  860. break;
  861. }
  862. default:
  863. $this->sendAjaxResponseJson('ajaxData', $_REQUEST);
  864. }
  865. }
  866. /**
  867. * ajax url: &_task=EDIT_INLINE
  868. * @param $rowID - $_GET['ID']
  869. * @param $fieldName - $_GET['col']
  870. */
  871. private function ajaxInlineEdit() {
  872. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  873. $args = $_REQUEST;
  874. $idRecord = V::get('ID', 0, $_REQUEST, 'int');
  875. $fieldName = V::get('col', '', $_REQUEST);
  876. if ($idRecord <= 0 || empty($fieldName)) throw new HttpException("404", 404);
  877. $response = array();
  878. ob_start();
  879. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  880. if (!$fieldID) die("404: No field by name ({$fieldName})");
  881. $response['idZasob'] = $fieldID;
  882. $response['htmlFieldName'] = "f{$fieldID}";
  883. if ($DBG) echo "fieldID: {$fieldID}\n";
  884. $record = $this->_acl->buildQuery([])->getItem($idRecord);
  885. if (!$record) die("404: No item ID({$idRecord})");
  886. $fieldVal = '';
  887. if ($this->_acl->canReadObjectField($fieldName, $record)) {
  888. $fieldVal = V::get($fieldName, $fieldVal, $record);
  889. } else {
  890. $fieldVal = '*****';
  891. }
  892. $fieldVal = V::get("f{$fieldID}", $fieldVal, $_POST);
  893. $vCol = $this->_acl->getField($fieldID);
  894. $vCol['label'] = (!empty($vCol['label']))? $vCol['label'] : $vCol['name'];
  895. $response['fieldLabel'] = $vCol['label'];
  896. $tsValues = array();
  897. $typeSpecial = Typespecial::getInstance($fieldID, $vCol['name']);
  898. if ($typeSpecial) {
  899. 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>';}
  900. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record['ID'], $fieldName, V::get($fieldName, $fieldVal, $record));
  901. 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>';}
  902. if (!empty($specialValues)) {
  903. $tsValues[ $record['ID'] ] = implode('<br>', $specialValues);
  904. }
  905. }
  906. $fieldParams = array('widthClass'=>'inside-modal', 'maxGrid'=>6);
  907. if (!empty($tsValues[ $record['ID'] ])) $fieldParams['typespecialValue'] = $tsValues[ $record['ID'] ];
  908. if (!empty($tsValues[ $record['ID'] ])) $response['typespecialValue'] = $tsValues[ $record['ID'] ];
  909. $vDefault = $this->_acl->getFieldDefaultValue($fieldName);
  910. if (!empty($vDefault)) $fieldParams['default'] = $vDefault;
  911. if (!empty($vDefault)) $response['defaultValue'] = $vDefault;
  912. {
  913. try {
  914. $item = $this->_acl->getFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $record);
  915. $response['formItem'] = $item;
  916. if (!empty($item['rawColType']['simpleType'])) $response['simpleType'] = $item['rawColType']['simpleType'];
  917. if (!empty($item['rawColType']['restrictions'])) $response['restrictions'] = $item['rawColType']['restrictions'];
  918. echo '<div style="display:none">';
  919. DBG::_(true, true, "item", $item, __CLASS__, __FUNCTION__, __LINE__);
  920. echo '</div>';
  921. } catch (Exception $e) {
  922. echo '<div style="display:none">';
  923. UI::alert('danger', $e->getMessage());
  924. echo '</div>';
  925. }
  926. }
  927. ?>
  928. <label for="<?= "f{$fieldID}"; ?>" class="AjaxTableEdit-label">
  929. <strong title="<?= "[{$fieldID}] {$fieldName}"; ?>"><?= "{$vCol['label']}"; ?></strong>
  930. <?php if (!empty($vCol['opis'])) : ?>
  931. <em><?= $vCol['opis']; ?></em>
  932. <?php endif; ?>
  933. </label>
  934. <?php
  935. if (!$this->_acl->canWriteObjectField($fieldName, $record)) {
  936. // TODO: hide Zapisz btn on frontend side
  937. if (!$this->_acl->canReadObjectField($fieldName, $record)) {
  938. UI::alert('warning', "Brak uprawnień do odczytu i zapisu");
  939. } else {
  940. echo '<p style="margin-top:16px">' . $fieldVal . '</p>';
  941. UI::alert('warning', "Brak uprawnień do zapisu");
  942. }
  943. } else {
  944. echo $this->_acl->showFormItem('W', $fieldID, "f{$fieldID}", $fieldVal, $fieldParams, $record);
  945. if ($typeSpecial
  946. || $this->_acl->isDateField($fieldName)
  947. || $this->_acl->isDateTimeField($fieldName)
  948. ) {
  949. echo '<p style="padding:120px 0;"></p>';
  950. }
  951. }
  952. $response['legacy_html'] = ob_get_clean();
  953. //$response['legacy_html'] = utf8_encode($response['legacy_html']);// pl chars bug
  954. return $response;
  955. }
  956. private function ajaxEditInlineSave($args) {
  957. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  958. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  959. $fieldName = V::get('col', '', $_REQUEST);
  960. if (empty($primaryKey)) throw new HttpException("Wrong param id!", 400);
  961. if (empty($fieldName)) throw new HttpException("Wrong param col!", 400);
  962. $fieldID = $this->_acl->getFieldIdByName($fieldName);
  963. if (!$fieldID) throw new HttpException("Field not exists!", 404);
  964. $item = $this->_acl->buildQuery([])->getItem($primaryKey);
  965. if (!$item) throw new HttpException("Item not exists!", 404);
  966. $itemFromUser = $this->_acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  967. if (!isset($itemFromUser[$fieldName])) throw new HttpException("Field not set!", 400);
  968. $itemPatch = array();
  969. $itemPatch[$fieldName] = V::get($fieldName, null, $itemFromUser);
  970. $itemPatch[$primaryKeyField] = $primaryKey;
  971. $response = new stdClass();
  972. try {
  973. $affected = $this->_acl->updateItem($itemPatch);
  974. if ($affected > 0) {
  975. $response->type = 'success';
  976. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  977. } else if ($affected == 0) {
  978. $response->type = 'info';
  979. $response->msg = "Nie wprowadzono żadnych zmian";
  980. }
  981. $response->record = $this->_acl->buildQuery([])->getItem($primaryKey);
  982. }
  983. catch (Exception $e) {
  984. $response->type = 'error';
  985. $response->msg = $e->getMessage();
  986. }
  987. return $response;
  988. }
  989. public function sendAjaxEdit($id, $args) { // TODO: not used @see ViewTableAjax::editFormAction
  990. header("Content-type: text/plain");
  991. $acl = $this->_acl;
  992. $record = $acl->buildQuery([])->getItem($id);
  993. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
  994. UI::alert('danger', "Brak dostępu do rekordu");
  995. return;
  996. }
  997. $fieldsList = array();
  998. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  999. if ($fieldName == 'ID') continue;
  1000. $field['name'] = $fieldName;
  1001. $field['opis'] = $acl->getFieldOpis($fieldName);
  1002. $field['label'] = $acl->getFieldLabel($fieldName);
  1003. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  1004. $fieldsList[$kID] = $field;
  1005. }
  1006. $cols = array();
  1007. foreach ($fieldsList as $kID => $field) {
  1008. $cols[$kID] = '';
  1009. if ($this->_acl->canReadObjectField($field['name'], $record)) {
  1010. $cols[$kID] = V::get($field['name'], '', $record);
  1011. } else {
  1012. $cols[$kID] = '*****';
  1013. }
  1014. // if ($acl->canReadObjectField($field['name'])) {
  1015. // $cols[$kID] = V::get($field['name'], '', $record);
  1016. // } else {
  1017. // $cols[$kID] = '*****';
  1018. // }
  1019. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  1020. }
  1021. $tsValues = array();
  1022. if (!empty($fieldsList)) {
  1023. foreach ($fieldsList as $vColID => $vCol) {
  1024. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  1025. if ($typeSpecial) {
  1026. $colValue = V::get($vCol['name'], '', $record);
  1027. $specialValues = $typeSpecial->getEditSelectedValuesByIds($this->_zasobID, $record['ID'], $vCol['name'], $colValue);
  1028. if (!empty($specialValues)) {
  1029. $tsValues[$vColID] = implode('<br>', $specialValues);
  1030. }
  1031. }
  1032. }
  1033. }
  1034. $rowFunctionsOut = $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  1035. ?>
  1036. <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
  1037. <form class="form-horizontal" action="" method="post" id="EDIT_FRM_<?= $this->_htmlID; ?>">
  1038. <fieldset>
  1039. <legend>Edycja rekordu Nr <?= $record['ID']; ?><span class="pull-right valign-btns-bottom"><?= $rowFunctionsOut; ?></span></legend>
  1040. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  1041. <?php if ($acl->canWriteObjectField($vCol['name'], $record)) : ?>
  1042. <div class="form-group">
  1043. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?= "f{$kID}"; ?>"><?= $vCol['label']; ?>
  1044. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?= htmlspecialchars($vCol['opis']); ?>" data-original-title="<?= "[{$kID}] {$vCol['name']}"; ?>"></i>
  1045. </label>
  1046. <div class="col-xs-12 col-sm-9 col-md-10">
  1047. <?php
  1048. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  1049. if (!empty($tsValues[$kID])) {
  1050. $fieldParams['typespecialValue'] = $tsValues[$kID];
  1051. }
  1052. echo $acl->showFormItem('W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record);
  1053. ?>
  1054. </div>
  1055. </div>
  1056. <?php elseif ($acl->canReadObjectField($vCol['name'], $record)) : ?>
  1057. <div class="form-group">
  1058. <label class="col-xs-12 col-sm-3 col-md-2 control-label" for="<?= "f{$kID}"; ?>"><?= $vCol['label']; ?>
  1059. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?= htmlspecialchars($vCol['opis']); ?>" data-original-title="<?= "[{$kID}] {$vCol['name']}"; ?>"></i>
  1060. </label>
  1061. <div class="col-xs-12 col-sm-9 col-md-10">
  1062. <p style="margin-top:5px;">
  1063. <?php
  1064. //echo $acl->showFormItem('R', $kID, "f{$kID}", $cols[$kID], array('appendBack'=>true), $record);
  1065. if (!empty($tsValues[$kID])) {
  1066. echo $tsValues[$kID];
  1067. } else if (!empty($record[ $vCol['name'] ])) {
  1068. echo $record[ $vCol['name'] ];
  1069. }
  1070. ?>
  1071. </p>
  1072. </div>
  1073. </div>
  1074. <?php endif; ?>
  1075. <?php endforeach; ?>
  1076. <div class="form-group">
  1077. <div class="col-xs-offset-0 col-xs-12 col-sm-offset-3 col-sm-9 col-md-offset-2 col-md-10">
  1078. <button type="submit" class="btn btn-primary" tabindex="<?= (++$tabindex); ?>">Zapisz</button>
  1079. </div>
  1080. </div>
  1081. </fieldset>
  1082. </form>
  1083. <p style="padding:100px 0;"></p>
  1084. </div>
  1085. <script>
  1086. jQuery(document).ready(function(){
  1087. jQuery('textarea').autosize();
  1088. jQuery('.frm-help').popover({trigger:'hover'});
  1089. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  1090. var formData = {};
  1091. jQuery(this).serializeArray().map(function(i) { formData[i.name] = i.value; });// TODO: edit Widget - send only updated fields
  1092. // TODO: change Edit btn to return to edit record with fields -> show form
  1093. var taskCont = jQuery('#<?php echo $this->_htmlID; ?>_task').parent();
  1094. //taskCont.empty();
  1095. taskCont.children().fadeOut('slow');
  1096. var alertCntWrap = jQuery('<div class="AjaxTableAlert AjaxTable-loading"></div>').prependTo(taskCont)
  1097. , alertCnt = jQuery('<div class="container"></div>').prependTo(alertCntWrap);
  1098. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> zapisywanie ... </div></div>').appendTo(alertCnt);
  1099. function notifyAjaxCallback(data) {
  1100. var notify = {}, outMsg = '';
  1101. notify.type = (data && data.type)? data.type : '';
  1102. notify.msg = (data && data.msg)? data.msg : '';
  1103. switch (notify.type) {
  1104. case 'success':
  1105. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  1106. break;
  1107. case 'info':
  1108. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  1109. break;
  1110. case 'error':
  1111. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1112. break;
  1113. case 'warning':
  1114. notify.type = 'warn';
  1115. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1116. break;
  1117. default:
  1118. notify.msg = 'Nieznany błąd';
  1119. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  1120. notify.type = '';
  1121. }
  1122. jQuery.notify(notify.msg, notify.type);
  1123. var alertType = ('error' == data.type) ? 'danger' : data.type;
  1124. outMsg = '<div class="alert alert-' + alertType + '">' + notify.msg + '</div>';
  1125. return outMsg;
  1126. }
  1127. superagent
  1128. .post('<?= $this->syncUrl; ?>&_hash=<?= $this->_htmlID; ?>&_task=editSaveAjax')
  1129. .type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
  1130. .send({
  1131. namespace: '<?= $acl->getNamespace(); ?>',
  1132. primaryKey: '<?= $record['ID']; ?>',
  1133. form: formData
  1134. })
  1135. .set('Accept', 'application/json')
  1136. .end(function(err, res) {
  1137. var payload;
  1138. if (err || !res.ok || 'application/json' !== res.type) {
  1139. payload = {type: 'warning', msg: res.body.msg || 'Wystąpiły błędy', body: res.body};
  1140. } else {
  1141. payload = {type: 'success', msg: res.body.msg || '', body: res.body};
  1142. }
  1143. var data = res.body;
  1144. alertCntWrap.removeClass('AjaxTable-loading');
  1145. alertCnt.empty();
  1146. if (false === ['success', 'info'].indexOf(payload.type)) {
  1147. jQuery(errorTxt).appendTo(alertCnt);
  1148. var errLinks = jQuery('<div class="breadcrumb"></div>').appendTo(alertCnt);
  1149. jQuery('<a href="#" onclick="return tableAjaxBackToTable();"> <i class="icon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>').appendTo(errLinks);
  1150. 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);
  1151. backToEditBtn.on('click', function(){
  1152. alertCnt.remove();
  1153. taskCont.children().fadeIn('slow');
  1154. return false;
  1155. });
  1156. } else {
  1157. var outMsg = notifyAjaxCallback(payload);
  1158. var out = '';
  1159. out += outMsg;
  1160. out += '<div class="breadcrumb">' +
  1161. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  1162. ' <a href="#EDIT/<?php echo $id; ?>/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord <?php echo $id; ?></a>' +
  1163. '</div>';
  1164. jQuery(out).appendTo(alertCnt);
  1165. // add rowFunctions from response
  1166. if (data && data.rowFunctions && data.primaryKey) {
  1167. var rowFunWrapNode = $('<div class="container"></div>').insertAfter(alertCnt);
  1168. var rowFunListNode = $('<ul></ul>').appendTo(rowFunWrapNode);
  1169. var keys = Object.keys(data.rowFunctions),
  1170. total = keys.length,
  1171. moreFuncBtnNode,
  1172. moreFunctions = [],
  1173. idx
  1174. ;
  1175. moreFunctions = keys.splice(3);
  1176. keys.forEach(function(key) {
  1177. var cellNode = $('<li></li>');
  1178. var funObj = data.rowFunctions[key],
  1179. funcNode = p5UI_TableAjax_generateFunctionNode(funObj, data.primaryKey, {ico: true, label: true})
  1180. ;
  1181. funcNode.appendTo(cellNode);
  1182. cellNode.appendTo(rowFunListNode);
  1183. });
  1184. }
  1185. }
  1186. });
  1187. return false;
  1188. });
  1189. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value input').on('input', function(e) {
  1190. var input, btn, btnIco;
  1191. input = jQuery(e.target);
  1192. btn = input.next('.button-appendBack');
  1193. btnIco = btn.find('.glyphicon');
  1194. if (btn.attr('title') != input.val()) {
  1195. btnIco.show();
  1196. } else {
  1197. btnIco.hide();
  1198. }
  1199. });
  1200. jQuery('#EDIT_FRM_<?php echo $this->_htmlID; ?>').find('.show-last-value').find('.button-appendBack').on('click', function(e) {
  1201. var input, btn, btnIco;
  1202. btn = jQuery(this);
  1203. btnIco = btn.find('.glyphicon');
  1204. input = btn.prev();
  1205. if (input.is('input')) {
  1206. if (btn.attr('title') != input.val()) {
  1207. input.val(btn.attr('title'));
  1208. btnIco.hide();
  1209. }
  1210. }
  1211. });
  1212. });
  1213. </script>
  1214. <?php
  1215. exit;
  1216. }
  1217. public function sendAjaxCreate($args = []) {
  1218. $acl = $this->_acl;
  1219. header("Content-type: text/plain");
  1220. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  1221. if (!Core_AclHelper::hasCreatePerms($acl)) {
  1222. UI::alert('danger', "Brak uprawnień do utworzenia nowego rekordu.");
  1223. return;
  1224. }
  1225. $cols = array();
  1226. $forceFilterInit = array();
  1227. $defaultAclGroup = User::getDefaultAclGroup();
  1228. if ($defaultAclGroup) {
  1229. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  1230. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  1231. }
  1232. foreach ($_GET as $k => $v) {
  1233. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  1234. $fldName = substr($k, 3);
  1235. $forceFilterInit[$fldName] = $v;
  1236. }
  1237. }
  1238. $pkField = $acl->getPrimaryKeyField();
  1239. $fieldsList = $acl->getFields();
  1240. $fieldsList = array_filter($fieldsList, function ($vCol) {
  1241. return ($vCol['name'] != $pkField);
  1242. });
  1243. foreach ($fieldsList as $kID => $vCol) {
  1244. $defaultValue = '';
  1245. if (!empty($forceFilterInit[$vCol['name']])) {
  1246. $defaultValue = $forceFilterInit[$vCol['name']];
  1247. }
  1248. // TODO: read from session cache
  1249. $cols[$kID] = V::get("f{$kID}", $defaultValue, $_POST);
  1250. $label = V::get('label', '', $vCol);
  1251. $fieldsList[$kID]['label'] = ($label) ? $label : $vCol['name'];
  1252. }
  1253. ?>
  1254. <div class="container AjaxFrmHorizontalEdit" style="max-width:940px">
  1255. <form action="" method="post" id="CREATE_FRM_<?php echo $this->_htmlID; ?>">
  1256. <fieldset>
  1257. <legend>Dodaj nowy rekord</legend>
  1258. <?php $tabindex = 0; foreach ($fieldsList as $kID => $vCol) : ?>
  1259. <?php if ($acl->canCreateField($vCol['name'])) : ?>
  1260. <div class="form-group">
  1261. <label class="control-label" for="<?php echo "f{$kID}"; ?>"><?= V::get('label', $vCol['name'], $vCol); ?>
  1262. <i class="glyphicon glyphicon-info-sign frm-help" data-toggle="popover" data-trigger="hover" title="" data-content="<?php echo htmlspecialchars(V::get('opis', '', $vCol)); ?>" data-original-title="<?php echo "[{$kID}] {$vCol['name']}"; ?>"></i>
  1263. </label>
  1264. <div>
  1265. <?php
  1266. $fieldParams = array('appendBack'=>true, 'tabindex'=>(++$tabindex), 'maxGrid'=>8);
  1267. echo $acl->showFormItem('C', $kID, "f{$kID}", $cols[$kID], $fieldParams);
  1268. ?>
  1269. </div>
  1270. </div>
  1271. <?php endif; ?>
  1272. <?php endforeach; ?>
  1273. <div class="form-group">
  1274. <button type="submit" class="btn btn-primary" tabindex="<?php echo (++$tabindex); ?>">Dodaj rekord</button>
  1275. </div>
  1276. </fieldset>
  1277. </form>
  1278. </div>
  1279. <script>
  1280. jQuery(document).ready(function(){
  1281. jQuery('textarea').autosize();
  1282. jQuery('.frm-help').popover({trigger:'hover'});
  1283. jQuery('#CREATE_FRM_<?php echo $this->_htmlID; ?>').on('submit', function(){
  1284. var data = jQuery(this).serialize();
  1285. var taskContLast = jQuery('#<?php echo $this->_htmlID; ?>_task'),
  1286. taskCont = taskContLast.parent();
  1287. taskContLast.fadeOut('slow');
  1288. var taskCnt = jQuery('<div id="<?php echo $this->_htmlID . '_task'; ?>" class="AjaxTableTaskCnt AjaxTable-loading"></div>').appendTo(taskCont);
  1289. jQuery('<div class="alert alert-danger"><div style="padding:0 0 0 20px; background:url(./icon/loading.gif) no-repeat left top;"> save ... </div></div>').appendTo(taskCnt);
  1290. function notifyAjaxCallback(data) {
  1291. var notify = {};
  1292. notify.type = (data && data.type)? data.type : '';
  1293. notify.msg = (data && data.msg)? data.msg : '';
  1294. switch (notify.type) {
  1295. case 'success':
  1296. if (!notify.msg) notify.msg = 'OK';
  1297. break;
  1298. case 'info':
  1299. if (!notify.msg) notify.msg = '';
  1300. break;
  1301. case 'error':
  1302. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1303. break;
  1304. case 'warning':
  1305. notify.type = 'warn';
  1306. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  1307. break;
  1308. default:
  1309. notify.msg = 'Nieznany błąd';
  1310. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  1311. notify.type = '';
  1312. }
  1313. jQuery.notify(notify.msg, notify.type);
  1314. }
  1315. $.ajax({
  1316. data: data,
  1317. dataType: 'json',
  1318. type: "POST",
  1319. async: true,
  1320. url: 'index-ajax.php?_zasobID=<?php echo $this->_zasobID; ?>&_cls=<?php echo __CLASS__; ?>&_hash=<?php echo $this->_htmlID; ?>&_task=CREATE_SAVE'
  1321. })
  1322. .always(function(dataOrJqXHR){
  1323. var data;
  1324. if (dataOrJqXHR && 'readyState' in dataOrJqXHR && 'status' in dataOrJqXHR) {
  1325. if ('responseJSON' in dataOrJqXHR) {
  1326. data = dataOrJqXHR.responseJSON;
  1327. } else {
  1328. data = {};
  1329. data.msg = dataOrJqXHR.responseText || 'Nieznany błąd';
  1330. if (dataOrJqXHR.status == 404) {
  1331. data.type = 'error';
  1332. } else {
  1333. data.type = 'warning';
  1334. }
  1335. }
  1336. }
  1337. else {
  1338. data = dataOrJqXHR;
  1339. }
  1340. notifyAjaxCallback(data);
  1341. taskCnt.removeClass('AjaxTable-loading');
  1342. taskCnt.empty();
  1343. if (data.type == 'error' || data.type == 'warning') {
  1344. var out = '<div class="container">' +
  1345. '<div class="alert alert-danger">' +
  1346. '<h4>Wystąpiły błędy!</h4>' + data.msg +
  1347. (('errors' in data)? '<p>' + data.errors + '</p>' : '') +
  1348. '</div>';
  1349. out += '<div class="breadcrumb">' +
  1350. ' <a class="create-fix" href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do formularza i popraw dane</a></li>' +
  1351. '</div>' +
  1352. '</div>';
  1353. jQuery(out).appendTo(taskCnt);
  1354. var taskContLastNode = taskContLast
  1355. , taskCntNode = taskCnt;
  1356. taskCnt.find('.create-fix').click(function(){
  1357. taskCntNode.remove();
  1358. taskContLastNode.fadeIn('slow');
  1359. return false;
  1360. });
  1361. }
  1362. else if (data.type == 'success') {
  1363. var msg = '';
  1364. if (data.id && data.id > 0) {
  1365. msg = 'Utworzono pomyślnie rekord: ID = ' + data.id;
  1366. } else if (data.msg) {
  1367. msg = data.msg;
  1368. } else {
  1369. msg = 'OK';
  1370. }
  1371. var out = '<div class="container">';
  1372. out += '<div class="alert alert-success">' + msg + '</div>';
  1373. out += '<div class="breadcrumb">' +
  1374. ' <a href="#" onclick="return tableAjaxBackToTable();" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-arrow-left"></i> Wróć do tabeli <?php echo $this->getLabelHtml(); ?></a>' +
  1375. ' <a href="#EDIT/' + data.id + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-pencil"></i> Edytuj rekord ' + data.id + '</a>' +
  1376. ' <a href="#CREATE/' + Math.random(1).toString().substr(2) + '" class="btn btn-link btn-sm"> <i class="glyphicon glyphicon-plus"></i> Dodaj nowy rekord</a></li>' +
  1377. '</div>';
  1378. out += '</div>';
  1379. jQuery(out).appendTo(taskCnt);
  1380. }
  1381. });
  1382. return false;
  1383. });
  1384. });
  1385. </script>
  1386. <?php
  1387. exit;
  1388. }
  1389. private function ajaxCreateSave($args) {
  1390. DBG::log($args, 'array', "ajaxCreateSave");
  1391. $acl = $this->_acl;
  1392. $response = new stdClass();
  1393. $createdId = null;
  1394. try {
  1395. $item = $acl->convertObjectFromUserInput($args, $type = 'array_by_id', $prefix = 'f');
  1396. $createdId = $acl->addItem($item);
  1397. if ($createdId) {
  1398. $response->type = 'success';
  1399. $response->msg = "Utworzono pomyślnie rekord nr {$createdId}";
  1400. $response->id = $createdId;
  1401. $response->record = $acl->buildQuery([])->getItem($createdId);
  1402. }
  1403. else {
  1404. $response->type = 'error';
  1405. $response->msg = "Nie udało się utworzyć nowego rekordu!";
  1406. }
  1407. }
  1408. catch (Exception $e) {
  1409. $response->type = 'error';
  1410. $response->msg = $e->getMessage();
  1411. }
  1412. return $response;
  1413. }
  1414. private function ajaxCopy($args) {
  1415. $acl = $this->_acl;
  1416. $id = V::get('ID', 0, $_REQUEST, 'int');
  1417. if ($id <= 0) {
  1418. throw new HttpException("Wrong param ID!", 404);
  1419. }
  1420. $item = $acl->buildQuery([])->getItem($id);
  1421. if (!$item) {
  1422. throw new HttpException("Item '{$id}' not exists!", 404);
  1423. }
  1424. $response = new stdClass();
  1425. $itemCopy = $acl->createItemCopy($item);
  1426. $createdId = null;
  1427. try {
  1428. $createdId = $acl->addItem($itemCopy);
  1429. if ($createdId) {
  1430. $response->type = 'success';
  1431. $response->msg = "Rekord skopiowany pomyślnie - utworzono rekord nr {$createdId}";
  1432. $response->id = $createdId;
  1433. $response->record = $acl->buildQuery([])->getItem($createdId);
  1434. }
  1435. else {
  1436. $response->type = 'error';
  1437. $response->msg = "Nie udało się skopiować rekordu!";
  1438. }
  1439. }
  1440. catch (Exception $e) {
  1441. $response->type = 'error';
  1442. $response->msg = "Wystąpiły błędy!";
  1443. $response->msg = $e->getMessage();
  1444. }
  1445. return $response;
  1446. }
  1447. private function ajaxHist($args) {
  1448. $jsonResponse = array();
  1449. $id = V::get('ID', 0, $args, 'int');
  1450. $acl = $this->_acl;
  1451. $record = $acl->buildQuery([])->getItem($id);
  1452. if (!$record) throw new HttpException("404: No item ID({$id})", 404);
  1453. $visibleCols = $acl->getRealFieldList();
  1454. try {
  1455. $rowsHist = $acl->getHistItems($id);
  1456. } catch (Exception $e) {
  1457. DBG::log($e);
  1458. $rowsHist = [];
  1459. }
  1460. $jsonResponse['row_functions'] = $this->_parseRowFunctions($record['ID'], array('hist', 'cp'), $showLabel = true);
  1461. $visibleColsWithIds = array();
  1462. $visibleColsLabels = array();
  1463. foreach ($visibleCols as $vColName) {
  1464. $fldId = $acl->getFieldIdByName($vColName);
  1465. if ($fldId) {
  1466. $visibleColsWithIds[$fldId] = $vColName;
  1467. $label = $acl->getFieldLabel($vColName);
  1468. $label = (!$label)? $vColName : '<span title="' . "[{$fldId}] {$vColName}" . '">' . $label . '</span>';
  1469. $visibleColsLabels[$fldId] = $label;
  1470. }
  1471. }
  1472. $jsonResponse['label'] = "Historia rekordu Nr {$id}";
  1473. $jsonResponse['fields'] = array_values($visibleColsWithIds);
  1474. $jsonResponse['field_label'] = $visibleColsLabels;
  1475. if (empty($rowsHist)) return $jsonResponse;
  1476. $jsonResponse['rows'] = array();
  1477. foreach ($rowsHist as $histRow) {
  1478. $histItem = array();
  1479. $histItem['ID'] = V::get('ID', '', $histRow);
  1480. $histItem['_created'] = V::get('_created', '', $histRow);
  1481. $histItem['_author'] = V::get('_author', '', $histRow);
  1482. $histItem['changes'] = array();
  1483. foreach ($visibleColsWithIds as $fldId => $fieldName) {
  1484. if (!array_key_exists($fieldName, (array)$histRow)) continue;
  1485. $value = V::get($fieldName, '', $histRow);
  1486. if ('N/S;' == $value) continue;
  1487. $changeItem = array();
  1488. $changeItem['fieldName'] = $fieldName;
  1489. $changeItem['acl_read'] = $acl->canReadObjectField($fieldName, $record);
  1490. if ($changeItem['acl_read']) {
  1491. $changeItem['value'] = V::get($fieldName, '', $histRow);
  1492. }
  1493. if ('the_geom' == $fieldName && $acl->canWriteObjectField($fieldName, $record)) {
  1494. $sourceName = $acl->getSourceName();
  1495. if ('default_db' == $sourceName && !empty($value)) {
  1496. $typeName = $acl->getName();
  1497. $idHist = V::get('ID', '', $histRow);
  1498. $changeItem['revert_function_url'] = Request::getPathUri() . "index.php?_route=ViewTableAjax&typeName=p5_{$sourceName}:{$typeName}&_task=revertFromHistAjax&ID={$id}&idHist={$idHist}&fieldName={$fieldName}";
  1499. $changeItem['revert_function_data'] = "ID={$id}&idHist={$idHist}&fieldName={$fieldName}";
  1500. }
  1501. }
  1502. $histItem['changes'][$fieldName] = $changeItem;
  1503. }
  1504. $jsonResponse['rows'][] = $histItem;
  1505. }
  1506. return $jsonResponse;
  1507. }
  1508. public function ajaxFileUpload($args) {
  1509. $id = V::get('ID', 0, $args, 'int');
  1510. if ($id <= 0) throw new HttpException("404", 404);
  1511. $dbID = $this->_acl->getDB();
  1512. $db = DB::getDB($dbID);
  1513. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1514. $record = $this->_acl->buildQuery([])->getItem($id);
  1515. if (!$record) throw new HttpException("No item ID({$id})", 404);
  1516. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1517. if (!$this->_acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  1518. $tblName = $this->_acl->getName();
  1519. $confTblName = "{$tblName}_COLUMN";
  1520. $folderConfAll = FoldersConfig::getRawData();
  1521. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  1522. $folderConf = FoldersConfig::getAll($confTblName);
  1523. $uploader = new FileUploader($confTblName, (object)$record);
  1524. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  1525. $uploader->findFolder();
  1526. $errorMsg = '';
  1527. if (!empty($args['SCANS_COLUMN_ADD'])) {
  1528. $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  1529. }
  1530. else {
  1531. $uploaded = $uploader->tryUploadAjax($errorMsg);
  1532. }
  1533. $retJson = new stdClass();
  1534. if (!$uploaded) throw new Exception($errorMsg);
  1535. $uploadedFileName = '';
  1536. $uploadedFile = $uploader->getLastUploadedFile();
  1537. if ($uploadedFile) {
  1538. $uploadedFileName = explode('/', $uploadedFile);
  1539. $uploadedFileName = end($uploadedFileName);
  1540. }
  1541. //echo '{"type":"SUCCESS", "string": "Plik został poprawnie wgrany do odpowiedniego katalogu '.$uploadedFileName.'"}';
  1542. $retJson->type = 'SUCCESS';
  1543. $retJson->msg = "Plik został poprawnie wgrany do odpowiedniego katalogu {$uploadedFileName}";
  1544. if (!empty($uploadedFileName)) {
  1545. $sqlObj = new stdClass();
  1546. $sqlObj->ID = $record['ID'];
  1547. $sqlObj->M_DIST_FILES = "Wgrano plik {$uploadedFileName}";
  1548. $db->UPDATE_OBJ($this->_tbl, $sqlObj);
  1549. }
  1550. return $retJson;
  1551. }
  1552. public function ajaxFileList($args) {
  1553. $id = V::get('ID', 0, $args, 'int');
  1554. if ($id <= 0) throw new HttpException("404", 404);
  1555. $dbID = $this->_acl->getDB();
  1556. $db = DB::getDB($dbID);
  1557. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1558. $record = $this->_acl->buildQuery([])->getItem($id);
  1559. if (!$record) throw new HttpException("No item ID({$id})", 404);
  1560. if (!$this->_acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1561. $tblName = $this->_acl->getName();
  1562. $confTblName = "{$tblName}_COLUMN";
  1563. $folderConfAll = FoldersConfig::getRawData();
  1564. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  1565. $folderConf = FoldersConfig::getAll($confTblName);
  1566. $uploader = new FileUploader($confTblName, (object)$record);
  1567. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  1568. $uploader->findFolder();
  1569. $mainFolder = $uploader->getDestFolder();
  1570. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  1571. $localPath = $uploader->getLocalPath();
  1572. $folderWeb = $uploader->getFolderWeb();
  1573. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  1574. return $jsonFiles;
  1575. }
  1576. private function ajaxFilePermsRefresh($args) {
  1577. $id = V::get('ID', 0, $args, 'int');
  1578. if ($id <= 0) throw new HttpException("Wrong param ID", 404);
  1579. $dbID = $this->_acl->getDB();
  1580. $db = DB::getDB($dbID);
  1581. if (!$db) throw new HttpException("No DB", 406);
  1582. $record = $this->_acl->buildQuery([])->getItem($id);
  1583. if (!$record) throw new Exception("No item ID({$id})", 404);
  1584. $tblName = $this->_acl->getName();
  1585. // TODO: SyncPermsCustomTables->getRecordTask($tbl, $id);
  1586. $sql_L_APPOITMENT_USER = V::get('L_APPOITMENT_USER', '', $record);
  1587. $sql_A_ADM_COMPANY = V::get('A_ADM_COMPANY', '', $record);
  1588. $sql_A_CLASSIFIED = V::get('A_CLASSIFIED', '', $record);
  1589. $mainDB = DB::getDB();
  1590. if ('IN7_MK_BAZA_DYSTRYBUCJI' == $tblName) {
  1591. $sql = "insert into `_SYNC_FILE_PERMS` (
  1592. `ID_PROJECT`,
  1593. `A_SYNCHRONIZED`
  1594. )
  1595. values (
  1596. '{$record['ID']}'
  1597. , 0
  1598. )
  1599. ON DUPLICATE KEY UPDATE
  1600. `A_SYNCHRONIZED`=0
  1601. ";
  1602. }
  1603. else if ('IN7_DZIENNIK_KORESP' == $tblName) {
  1604. $sql = "insert into `_SYNC_FILE_PERMS` (
  1605. `ID_PROJECT`,
  1606. `A_SYNCHRONIZED`
  1607. )
  1608. values (
  1609. '{$record['ID_PROJECT']}'
  1610. , 0
  1611. )
  1612. ON DUPLICATE KEY UPDATE
  1613. `A_SYNCHRONIZED`=0
  1614. ";
  1615. }
  1616. else {
  1617. $sql = "insert into `_SYNC_TABLE_FILE_PERMS` (
  1618. `TBL_NAME`,
  1619. `TBL_ID`,
  1620. `L_APPOITMENT_USER`,
  1621. `A_ADM_COMPANY`,
  1622. `A_CLASSIFIED`,
  1623. `A_SYNCHRONIZED`
  1624. )
  1625. values (
  1626. '{$tblName}'
  1627. , '{$id}'
  1628. , '{$sql_L_APPOITMENT_USER}'
  1629. , '{$sql_A_ADM_COMPANY}'
  1630. , '{$sql_A_CLASSIFIED}'
  1631. , 0
  1632. )
  1633. ON DUPLICATE KEY UPDATE
  1634. `A_SYNCHRONIZED`=0
  1635. ";
  1636. }
  1637. $res = $mainDB->query($sql);
  1638. if ($mainDB->has_errors()) {
  1639. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($sql);echo'</pre>';
  1640. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;"> (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($mainDB->get_errors());echo'</pre>';
  1641. throw new Exception("Nie udało się dodać zadania");
  1642. }
  1643. // TODO: this blocks browser ajax query
  1644. //$limit = 3;
  1645. //while ($limit--) {
  1646. // sleep(10);
  1647. // TODO: check if task is done
  1648. //}
  1649. $confTblName = "{$tblName}_COLUMN";
  1650. $folderConfAll = FoldersConfig::getRawData();
  1651. if (!FoldersConfig::hasConfig($confTblName)) {
  1652. throw new Exception("Brak danych konfiguracyjnych ({$tblName})", 404);
  1653. }
  1654. $folderConf = FoldersConfig::getAll($confTblName);
  1655. $uploader = new FileUploader($confTblName, (object)$record);
  1656. if (!$uploader->setConfig($folderConf)) {
  1657. throw new Exception("Błąd danych konfiguracyjnych ({$tblName})", 404);
  1658. }
  1659. $uploader->findFolder();
  1660. $mainFolder = $uploader->getDestFolder();
  1661. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  1662. $localPath = $uploader->getLocalPath();
  1663. $folderWeb = $uploader->getFolderWeb();
  1664. $jsonData = new stdClass();
  1665. $jsonData->msg = 'Zadanie dodane';
  1666. $jsonData->type = 'success';
  1667. $jsonData->files = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  1668. return $jsonData;
  1669. }
  1670. private function sendAjaxFilesConnTblList($id, $args) {
  1671. header("Content-type: application/json");
  1672. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  1673. $dbID = $this->_acl->getDB();
  1674. $db = DB::getDB($dbID);
  1675. if (!$db) {
  1676. header('HTTP/1.0 406 Not Acceptable');
  1677. echo 'No DB (' . $dbID . ')';
  1678. exit;
  1679. }
  1680. $record = $this->_acl->buildQuery([])->getItem($id);
  1681. if (!$record) {
  1682. header('HTTP/1.0 404 Not Found');
  1683. echo 'No item ID(' . $rowID . ')';
  1684. exit;
  1685. }
  1686. $connTblName = '';
  1687. $connTblID = V::get('connTblID', 0, $_REQUEST, 'int');
  1688. if ($connTblID <= 0) {
  1689. header('HTTP/1.0 406 Not Acceptable');
  1690. echo 'No conn Table ID';
  1691. exit;
  1692. }
  1693. $connTblTypespecials = $this->getConnectedTblTypespecials($connTblID);
  1694. if (empty($connTblTypespecials)) {
  1695. header('HTTP/1.0 406 Not Acceptable');
  1696. echo "No conn Table (ID={$connTblID})";
  1697. exit;
  1698. }
  1699. 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>';}
  1700. if(1) {
  1701. header('HTTP/1.0 404 Not Found');
  1702. echo 'TODO: ...';
  1703. exit;
  1704. }
  1705. $tblName = $this->_acl->getName();
  1706. $confTblName = "{$tblName}_COLUMN";
  1707. $folderConfAll = FoldersConfig::getRawData();
  1708. if (!FoldersConfig::hasConfig($confTblName)) {
  1709. header('HTTP/1.0 404 Not Found');
  1710. echo '{"type":"ERROR", "string": "Brak danych konfiguracyjnych (' . $tblName . ')"}';
  1711. exit;
  1712. }
  1713. $folderConf = FoldersConfig::getAll($confTblName);
  1714. $uploader = new FileUploader($confTblName, (object)$record);
  1715. if (!$uploader->setConfig($folderConf)) {
  1716. header('HTTP/1.0 404 Not Found');
  1717. echo '{"type":"ERROR", "string": "Błąd danych konfiguracyjnych (' . $tblName . ')"}';
  1718. exit;
  1719. }
  1720. $uploader->findFolder();
  1721. $mainFolder = $uploader->getDestFolder();
  1722. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  1723. $localPath = $uploader->getLocalPath();
  1724. $folderWeb = $uploader->getFolderWeb();
  1725. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  1726. echo json_encode($jsonFiles);
  1727. exit;
  1728. }
  1729. public function convertFileListToJson($files, $folderWeb, $localPath, $mainFolder) {
  1730. $jsonFiles = array();
  1731. if (!is_array($files) || empty($files)) {
  1732. return $jsonFiles;
  1733. }
  1734. sort($files);
  1735. foreach ($files as $vFilePath) {
  1736. $file = new stdClass();
  1737. $file->name = str_replace("{$localPath}/{$mainFolder}/", '', $vFilePath);
  1738. //$file->name = explode('/', $vFilePath);
  1739. //$file->name = end($file->name);
  1740. $file->size = filesize($vFilePath);
  1741. $file->sizeStr = V::humanFileSize($file->size);
  1742. $file->type = '';
  1743. $file->created = date("Y-m-d H:i:s", filectime($vFilePath));
  1744. $file->web = str_replace($localPath, $folderWeb, $vFilePath);
  1745. $jsonFiles[] = $file;
  1746. }
  1747. return $jsonFiles;
  1748. }
  1749. private function getConnectedTables() {
  1750. $connTbls = array();
  1751. return $connTbls;// TODO: OFF - hardlinki tworzone w bash_sync_perms.php
  1752. $fields = $this->_acl->getVirtualFieldListByIdZasob();
  1753. if (!empty($fields)) {
  1754. foreach ($fields as $vColID => $vCol) {
  1755. $typeSpecial = Typespecial::getInstance($vColID);
  1756. if ($typeSpecial) {
  1757. $tsConnTbls = $typeSpecial->getTblAliasList();
  1758. if (!empty($tsConnTbls)) {
  1759. foreach ($tsConnTbls as $kID => $vName) {
  1760. $connTbls[$kID] = $vName;
  1761. }
  1762. }
  1763. }
  1764. }
  1765. }
  1766. return $connTbls;
  1767. }
  1768. private function getConnectedTblTypespecials($connTblID) {
  1769. $connTblTypespecials = array();
  1770. $fields = $this->_acl->getVirtualFieldListByIdZasob();
  1771. if (!empty($fields)) {
  1772. foreach ($fields as $vColID => $vCol) {
  1773. $typeSpecial = Typespecial::getInstance($vColID);
  1774. if ($typeSpecial) {
  1775. $tsConnTbls = $typeSpecial->getTblAliasList();
  1776. if (array_key_exists($connTblID, $tsConnTbls)) {
  1777. $connTblTypespecials[] = $typeSpecial;
  1778. }
  1779. }
  1780. }
  1781. }
  1782. return $connTblTypespecials;
  1783. }
  1784. private function sendAjaxFiles($id, $args) {
  1785. header("Content-type: text/plain");
  1786. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  1787. $acl = $this->_acl;
  1788. $dbID = $acl->getDB();
  1789. $db = DB::getDB($dbID);
  1790. if (!$db) throw new HttpException("", 406);
  1791. $record = $acl->buildQuery([])->getItem($id);
  1792. if (!$record) throw new HttpException("404: No item ID({$rowID})", 404);
  1793. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1794. $tblName = $acl->getName();
  1795. $confTblName = "{$tblName}_COLUMN";
  1796. $folderConfAll = FoldersConfig::getRawData();
  1797. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych", 404);
  1798. $folderConf = FoldersConfig::getAll($confTblName);
  1799. //echo'<pre style="max-height:200px;overflow:auto;border:1px solid red;text-align:left;">$folderConf (' . __CLASS__ . '::' . __FUNCTION__ . ':' . __LINE__ . '): ';print_r($folderConf);echo'</pre>';
  1800. $uploader = new FileUploader($confTblName, (object)$record);
  1801. $errMsg = '';
  1802. if (!$uploader->setConfig($folderConf, $errMsg)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})" . '<br>' . "\n" . $errMsg, 404);
  1803. $uploader->findFolder();
  1804. 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>'; }
  1805. $mainFolder = $uploader->getDestFolder();
  1806. 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>'; }
  1807. if (!$mainFolder) {
  1808. $destFolderPath = $uploader->getDestLocalPath(true);
  1809. $folderCreated = $uploader->tryCreateDestFolder($destFolderPath);
  1810. if ($folderCreated) {
  1811. //UI::alert('info', "Utworzono katalog");
  1812. $uploader->findFolder();
  1813. $mainFolder = $uploader->getDestFolder();
  1814. } else {
  1815. UI::alert('warning', "Nie udało się utworzyć katalogu");
  1816. }
  1817. }
  1818. $files = $uploader->getFilesFromFolder($mainFolder, false, true);
  1819. 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>'; }
  1820. $sharePoint = V::get('share_point', null, $folderConf);
  1821. if ($sharePoint) {
  1822. if ('//' == substr($mainFolder, 0, 2)) {
  1823. $sharePoint = FoldersConfig::getNfsOsPath() . "{$mainFolder}";
  1824. } else {
  1825. $sharePoint = FoldersConfig::getNfsOsPath() . "{$sharePoint}/{$mainFolder}";
  1826. }
  1827. }
  1828. $localPath = $uploader->getLocalPath();
  1829. $folderWeb = $uploader->getFolderWeb();
  1830. $jsonFiles = $this->convertFileListToJson($files, $folderWeb, $localPath, $mainFolder);
  1831. 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>'; }
  1832. $folderSkanyConf = FoldersConfig::getAll('SCANS_COLUMN');
  1833. $skanyLocalPath = V::get('mount_point', null, $folderSkanyConf);
  1834. $skanySharePoint = V::get('share_point', null, $folderSkanyConf);
  1835. $skanyFolderWeb = V::get('www_share_point', null, $folderSkanyConf);
  1836. $skanyFiles = $uploader->getFilesFromSkany($folderSkanyConf, false);
  1837. sort($skanyFiles);
  1838. $fileTypes = FoldersConfig::getAll('m_dist_files_types');
  1839. $rowFunctionsOut = $this->_showRowFunctions($record['ID'], array('files', 'cp'), true);
  1840. $fileIndexField = V::get('DEST_FILE_INDEX_FIELD', 'ID', $folderConf);
  1841. $fileIndex = V::get($fileIndexField, $record['ID'], $record);
  1842. $namespace = $acl->getNamespace();
  1843. echo UI::h('div', [ 'class' => "container" ], [
  1844. UI::h('h4', [ 'style' => "margin:20px 0 3px 0;" ], [
  1845. "Pliki w katalogu ",
  1846. ($sharePoint)
  1847. ? UI::h('a', [ 'href' => $sharePoint ], [
  1848. UI::h('span', [ 'class' => "glyphicon glyphicon-folder-open" ]),
  1849. UI::h('code', [ 'style' => "margin-left:6px" ], $mainFolder),
  1850. ])
  1851. : UI::h('code', [], $mainFolder),
  1852. UI::h('span', [ 'class' => "pull-right valign-btns-bottom" ], [
  1853. UI::h('span', [ 'id' => "FILES_LIST_ACTIONS_{$this->_htmlID}" ]),
  1854. " {$rowFunctionsOut}",
  1855. ]),
  1856. ]),
  1857. UI::h('div', [ 'style' => "clear:both; max-height:180px; overflow:auto; border-bottom:1px solid #ddd;" ], [
  1858. UI::h('table', [ 'class' => "table table-bordered table-hover" ], [
  1859. UI::h('colgroup', [], [
  1860. UI::h('col', [ 'style' => "" ]),
  1861. UI::h('col', [ 'style' => "width:30px" ]),
  1862. ($sharePoint)
  1863. ? UI::h('col', [ 'style' => "width:30px" ])
  1864. : '',
  1865. UI::h('col', [ 'style' => "width:80px" ]),
  1866. UI::h('col', [ 'style' => "width:140px" ]),
  1867. ]),
  1868. UI::h('tbody', [ 'id' => "FILES_LIST_{$this->_htmlID}" ], [
  1869. (empty($mainFolder) || empty($files))
  1870. ? UI::h('tr', [], [
  1871. UI::h('td', [ 'colspan' => "5" ], [
  1872. (empty($mainFolder))
  1873. ? UI::h('div', [ 'class' => "alert alert-warning" ], [
  1874. UI::h('h4', [], "Brak folderu!"),
  1875. "Folder dla tego rekordu nie został utworzony."
  1876. ])
  1877. : UI::h('div', [ 'class' => "alert alert-info" ], [
  1878. UI::h('h4', [], "Brak plików!"),
  1879. ])
  1880. ]),
  1881. ])
  1882. : '',
  1883. ]),
  1884. ]),
  1885. ]),
  1886. UI::h('br'),
  1887. UI::h('br'),
  1888. (!$this->_acl->canWriteRecord($record))
  1889. ? UI::h('div', [ 'class' => "alert alert-warning" ], [
  1890. "Brak uprawnień do dodawania plików",
  1891. ])
  1892. : UI::h('div', [ 'id' => "FILES_CONN_TBLS_{$this->_htmlID}" ]),
  1893. (!$this->_acl->canWriteRecord($record))
  1894. ? ''
  1895. : UI::h('form', [ 'enctype' => "multipart/form-data", 'method' => "POST", 'action' => "", 'id' => "FILES_FRM_{$this->_htmlID}", 'class' => "form-inline" ], [
  1896. UI::h('input', [ 'type' => "hidden", 'name' => "M_DIST_UPLOAD_SOURCE", 'value' => "local" ]),
  1897. UI::h('ul', [ 'id' => "FILES_TAB_{$this->_htmlID}", 'class' => "nav nav-tabs", 'style' => "margin:0;"], [
  1898. UI::h('li', [ 'class' => "active" ], [ UI::h('a', [ 'href' => "#local", 'data-toggle' => "local" ], "Wybierz plik lokalny"), ]),
  1899. UI::h('li', [], [ UI::h('a', [ 'href' => "#scan", 'data-toggle' => "scan" ], "Wybierz plik ze skanów" ), ]),
  1900. UI::h('li', [], [ UI::h('a', [ 'href' => "#multiple", 'data-toggle' => "multiple" ], "Wgraj wiele plików" ), ]),
  1901. ]),
  1902. UI::h('div', [ 'id' => "myTabContent", 'class' => "tab-content" ], [
  1903. UI::h('div', [ 'class' => "tab-pane fade in active", 'id' => "local", 'style' => "text-align: center;" ], [
  1904. UI::h('input', [ 'name' => "M_DIST_FILES_NAME", 'type' => "file", 'size' => "60", 'class' => "field-upload btn",
  1905. 'style' => "width:86%;margin:10px auto;padding:10px 4%;background:#eee;text-align:center",
  1906. 'ondragover' => "this.style.backgroundColor='#D9EDF7'",
  1907. 'ondragleave' => "this.style.backgroundColor='#eee'",
  1908. 'ondragend' => "this.style.backgroundColor='#eee'",
  1909. ]),
  1910. ]),
  1911. UI::h('div', [ 'class' => "tab-pane fade", 'id' => "multiple" ], [
  1912. UI::h('div', [
  1913. 'id' => "FILES_MULTIPLE_UPLOAD_{$this->_htmlID}",
  1914. 'style' => "width:86%; margin:10px auto; padding:40px 100px; background-color:#eee; border-radius:4px; text-align:center",
  1915. 'ondrop' => "p5TAFiles_onDropMultiple(event, this, '{$id}', '{$namespace}')",
  1916. 'ondragover' => "p5TAFiles_onDragOverMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#D9EDF7'",
  1917. 'ondragleave' => "p5TAFiles_onDragLeaveMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#eee'",
  1918. 'ondragend' => "p5TAFiles_onDragEndMultiple(event, this)", // "event.preventDefault(); this.style.backgroundColor='#eee'",
  1919. ], [
  1920. "Upuść pliki tutaj",
  1921. ]),
  1922. ]),
  1923. UI::h('div', [ 'class' => "tab-pane fade", 'id' => "scan" ], [
  1924. (empty($skanyFiles))
  1925. ? UI::h('div', [ 'class' => "alert alert-info" ], [
  1926. UI::h('h4', [], "Brak plików"),
  1927. (!empty($skanyFolderWeb))
  1928. ? "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>"
  1929. : '',
  1930. ])
  1931. : UI::h('div', [ 'style' => "max-height:150px; overflow:auto; border-bottom:1px solid #ddd;" ], [
  1932. UI::h('table', [ 'class' => "table table-bordered table-hover" ], [
  1933. UI::h('colgroup', [], [
  1934. UI::h('col', [ 'style' => "width:30px;" ]),
  1935. UI::h('col', [ 'style' => "" ]),
  1936. UI::h('col', [ 'style' => "width:30px;" ]),
  1937. UI::h('col', [ 'style' => "width:80px;" ]),
  1938. UI::h('col', [ 'style' => "width:140px;" ]),
  1939. ]),
  1940. UI::h('tbody', [], array_map(function ($vFilePath) use ($skanyLocalPath, $skanyFolderWeb) {
  1941. $vFileName = explode('/', $vFilePath);
  1942. $vFileName = end($vFileName);
  1943. $vFileSize = filesize($vFilePath);
  1944. $vFileSizeOut = V::humanFileSize($vFileSize);
  1945. return UI::h('tr', [], [
  1946. UI::h('td', [], [ UI::h('input', [ 'style' => "margin:0", 'type' => "radio", 'name' => "SCANS_COLUMN_ADD", 'value' => $vFileName]) ]),
  1947. UI::h('td', [], [ UI::h('div', [ 'style' => "overflow:hidden; white-space:nowrap", 'title' => $vFileName ], $vFileName) ]),
  1948. UI::h('td', [ 'style' => "white-space:nowrap; text-align:center" ], [
  1949. UI::h('a', [ 'href' => str_replace($skanyLocalPath, $skanyFolderWeb, $vFilePath), 'target' => "_blank", 'class' => "glyphicon glyphicon-download-alt" ])
  1950. ]),
  1951. UI::h('td', [ 'style' => "white-space:nowrap; text-align:right" ], $vFileSizeOut),
  1952. UI::h('td', [ 'style' => "white-space:nowrap" ], date("Y-m-d H:i:s", filectime($vFilePath))),
  1953. ]);
  1954. }, $skanyFiles)),
  1955. ])
  1956. ]),
  1957. ])
  1958. ]),
  1959. UI::h('br'),
  1960. UI::h('h4', [], [
  1961. "Ustal nazwę pliku zgodną z obiegiem dokumentów",
  1962. //TODO: link do procesu o obiegu dokumentów <i class="glyphicon glyphicon-question-sign" style="cursor:help" title="działa w nowszych przeglądarkach jak Firefox, Chrome"></i>
  1963. ]),
  1964. UI::h('table', [ 'style' => "width:100%", 'class' => "table table-bordered" ], [
  1965. UI::h('tr', [], [
  1966. UI::h('th', [], "Nr"),
  1967. UI::h('th', [], "Typ"),
  1968. UI::h('th', [ 'style' => "width:40%" ], [
  1969. "Opis ",
  1970. UI::h('i', [ 'class' => "glyphicon glyphicon-question-sign", 'title' => "kogo dotyczy / czego / sprawa / nazwa_firmy itp" ]),
  1971. ]),
  1972. UI::h('th', [ 'style' => "width:16%" ], "Data wersji"),
  1973. UI::h('th', [ 'style' => "width:12%" ], "Numer wersji"),
  1974. ]),
  1975. UI::h('tr', [], [
  1976. UI::h('td', [], $fileIndex),
  1977. UI::h('td', [], [
  1978. UI::h('select', [ 'class' => "form-control", 'name' => "M_DIST_FILES_TYPE" ], array_map(function ($vLabel, $kType) {
  1979. return UI::h('option', array_merge([ 'value' => $kType],
  1980. ($kType == 'TODO')
  1981. ? [ 'selected' => "selected"]
  1982. : []
  1983. ), $vLabel);
  1984. }, $fileTypes, array_keys($fileTypes)) ),
  1985. UI::h('br'),
  1986. UI::h('label', [ 'class' => "checkbox" ], [
  1987. UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_TYPE_AUTO" ]),
  1988. " Wykrycie automatyczne typu z wysylanego pliku",
  1989. ]),
  1990. UI::h('label', [ 'class' => "checkbox" ], [
  1991. UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_TEMP" ]),
  1992. " Plik tymczasowy / roboczy / nieoficjalny (_TEMP)",
  1993. ]),
  1994. ]),
  1995. UI::h('td', [], [
  1996. UI::h('input', [ 'class' => "form-control", 'style' => "width:100%", 'type' => "text", 'name' => "M_DIST_FILES_DESCRIPTION", 'value' => "", 'maxlength' => "50" ]),
  1997. "<br><label>jeśli nie zostanie podany to zostanie automatycznie wygenerowany na podstawie nazwy pliku wysyłanego</label>",
  1998. ]),
  1999. UI::h('td', [], [
  2000. UI::h('div', [ 'class' => "input-group" ], [
  2001. UI::h('input', [ 'name' => "M_DIST_FILES_DATE", 'type' => "text", 'value' => date('Y-m-d'), 'class' => "se_type-date form-control", 'data-format' => "yyyy-MM-dd", 'maxlength' => "10" ]),
  2002. UI::h('span', [ 'class' => "input-group-addon" ], [
  2003. UI::h('span', [ 'class' => "glyphicon glyphicon-calendar" ]),
  2004. ]),
  2005. ]),
  2006. // UI::h('input', [ 'class' => "form-control", 'type' => "date", 'name' => "M_DIST_FILES_DATE", 'value' => date('Y-m-d'), 'maxlength' => "10" ]),
  2007. "<br><label>jeśli nie zostanie podana to zostanie ustawiona na dzisiaj (" . date('Y-m-d') . ")</label>",
  2008. ]),
  2009. UI::h('td', [], [
  2010. UI::h('input', [ 'class' => "form-control", 'style' => "width:100%", 'type' => "number", 'name' => "M_DIST_FILES_VERSION" ]),
  2011. UI::h('br'),
  2012. UI::h('label', [ 'class' => "checkbox" ], [
  2013. UI::h('input', [ 'type' => "checkbox", 'name' => "M_DIST_FILES_VERSION_AUTO" ]),
  2014. " Automatycznie dodaj wersje",
  2015. ]),
  2016. ]),
  2017. ]),
  2018. UI::h('tr', [], [
  2019. UI::h('td', [ 'colspan' => "5" ], [
  2020. UI::h('div', [ 'id' => "FRM_UPLOAD_RESULTS_{$this->_htmlID}" ]),
  2021. UI::h('p', [], [
  2022. UI::h('input', [ 'type' => "submit", 'value' => "Wyślij", 'class' => "btn btn-primary" ], "wybrany plik do folderu:"),
  2023. ]),
  2024. UI::h('p', [], [
  2025. UI::h('code', [], [
  2026. UI::h('b', [], $uploader->getDestPathShare(true)),
  2027. ]),
  2028. UI::h('br'),
  2029. UI::h('i', [ 'style' => "color:#777" ], "(Jeśli folder nie istnieje to zostanie utworzony automatycznie)"),
  2030. ]),
  2031. ]),
  2032. ]),
  2033. ]),
  2034. ]),
  2035. ]);
  2036. $className = __CLASS__;
  2037. $namespace = $acl->getNamespace();
  2038. UI::inlineJS(__FILE__ . '.files.js', [
  2039. 'UNIQ_HASH' => $this->_htmlID,
  2040. 'FUNCTION_FILE_LIST_UPDATE_AJAX' => "fileListUpdateAjax{$this->_htmlID}", // fileListUpdateAjax
  2041. 'FUNCTION_FILE_LIST_UPDATE' => "fileListUpdate{$this->_htmlID}", // fileListUpdate
  2042. 'FUNCTION_CONN_TBL_LIST_UPDATE_AJAX' => "connTblListUpdateAjax{$this->_htmlID}", // connTblListUpdateAjax
  2043. 'FUNCTION_CONN_TBL_LIST_UPDATE' => "connTblListUpdate{$this->_htmlID}", // connTblListUpdate
  2044. 'FUNCTION_FILE_LIST_ACTIONS' => "fileListActions{$this->_htmlID}", // fileListActions
  2045. 'CONN_TABLES' => $this->getConnectedTables(),
  2046. 'NODE_ID_FILES_FRM' => "FILES_FRM_{$this->_htmlID}",
  2047. 'NODE_ID_FRM_UPLOAD_RESULTS' => "FRM_UPLOAD_RESULTS_{$this->_htmlID}",
  2048. 'NODE_ID_FILES_TAB' => "FILES_TAB_{$this->_htmlID}",
  2049. 'NODE_ID_FILES_LIST' => "FILES_LIST_{$this->_htmlID}",
  2050. 'NODE_ID_FILES_CONN_TBLS' => "FILES_CONN_TBLS_{$this->_htmlID}",
  2051. 'NODE_ID_FILES_LIST_ACTIONS' => "FILES_LIST_ACTIONS_{$this->_htmlID}",
  2052. 'NODE_ID_FILES_MULTIPLE_UPLOAD' => "FILES_MULTIPLE_UPLOAD_{$this->_htmlID}",
  2053. 'URL_FILE_LIST_UPDATE_AJAX' => "index-ajax.php?_zasobID={$this->_zasobID};&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_LIST&ID={$record['ID']}",
  2054. 'URL_FILE_REMOVE_AJAX' => "index.php?_route=ViewTableAjax&namespace={$namespace}&_task=removeFileAjax&ID={$record['ID']}",
  2055. 'URL_CONNECTED_TABLE_LIST' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_CONN_TBL_LIST&ID={$record['ID']}",
  2056. 'URL_FILE_PERMS_REFRESH' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=filePermsRefresh&ID={$record['ID']}",
  2057. 'URL_FILE_UPLOAD' => "index-ajax.php?_zasobID={$this->_zasobID}&_cls={$className}&_hash={$this->_htmlID}&_task=FILES_UPLOAD&ID={$record['ID']}",
  2058. 'CAN_WRITE_RECORD' => (int)$this->_acl->canWriteRecord($record),
  2059. 'SHARE_POINT' => $sharePoint,
  2060. 'JSON_FILES' => $jsonFiles,
  2061. ]);
  2062. exit;
  2063. }
  2064. private function sendTypeSpecial($fldID, $args) {
  2065. $DBG = ('1' == V::get('DBG', '', $_REQUEST));
  2066. header("Content-type: application/json");
  2067. $fldName = '';
  2068. $fld = $this->_acl->getField($fldID);
  2069. DBG::log($fld, 'array', "\$fld({$fldID})");
  2070. if (!$fld) {
  2071. // 404
  2072. } else {
  2073. $fldName = $fld['name'];
  2074. }
  2075. $jsonData = array();
  2076. $typeSpecial = Typespecial::getInstance($fldID, $fldName);
  2077. if ($typeSpecial) {
  2078. $query = V::get('q', '', $_REQUEST);
  2079. DBG::log("\$query({$query})");
  2080. $rawRows = null;
  2081. $rows = $typeSpecial->getValuesWithExports($query);
  2082. DBG::log($rows, 'array', "\$rows({$query})");
  2083. foreach ($rows as $kID => $vItem) {
  2084. $itemJson = new stdClass();
  2085. $itemJson->id = $vItem->id;
  2086. $itemJson->name = $vItem->param_out;
  2087. if (!empty($vItem->exports)) {
  2088. $itemJson->exports = $vItem->exports;
  2089. }
  2090. if (!empty($vItem->{'$order'})) {
  2091. $itemJson->{'$order'} = $vItem->{'$order'};
  2092. }
  2093. $jsonData[] = $itemJson;
  2094. }
  2095. }
  2096. /*
  2097. MENU_INIT:VIEWTABLE_AJAX
  2098. ZASOB_ID:1188
  2099. _task:TYPESPECIAL
  2100. fldID:3866
  2101. Form Dataview sourceview URL encoded
  2102. q:te
  2103. */
  2104. echo json_encode($jsonData);
  2105. exit;
  2106. }
  2107. public function ajaxData($args) {// executed from url: "{$this->syncUrl"&_hash={$this->_htmlID}&_task=loadDataAjax"
  2108. $acl = $this->_acl;
  2109. $pageSize = V::get('pageSize', $this->_pageSize, $args, 'int');
  2110. $page = V::get('page', 0, $args, 'int');
  2111. $page = ($page > 0) ? $page - 1 : $page;
  2112. $currSortCol = V::get('currSortCol', '', $args);
  2113. $currSortFlip = V::get('currSortFlip', '', $args);
  2114. $params = array();
  2115. $params['limit'] = $pageSize;
  2116. $params['limitstart'] = $page * $params['limit'];
  2117. $params['order_by'] = ($currSortCol)? $currSortCol : '';
  2118. $params['order_dir'] = $currSortFlip;
  2119. foreach ($args as $k => $v) {
  2120. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  2121. $params[$k] = $v;
  2122. }
  2123. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  2124. $params[$k] = $v;
  2125. }
  2126. }
  2127. if ($this->_backRefFilter) {
  2128. $params['__backRef'] = $this->_backRefFilter;
  2129. DBG::log($params, 'array', '$params __backRef');
  2130. }
  2131. if ($this->_childRefFilter) {
  2132. $params['__childRef'] = $this->_childRefFilter;
  2133. DBG::log($params, 'array', '$params __childRef');
  2134. }
  2135. $filters = new stdClass();
  2136. $filters->currSortCol = $currSortCol;
  2137. $filters->currSortFlip = $currSortFlip;
  2138. foreach ($args as $k => $v) {
  2139. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  2140. $filters->{$k} = $v;
  2141. }
  2142. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  2143. $filters->{$k} = $v;
  2144. }
  2145. }
  2146. $this->setFilters($filters);
  2147. $vCols = $acl->getVirtualFieldListByIdZasob();
  2148. DBG::log($vCols, 'array', "\$vCols");
  2149. $visibleCols = $acl->getVisibleFieldListByIdZasob();
  2150. DBG::log($visibleCols, 'array', "\$visibleCols");
  2151. $jsonData = new stdClass();
  2152. $jsonData->page = $page + 1;
  2153. $jsonData->pageSize = $pageSize;
  2154. $jsonData->filters = $filters;
  2155. $jsonData->cols = new stdClass();
  2156. $jsonData->primaryKey = $acl->getPrimaryKeyField();
  2157. $ind = 0;
  2158. foreach ($visibleCols as $fieldID => $col) {
  2159. $ind++;
  2160. $columnConfig = (object)array('index'=>$ind);
  2161. if (in_array($col, array('A_STATUS','A_STATUS_CURRENT','A_SERVICES_STATUS_CURRENT'))) {
  2162. $columnConfig->format = '<div class="cell-A_STATUS-{0}">{0}</div>';
  2163. }
  2164. else if (in_array($col, array('Status'))) {
  2165. // Ahmes problems Status colors
  2166. $columnConfig->format = '<div class="cell-Status-{0}">{0}</div>';
  2167. }
  2168. else if ($acl->isGeomField($col)) {
  2169. $columnConfig->type = 'geom';
  2170. }
  2171. if ('' !== ($label = $acl->getFieldLabel($col))) {
  2172. $columnConfig->friendly = $label;
  2173. }
  2174. $colType = $acl->getFieldType($col);
  2175. if ($colType) {// @see MarkTableAjaxFilterColType
  2176. if ($colType['type'] == 'date') {
  2177. // $columnConfig->type = 'date';// TODO: require datetimepicker
  2178. }
  2179. if (!empty($colType['simpleType'])) $columnConfig->type = $colType['simpleType'];
  2180. } else {// typespecial - no type
  2181. $columnConfig->type = 'special';
  2182. }
  2183. $columnConfig->xsdType = $acl->getXsdFieldType($col);
  2184. if ($columnConfig->xsdType) {
  2185. list($prefix, $typeName, $refTypeName) = explode(":", $columnConfig->xsdType);
  2186. DBG::log([$prefix, $typeName, $refTypeName], 'array', "col '{$col}' xsdType");
  2187. switch ($prefix) {
  2188. case 'ref':
  2189. case 'alias_ref':
  2190. if (!$refTypeName) throw new HttpException("Schema Error for field({$col}) xsdType({$columnConfig->xsdType})", 500);
  2191. $columnConfig->type = 'ref';
  2192. $columnConfig->xsdRefUri = Api_WfsNs::getNsUri($typeName);
  2193. $columnConfig->xsdRefType = $refTypeName;
  2194. $columnConfig->xsdRefNsPrefix = $typeName;
  2195. break;
  2196. case 'xsd':
  2197. switch ($typeName) {
  2198. case 'string': $columnConfig->type = 'string'; break;
  2199. case 'NMTOKEN': $columnConfig->type = 'string'; break; // xsd:NMTOKEN - non empty string without space - pattern: \c+
  2200. case 'NCName': $columnConfig->type = 'string'; break; // xsd:NCName - non empty without ':' and not started with '-' - pattern: [\i-[:]][\c-[:]]*
  2201. case 'integer': $columnConfig->type = 'number'; break;
  2202. case 'int': $columnConfig->type = 'number'; break;
  2203. case 'long': $columnConfig->type = 'number'; break;
  2204. }
  2205. break;
  2206. case 'p5':
  2207. switch ($typeName) {
  2208. case 'enum': $columnConfig->type = 'string'; break;
  2209. case 'alias': {
  2210. if ($format = $acl->getXsdFieldParam($col, 'format')) $columnConfig->format = $format;
  2211. if ($aliasMap = $acl->getXsdFieldParam($col, 'aliasMap')) $columnConfig->aliasMap = $aliasMap;
  2212. } break;
  2213. case 'string': {
  2214. $columnConfig->type = 'p5:string';
  2215. $columnConfig->formatByValue = $acl->getXsdFieldParam($col, 'formatByValue');
  2216. if ($aliasMap = $acl->getXsdFieldParam($col, 'aliasMap')) $columnConfig->aliasMap = $aliasMap;
  2217. } break;
  2218. }
  2219. break;
  2220. case 'p5Type':
  2221. switch ($typeName) {
  2222. case 'enum': $columnConfig->type = 'string'; break;
  2223. case 'alias': {
  2224. $format = $acl->getXsdFieldParam($col, 'format');
  2225. if ($format) $columnConfig->format = $format;
  2226. } break;
  2227. case 'integer': $columnConfig->type = 'number'; break;
  2228. case 'string': {
  2229. $columnConfig->type = 'p5:string';
  2230. $columnConfig->formatByValue = $acl->getXsdFieldParam($col, 'formatByValue');
  2231. if ($aliasMap = $acl->getXsdFieldParam($col, 'aliasMap')) $columnConfig->aliasMap = $aliasMap;
  2232. } break;
  2233. }
  2234. break;
  2235. }
  2236. }
  2237. $typeSpecial = Typespecial::getInstance($fieldID, $col);
  2238. if ($typeSpecial) {
  2239. DBG::log($typeSpecial, 'array', "\$typeSpecial id({$fieldID}) col({$col})");
  2240. $columnConfig->_tsRetId = $typeSpecial->getReturnId();
  2241. if ($columnConfig->_tsRetId == 0) {
  2242. $tsParamOut = V::get('param_out', null, $typeSpecial);
  2243. if ($tsParamOut) {
  2244. $tsFormat = V::get('format', null, $tsParamOut);
  2245. $tsValues = V::get('values', null, $tsParamOut);
  2246. $tsAliases = V::get('alias', null, $tsParamOut);
  2247. if (false !== strpos($tsFormat, '<a') && !empty($tsValues) && !empty($tsAliases)) {
  2248. $tsAliasMap = array();
  2249. /* [values] => Array([ID] => 1467), [alias] => Array([1467] => ID) */
  2250. $bugTsColsNotVisible = array();
  2251. foreach ($tsValues as $kVarName => $vIdZasob) {
  2252. if (array_key_exists($vIdZasob, $tsAliases)) {
  2253. $tsAliasMap[$kVarName] = $tsAliases[$vIdZasob];
  2254. } else {
  2255. $bugTsColsNotVisible[] = "noAliasFor {$vIdZasob}";
  2256. }
  2257. if (!array_key_exists($vIdZasob, $visibleCols)) {
  2258. $bugTsColsNotVisible[] = $vIdZasob;
  2259. }
  2260. }
  2261. if (empty($bugTsColsNotVisible)) {
  2262. $tsSimpleLink = new stdClass();
  2263. $tsSimpleLink->format = $tsFormat;
  2264. $tsSimpleLink->aliasMap = $tsAliasMap;
  2265. $columnConfig->_tsSimpleLink = $tsSimpleLink;
  2266. $columnConfig->type = 'simpleLink';
  2267. } else {
  2268. $columnConfig->_tsSimpleLinkBug = $bugTsColsNotVisible;
  2269. }
  2270. }
  2271. }
  2272. }
  2273. }
  2274. if ($columnConfig->xsdType) {// fix fields type p5:typeSpecialSimpleLink (previously defined by Typespecial)
  2275. switch ($columnConfig->xsdType) {
  2276. case 'p5:typeSpecialSimpleLink': {
  2277. $columnConfig->type = 'simpleLink';
  2278. $columnConfig->_tsRetId = 0;
  2279. $columnConfig->_tsSimpleLink = new stdClass();
  2280. $columnConfig->_tsSimpleLink->format = $acl->getXsdFieldParam($col, 'format');
  2281. $columnConfig->_tsSimpleLink->aliasMap = $acl->getXsdFieldParam($col, 'aliasMap');
  2282. } break;
  2283. }
  2284. }
  2285. // @see ajaxHiddenColsSave
  2286. if (UserProfile::isHiddenColumn($acl->getID(), $fieldID)) {
  2287. $columnConfig->hidden = true;
  2288. }
  2289. $columnConfig->description = $acl->getFieldOpis($col);
  2290. $jsonData->cols->{$col} = $columnConfig;
  2291. }
  2292. DBG::log($jsonData->cols, 'array', "\$jsonData->cols");
  2293. $jsonData->rows = array();
  2294. if ($acl instanceof AntAclBase) {
  2295. $params['f_is_instance'] = $acl->getNamespace();
  2296. }
  2297. $queryFeatures = $acl->buildQuery($params);
  2298. $jsonData->total = $queryFeatures->getTotal();
  2299. $listItems = $queryFeatures->getItems();
  2300. $primaryKeyField = $acl->getPrimaryKeyField();
  2301. $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
  2302. // TODO: add virtual data by Typespecial
  2303. if (!empty($vCols) && !empty($items)) {
  2304. foreach ($vCols as $vColID => $vCol) {
  2305. $colType = $acl->getFieldTypeById($vColID);
  2306. if ($colType) continue;// pomin Typespecial dla realnych komorek w bazie danych
  2307. $typeSpecial = Typespecial::getInstance($vColID, $vCol);
  2308. if ($typeSpecial) {
  2309. $columnConfig = V::get($vCol, null, $jsonData->cols);
  2310. if ($columnConfig && !empty($columnConfig->_tsSimpleLink)) {
  2311. // pomin simple link values - mved to js render
  2312. } else {
  2313. DBG::log($typeSpecial, 'array', "Typespecial({$vColID})");
  2314. $ids = array_keys($items);
  2315. $specialValues = $typeSpecial->getValuesByIds($this->_zasobID, $ids);
  2316. DBG::log($specialValues, 'array', "Typespecial({$vColID}) \$specialValues");
  2317. if (!empty($specialValues)) foreach ($specialValues as $kItemID => $vValues) {
  2318. $tsValue = implode('<br>', $vValues);
  2319. DBG::log($items[$kItemID], 'array', "Typespecial({$vColID}) Item[{$kItemID}].{$vCol}");
  2320. if (!empty($items[$kItemID][$vCol]) && !empty($tsValue)) {
  2321. $items[$kItemID][$vCol] .= ": {$tsValue}";
  2322. } else {
  2323. $items[$kItemID][$vCol] = $tsValue;
  2324. }
  2325. }
  2326. }
  2327. }
  2328. }
  2329. }
  2330. {
  2331. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__ = [];}
  2332. $p5Alias = [];
  2333. foreach ((array)$jsonData->cols as $fieldName => $conf) {
  2334. if ('p5:alias' == V::get('xsdType', '', $conf)) {
  2335. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__[$fieldName] = $conf;}
  2336. $aliasType = $acl->getXsdFieldParam($fieldName, 'type');// 'type' => 'sql_table_alias',
  2337. if ('sql_table_alias' == $aliasType) {
  2338. $p5Alias[$fieldName] = (array)$conf;
  2339. $p5Alias[$fieldName]['type'] = 'sql_table_alias';
  2340. $p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');// 'local_join_key' => 'ID',
  2341. $p5Alias[$fieldName]['remote_table_name'] = $acl->getXsdFieldParam($fieldName, 'remote_table_name');// 'remote_table_name' => 'CRM_LISTA_ZASOBOW_ORDERS_summary_view',
  2342. $p5Alias[$fieldName]['remote_join_key'] = $acl->getXsdFieldParam($fieldName, 'remote_join_key');// 'remote_join_key' => 'ID',
  2343. $p5Alias[$fieldName]['remote_column_value'] = $acl->getXsdFieldParam($fieldName, 'remote_column_value');// 'remote_column_value' => 'SUM_POS',
  2344. } else if ('sql_query_alias' == $aliasType) {
  2345. $p5Alias[$fieldName] = (array)$conf;
  2346. $p5Alias[$fieldName]['type'] = 'sql_query_alias';
  2347. $p5Alias[$fieldName]['local_join_key'] = $acl->getXsdFieldParam($fieldName, 'local_join_key');
  2348. $p5Alias[$fieldName]['join_query_format'] = $acl->getXsdFieldParam($fieldName, 'join_query_format');
  2349. }
  2350. }
  2351. }
  2352. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$p5Alias'] = $p5Alias;}
  2353. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'] = [];}
  2354. if ($p5Alias) {
  2355. $sqlLocalTableName = $acl->getRootTableName();
  2356. $primaryKeyField = $acl->getPrimaryKeyField();
  2357. foreach ($p5Alias as $fieldName => $conf) {
  2358. $aliasValuesRaw = [];
  2359. if ('sql_table_alias' == $conf['type']) {
  2360. $localKeys = [];
  2361. $localKeyName = V::get('local_join_key', '', $conf);
  2362. if ($localKeyName) {
  2363. if (!array_key_exists($localKeyName, $localKeys)) {
  2364. $localKeys[$localKeyName] = [];
  2365. foreach ($items as $item) {
  2366. $keyLocal = V::get($localKeyName, 0, $item);
  2367. if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
  2368. }
  2369. }
  2370. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$localKeys'] = $localKeys;}
  2371. if (!empty($localKeys[$localKeyName])) {
  2372. $sqlRemoteTable = V::get('remote_table_name', '', $conf);
  2373. $sqlRemoteValueFieldName = V::get('remote_column_value', '', $conf);
  2374. $sqlRemoteKeyName = V::get('remote_join_key', '', $conf);
  2375. $sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
  2376. try {
  2377. $aliasValuesRaw = DB::getPDO()->fetchAllByKey("
  2378. select r.{$sqlRemoteKeyName} as {$sqlLocalKeyName}, r.{$sqlRemoteValueFieldName} as remote_value
  2379. from {$sqlRemoteTable} r
  2380. where r.{$sqlRemoteKeyName} in(" . implode(",", $localKeys[$localKeyName]) . ")
  2381. ", $sqlLocalKeyName);
  2382. } catch (Exception $e) {
  2383. // TODO: error msg for GUI
  2384. DBG::log($e);
  2385. }
  2386. if(V::get('DBG', '', $_GET)){$jsonData->__DBG__['$aliasValuesRaw'][$fieldName] = $aliasValuesRaw;}
  2387. }
  2388. }
  2389. } else if ('sql_query_alias' == $conf['type']) {
  2390. $localKeys = [];
  2391. $localKeyName = V::get('local_join_key', '', $conf);
  2392. $sqlFormat = V::get('join_query_format', '', $conf);
  2393. if ($localKeyName && $sqlFormat) {
  2394. if (!array_key_exists($localKeyName, $localKeys)) {
  2395. $localKeys[$localKeyName] = [];
  2396. foreach ($items as $item) {
  2397. $keyLocal = V::get($localKeyName, 0, $item);
  2398. if ($keyLocal) $localKeys[$localKeyName][] = DB::getPDO()->quote($keyLocal, PDO::PARAM_STR);
  2399. }
  2400. }
  2401. }
  2402. if (!empty($localKeys[$localKeyName])) {
  2403. $sql = str_replace('{sql_in_local_join_key}', implode(",", $localKeys[$localKeyName]), $sqlFormat);
  2404. $sqlLocalKeyName = $acl->getSqlFieldName($localKeyName);
  2405. try {
  2406. $aliasValuesRaw = DB::getPDO()->fetchAllByKey($sql, $sqlLocalKeyName);
  2407. } catch (Exception $e) {
  2408. // TODO: error msg for GUI
  2409. DBG::log($e);
  2410. }
  2411. }
  2412. }
  2413. DBG::log($aliasValuesRaw, 'array', '$aliasValuesRaw');
  2414. if (!empty($aliasValuesRaw)) {
  2415. DBG::log($aliasValuesRaw, 'array', "DBG_P5: \$aliasValuesRaw");
  2416. array_walk($items, function (&$item) use ($fieldName, $sqlLocalKeyName, $aliasValuesRaw) {
  2417. $sqlValue = V::get($sqlLocalKeyName, null, $item);
  2418. DBG::log($sqlValue, 'array', "DBG_P5: \$sqlValue");
  2419. DBG::log($aliasValuesRaw[$sqlValue]['remote_value'], 'array', "DBG_P5: \$aliasValuesRaw[{$sqlValue}]['remote_value']");
  2420. DBG::log($item, 'array', "DBG_P5: \$item");
  2421. if ($sqlValue !== null && array_key_exists($sqlValue, $aliasValuesRaw)) {
  2422. DBG::log($aliasValuesRaw[$sqlValue]['remote_value'], 'array', "DBG_P5: TODO_update_value");
  2423. $item[$fieldName] = $aliasValuesRaw[$sqlValue]['remote_value'];
  2424. DBG::log($item[$fieldName], 'array', "DBG_P5: TODO_updated_value");
  2425. }
  2426. });
  2427. }
  2428. }
  2429. }
  2430. }
  2431. foreach ($items as $item) {
  2432. // TODO: hide items without 'R'
  2433. foreach ($visibleCols as $fieldName) {
  2434. // TODO: ID default 'R'
  2435. if (!$acl->canReadObjectField($fieldName, $item)) $item[$fieldName] = '*****';
  2436. // null => empty string
  2437. if (!isset($item[$fieldName]) || (!$item[$fieldName] && $item[$fieldName] !== '0')) {
  2438. // DBG::log($item[$fieldName], 'array', "isEmptyString[{$fieldName}]");
  2439. $item[$fieldName] = '';
  2440. }
  2441. }
  2442. $jsonData->rows[] = $item;
  2443. }
  2444. $jsonData->type = 'success';
  2445. $jsonData->msg = 'pobrano nowe dane';
  2446. // { // TODO: BUG - race condition in requests
  2447. // session_write_close();
  2448. // if (!empty($params['f_L_APPOITMENT_USER']) && strlen($params['f_L_APPOITMENT_USER']) === 3) sleep(2); // TODO: DBG
  2449. // if (!empty($params['f_L_APPOITMENT_USER']) && strlen($params['f_L_APPOITMENT_USER']) === 3) $jsonData->__DBG__sleep = 2; // TODO: DBG
  2450. // }
  2451. return $jsonData;
  2452. }
  2453. private function fixEmptyValueFromUser($fieldID) {// TODO: moved to TableAcl->fixEmptyValueFromUser
  2454. $value = '';
  2455. $type = $this->_acl->getFieldTypeById($fieldID);
  2456. if ($type) {
  2457. if ($type['type'] == 'date') {
  2458. $value = $type['default'];
  2459. }
  2460. // fix bug when field is unique and is null allowed: change empty string to null
  2461. if ($type['null']) {
  2462. $value = 'NULL';
  2463. }
  2464. // fix bug when field is enum and is set to '0': for php '0' is empty
  2465. if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  2466. if (false !== strpos($type['type'], "''")) {
  2467. // enum('', '1','2')
  2468. $value = '';
  2469. } else if (false !== strpos($type['type'], "'0'")) {
  2470. // enum('0', '1','2')
  2471. $value = '0';
  2472. } else {
  2473. $value = $type['default'];
  2474. }
  2475. }
  2476. }
  2477. return $value;
  2478. }
  2479. /**
  2480. * set hidden cols in $_SESSION['USER_PROFILE'][$this->_zasobID];
  2481. * $_SESSION['USER_PROFILE'][$this->_zasobID][fld_id] => boolean
  2482. */
  2483. private function ajaxHiddenColsSave($args) {
  2484. $response = new stdClass();
  2485. if (empty($args)) {
  2486. $response->type = 'info';
  2487. return $response;
  2488. }
  2489. UserProfile::load();
  2490. // clean up old, wrong values
  2491. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  2492. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  2493. }
  2494. $colVis = UserProfile::getHiddenCols($this->_zasobID);
  2495. $fields = $this->_acl->getFieldListByIdZasob();
  2496. foreach ($fields as $idField => $fieldName) {
  2497. if (isset($args[$fieldName])) {
  2498. if ($args[$fieldName] == 'SHOW') {
  2499. $colVis[$idField] = 1;
  2500. } else if ($args[$fieldName] == 'HIDE') {
  2501. $colVis[$idField] = 0;
  2502. }
  2503. }
  2504. }
  2505. UserProfile::setHiddenCols($this->_zasobID, $colVis);
  2506. UserProfile::save();
  2507. $response->type = 'success';
  2508. return $response;
  2509. }
  2510. private function ajaxPageSizeSave($args) {
  2511. $response = new stdClass();
  2512. if (empty($args)) {
  2513. $response->type = 'info';
  2514. return $response;
  2515. }
  2516. $pageSize = V::get('pageSize', 0, $args, 'int');
  2517. UserProfile::load();
  2518. // clean up old, wrong values
  2519. if (array_key_exists("{$this->_tbl}_COLUMN", $_SESSION['USER_PROFILE'])) {
  2520. unset($_SESSION['USER_PROFILE']["{$this->_tbl}_COLUMN"]);
  2521. }
  2522. $tableAjaxSettings = UserProfile::getTableAjaxSettings();
  2523. $tableAjaxSettings['pageSize'] = $pageSize;
  2524. UserProfile::setTableAjaxSettings($tableAjaxSettings);
  2525. UserProfile::save();
  2526. $response->type = 'success';
  2527. return $response;
  2528. }
  2529. private function ajaxTheGeomSave($args) {
  2530. $primaryKeyField = $this->_acl->getPrimaryKeyField();
  2531. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  2532. $polygon = V::get('polygon', 0, $args);
  2533. $geomFieldName = 'the_geom';
  2534. if ($primaryKey <= 0) {
  2535. throw new HttpException("Wrong param ID", 404);
  2536. }
  2537. // 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)))
  2538. $record = $this->_acl->buildQuery([])->getItem($primaryKey);
  2539. if (!$this->_acl->canWriteRecord($record) && !$this->_acl->hasPermSuperWrite()) {
  2540. throw new HttpException("Brak dostępu do rekordu", 403);
  2541. }
  2542. if (!$this->_acl->canWriteObjectField($geomFieldName, $record)) {
  2543. throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  2544. }
  2545. $itemPatch = array();
  2546. $itemPatch[$geomFieldName] = "GeomFromText('{$polygon}')";
  2547. $itemPatch[$primaryKeyField] = $primaryKey;
  2548. $response = new stdClass();
  2549. try {
  2550. $affected = $this->_acl->updateItem($itemPatch);
  2551. if ($affected > 0) {
  2552. $response->type = 'success';
  2553. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  2554. } else if ($affected == 0) {
  2555. $response->type = 'info';
  2556. $response->msg = "Nie wprowadzono żadnych zmian";
  2557. }
  2558. $response->record = $this->_acl->buildQuery([])->getItem($primaryKey);
  2559. }
  2560. catch (Exception $e) {
  2561. $response->type = 'error';
  2562. $response->msg = $e->getMessage();
  2563. }
  2564. return $response;
  2565. }
  2566. public function sendAjaxResponseJson($method, $args) {
  2567. try {
  2568. $response = $this->{$method}($args);
  2569. }
  2570. catch (HttpException $e) {
  2571. $response = new stdClass();
  2572. $response->type = 'error';
  2573. $response->msg = $e->getMessage();
  2574. $response->errorCode = $e->getCode();
  2575. Http::sendHeaderByCode($e->getCode());
  2576. }
  2577. catch (Exception $e) {
  2578. $response = new stdClass();
  2579. $response->type = 'error';
  2580. $response->msg = $e->getMessage();
  2581. $response->errorCode = $e->getCode();
  2582. }
  2583. header('Content-type: application/json');
  2584. if (!$response) $response = new stdClass();
  2585. echo json_encode($response);
  2586. exit;
  2587. }
  2588. }