TableAjax.php 101 KB

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