ViewTableAjax.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. <?php
  2. Lib::loadClass('RouteBase');
  3. Lib::loadClass('ProcesHelper');
  4. Lib::loadClass('TableAjax');
  5. // Lib::loadClass('Request');
  6. Lib::loadClass('Response');
  7. Lib::loadClass('UI');
  8. Lib::loadClass('Api_WfsNs');
  9. Lib::loadClass('Core_AclHelper');
  10. Lib::loadClass('Route_UrlAction');
  11. Lib::loadClass('Router');
  12. Lib::loadClass('Typespecial');
  13. Lib::loadClass('UserProfile');
  14. class Route_ViewTableAjax extends RouteBase {
  15. public function getTableAjaxWidget($acl) {
  16. $syncUrl = $this->getLink('', [ 'namespace' => $acl->getNamespace() ]);
  17. $tbl = new TableAjax($acl);
  18. $tblLabel = $acl->getNamespace();
  19. if ('default_db' == $acl->getSourceName()) {
  20. $tblLabel = array();
  21. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  22. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  23. if (!empty($zasobObj->DESC_PL)) $tblLabel[] = $zasobObj->DESC_PL;
  24. if (!empty($zasobObj->OPIS)) $tblLabel[] = $zasobObj->OPIS;
  25. $tblLabel = implode(" - ", $tblLabel);
  26. }
  27. $tbl->setSyncUrl($syncUrl);
  28. $tbl->showProcesInitFiltr = $this->getLink("procesInitFiltrAjax", [ 'namespace' => $acl->getNamespace() ]);
  29. $tbl->useUserTableFilter = $this->getLink("getUserTableFilterAjax");
  30. $tbl->setLabel($tblLabel);
  31. $tbl->addRowFunction('edit');
  32. $tbl->addRowFunction('hist');
  33. $tbl->addRowFunction('files');
  34. $tbl->addRowFunction('cp');
  35. $tbl->addRowFunction('msgs');
  36. return $tbl;
  37. }
  38. public function defaultAction() {
  39. UI::gora();
  40. UI::menu();
  41. try {
  42. $namespace = V::get('namespace', '', $_GET, 'word');
  43. if (!$namespace) {
  44. $typeName = V::get('typeName', '', $_GET, 'word');
  45. if (!$typeName) throw new Exception("Wrong param typeName");
  46. $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  47. }
  48. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  49. $forceFilterInit = array();
  50. $filterInit = new stdClass();
  51. $filterInit->currSortCol = $acl->getPrimaryKeyField();
  52. $filterInit->currSortFlip = 'desc';
  53. foreach ($_GET as $k => $v) {
  54. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
  55. $filterInit->$k = $v;
  56. }
  57. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
  58. $filterInit->$k = $v;
  59. }
  60. else if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  61. $fldName = substr($k, 3);
  62. $forceFilterInit[$fldName] = $v;
  63. }
  64. }
  65. $tbl = $this->getTableAjaxWidget($acl);
  66. $tbl->setFilterInit($filterInit);
  67. if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
  68. echo $tbl->render();
  69. if (DBG::isActive() && V::get('DBG_ACL', '', $_GET)) {// test load perms
  70. Lib::loadClass('DebugExecutionTime');
  71. $dbgExecTime = new DebugExecutionTime();
  72. $dbgExecTime->activate();
  73. $dbgExecTime->log('start');
  74. UI::startContainer(['style'=>'border:1px solid red']);
  75. UI::tag('p', null, "TEST - load perms from db");
  76. $idTable = $acl->getID();
  77. UI::tag('p', null, "DBG idTable({$idTable})");
  78. if ($idTable > 0) {
  79. $dbgExecTime->log('before sql');
  80. $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
  81. $dbgExecTime->log('after sql', ['sql']);
  82. UI::table(['caption' => "from CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW", 'rows' => $aclTableRows]);
  83. $csvIdProces = array();
  84. foreach ($aclTableRows as $row) {
  85. if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
  86. }
  87. }
  88. $tableName = $acl->getName();
  89. $databaseName = DB::getPDO()->getDatabaseName();
  90. UI::table([
  91. 'caption' => "Cell to process",
  92. 'rows' => array_map(
  93. function ($row) use ($aclTableRows, $idTable) {
  94. $row['proces'] = array();
  95. $row['id_zasob'] = 0;
  96. $row['PERM_R'] = 0;
  97. $row['PERM_W'] = 0;
  98. $row['PERM_X'] = 0;
  99. $row['PERM_C'] = 0;
  100. $row['PERM_S'] = 0;
  101. $row['PERM_O'] = 0;
  102. $row['PERM_V'] = 0;
  103. $row['PERM_E'] = 0;
  104. foreach ($aclTableRows as $aclInfo) {
  105. if (strtolower($aclInfo['CELL_NAME']) == strtolower($row['COLUMN_NAME'])) {
  106. $row['proces'][] = $aclInfo['ID_PROCES'];
  107. $row['id_zasob'] = $aclInfo['ID_CELL'];
  108. $row['PERM_R'] += $aclInfo['PERM_R'];
  109. $row['PERM_W'] += $aclInfo['PERM_W'];
  110. $row['PERM_X'] += $aclInfo['PERM_X'];
  111. $row['PERM_C'] += $aclInfo['PERM_C'];
  112. $row['PERM_S'] += $aclInfo['PERM_S'];
  113. $row['PERM_O'] += $aclInfo['PERM_O'];
  114. $row['PERM_V'] += $aclInfo['PERM_V'];
  115. $row['PERM_E'] += $aclInfo['PERM_E'];
  116. }
  117. }
  118. $row['proces'] = (empty($row['proces']))
  119. ? "<i style=\"color:red\">Brak</i>"
  120. : implode(", ", $row['proces']);
  121. if (!$row['id_zasob']) $row['id_zasob'] = DB::getPDO()->fetchValue("select ID from CRM_LISTA_ZASOBOW where `DESC` = '{$row['COLUMN_NAME']}' and PARENT_ID = {$idTable} limit 1");
  122. return $row;
  123. }, DB::getPDO()->fetchAll("
  124. select t.TABLE_NAME, t.COLUMN_NAME, t.DATA_TYPE, t.COLUMN_TYPE
  125. from `information_schema`.`COLUMNS` t
  126. where t.TABLE_SCHEMA = '{$databaseName}'
  127. and t.TABLE_NAME like '{$tableName}'
  128. ")
  129. )
  130. ]);
  131. if (!empty($csvIdProces)) {
  132. $csvIdProces = implode(",", $csvIdProces);
  133. UI::tag('p', null, "DBG csvIdProces({$csvIdProces})");
  134. $userLogin = User::getLogin();
  135. $dbgExecTime->log('before sql');
  136. $rows = DB::getPDO()->fetchAll("select ID_PROCES from `CRM_PROCES_idx_USER_to_PROCES_VIEW` where ADM_ACCOUNT = '{$userLogin}' and ID_PROCES in({$csvIdProces}) group by ID_PROCES");
  137. $dbgExecTime->log('after sql', ['sql']);
  138. UI::table(['caption' => "from CRM_PROCES_idx_USER_to_PROCES_VIEW", 'rows' => $rows]);
  139. $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
  140. $userTablePerms = array();
  141. foreach ($aclTableRows as $row) {
  142. if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
  143. if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
  144. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
  145. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
  146. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
  147. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
  148. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
  149. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
  150. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
  151. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
  152. } else {
  153. $userTablePerms[ $row['CELL_NAME'] ] = $row;
  154. unset($userTablePerms[ $row['CELL_NAME'] ][ 'TABLE_DESCRIPTION' ]);
  155. unset($userTablePerms[ $row['CELL_NAME'] ][ 'ID_PROCES' ]);
  156. unset($userTablePerms[ $row['CELL_NAME'] ][ 'FORM_TREAT' ]);
  157. }
  158. }
  159. UI::table(['caption' => "\$userTablePerms", 'rows' => $userTablePerms]);
  160. } else UI::alert('warning', "brak \$csvIdProces");
  161. $dbgExecTime->printDebug();
  162. UI::endContainer();
  163. }
  164. } catch (Exception $e) {
  165. UI::startContainer();
  166. UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
  167. UI::endContainer();
  168. DBG::log($e);
  169. }
  170. UI::dol();
  171. }
  172. public function rmUserTableFilterAjaxAction() {
  173. Response::sendTryCatchJson(array($this, 'rmUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  174. }
  175. public function rmUserTableFilterAjax($args) {
  176. $namespace = V::get('namespace', '', $args);
  177. $filtrName = V::get('filtrName', '', $args);
  178. if (!$namespace) throw new Exception("Missing namespace");
  179. if (!$filtrName) throw new Exception("Missing filtrName");
  180. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  181. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  182. if (!$currentFilters) return [
  183. 'type' => 'warning',
  184. 'msg' => "Brak filtrów w bazie",
  185. ];
  186. $currentFilters = json_decode($currentFilters, 'assoc');
  187. unset($currentFilters[$namespace][$filtrName]);
  188. $affeced = DB::getPDO()->update('CRM_CONFIG', 'CONF_KEY', $userFltrConfKey, [
  189. 'CONF_VAL' => json_encode($currentFilters)
  190. ]);
  191. return [
  192. 'type' => 'success',
  193. 'msg' => 'Zapisano nowy filtr',
  194. 'data' => $currentFilters[$namespace]
  195. ];
  196. }
  197. public function addUserTableFilterAjaxAction() {
  198. Response::sendTryCatchJson(array($this, 'addUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  199. }
  200. public function addUserTableFilterAjax($args) {
  201. $namespace = V::get('namespace', '', $args);
  202. $filtrName = V::get('filtrName', '', $args);
  203. $visibleCols = V::get('visibleCols', '', $args);
  204. if (!$namespace) throw new Exception("Missing namespace");
  205. if (!$filtrName) throw new Exception("Missing filtrName");
  206. if (!$visibleCols) throw new Exception("Missing visibleCols");
  207. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  208. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  209. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  210. $currentFilters[$namespace][$filtrName] = $visibleCols;
  211. $sqlFltr = json_encode($currentFilters);
  212. DB::getPDO()->execSql("
  213. insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  214. values ('$userFltrConfKey', '{$sqlFltr}')
  215. on duplicate key update CONF_VAL = '{$sqlFltr}'
  216. ");
  217. return [
  218. 'type' => 'success',
  219. 'msg' => 'Zapisano nowy filtr',
  220. 'data' => $currentFilters[$namespace]
  221. ];
  222. }
  223. public function getUserTableFilterAjaxAction() {
  224. Response::sendTryCatchJson(array($this, 'getUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  225. }
  226. public function getUserTableFilterAjax($args) {
  227. $namespace = V::get('namespace', '', $args);
  228. if (!$namespace) throw new Exception("Missing namespace");
  229. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  230. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  231. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  232. return [
  233. 'type' => 'success',
  234. 'msg' => 'Odczytano filtry użytkownika',
  235. 'data' => (!empty($currentFilters[$namespace])) ? $currentFilters[$namespace] : []
  236. ];
  237. }
  238. public function revertFromHistAjaxAction() {
  239. Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
  240. }
  241. public function revertFromHistAjax() {
  242. $typeName = V::get('typeName', '', $_REQUEST, 'word');
  243. if (!$typeName) throw new Exception("Wrong param typeName");
  244. // TODO: use namespace from url
  245. // $namespace = V::get('namespace', '', $_GET, 'word');
  246. // if (!$namespace) {
  247. // $typeName = V::get('typeName', '', $_GET, 'word');
  248. // if (!$typeName) throw new Exception("Wrong param typeName");
  249. // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  250. // }
  251. // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  252. $id = V::get('ID', '', $_REQUEST, 'word');
  253. if (!$id) throw new Exception("Wrong param ID");
  254. $idHist = V::get('idHist', '', $_REQUEST, 'word');
  255. if (!$idHist) throw new Exception("Wrong param idHist");
  256. $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
  257. if (!$fieldName) throw new Exception("Wrong param fieldName");
  258. $acl = Core_AclHelper::getAclByTypeName($typeName);
  259. $item = $acl->getItem($id);
  260. if (!$item) throw new HttpException("Item not found", 404);
  261. if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
  262. $histItem = $acl->getHistItem($id, $idHist);
  263. if (!$histItem) throw new HttpException("Hist Item not found", 404);
  264. $histValue = V::get($fieldName, 'N/S;', $histItem);
  265. if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
  266. if ($acl->isGeomField($fieldName)) {
  267. $wktType = strtoupper($acl->getGeomFieldType($fieldName));
  268. if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
  269. if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
  270. $coords = trim(substr($histValue, strlen($wktType)), '()');
  271. $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
  272. if (!$wktValue) throw new Exception("BUG in hist record");
  273. $sqlObj = array();
  274. $sqlObj['ID'] = $id;
  275. $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
  276. $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
  277. if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
  278. else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
  279. $jsonResponse = array();
  280. $jsonResponse['type'] = 'success';
  281. $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
  282. $jsonResponse['actions'] = array();
  283. $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
  284. return $jsonResponse;
  285. } else {
  286. throw new HttpException("Not implemented - update from hist only for the geom field", 501);
  287. }
  288. throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
  289. }
  290. public function removeTheGeomAjaxAction() {
  291. Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  292. }
  293. public function removeTheGeomAjax($args) {
  294. $namespace = V::get('namespace', '', $args, 'word');
  295. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  296. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  297. $primaryKeyField = $acl->getPrimaryKeyField();
  298. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  299. $geomFieldName = 'the_geom';
  300. $response = new stdClass();
  301. if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
  302. $record = $acl->getItem($primaryKey);
  303. if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  304. if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  305. if (empty($record->{$geomFieldName})) {
  306. $response->type = 'info';
  307. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  308. $response->record = $record;
  309. return $response;
  310. }
  311. $itemPatch = array();
  312. $itemPatch[$geomFieldName] = "NULL";
  313. $itemPatch[$primaryKeyField] = $primaryKey;
  314. $response = new stdClass();
  315. try {
  316. $affected = $acl->updateItem($itemPatch);
  317. if ($affected > 0) {
  318. $response->type = 'success';
  319. $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
  320. } else if ($affected == 0) {
  321. $response->type = 'info';
  322. $response->msg = "Nie wprowadzono żadnych zmian";
  323. }
  324. $response->record = $acl->getItem($primaryKey);
  325. }
  326. catch (Exception $e) {
  327. $response->type = 'error';
  328. $response->msg = $e->getMessage();
  329. }
  330. return $response;
  331. }
  332. public function moreFunctionsCellAjaxAction() {
  333. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  334. }
  335. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  336. $id = V::get('ID', 0, $args, 'int');
  337. if ($id <= 0) throw new HttpException("404", 404);
  338. $namespace = V::get('namespace', '', $args, 'word');
  339. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  340. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  341. $response = new stdClass();
  342. $response->type = 'success';
  343. $response->msg = 'Funkcje';
  344. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  345. return $response;
  346. }
  347. public function editFormAction() {// namespace, _hash, _primaryKey
  348. try {
  349. $args = $_REQUEST;
  350. $id = V::get('_primaryKey', 0, $args, 'int');
  351. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  352. $namespace = V::get('namespace', '', $args, 'word');
  353. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  354. $acl = Core_AclHelper::getAclByNamespace($namespace);
  355. $tbl = $this->getTableAjaxWidget($acl);
  356. $tbl->sendAjaxEdit($id, $args);
  357. } catch (Exception $e) {
  358. DBG::log($e);
  359. throw $e;
  360. }
  361. }
  362. public function editFormJsonAction() {
  363. Response::sendTryCatchJson(array($this, 'editFormJson'), $args = $_REQUEST);
  364. }
  365. public function editFormJson($args) {// namespace, _hash, _primaryKey
  366. $id = V::get('_primaryKey', 0, $args, 'int');
  367. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  368. $namespace = V::get('namespace', '', $args, 'word');
  369. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  370. $acl = Core_AclHelper::getAclByNamespace($namespace);
  371. $tbl = $this->getTableAjaxWidget($acl);
  372. $record = $acl->buildQuery([])->getItem($id);
  373. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) throw new Exception("Brak dostępu do rekordu");
  374. $fieldsList = array();
  375. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  376. if ($fieldName == 'ID') continue;
  377. $field['name'] = $fieldName;
  378. $field['opis'] = $acl->getFieldOpis($fieldName);
  379. $field['label'] = $acl->getFieldLabel($fieldName);
  380. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  381. $fieldsList[$kID] = $field;
  382. }
  383. $cols = array();
  384. foreach ($fieldsList as $kID => $field) {
  385. $cols[$kID] = '';
  386. if ($acl->canReadObjectField($field['name'], $record)) {
  387. $cols[$kID] = V::get($field['name'], '', $record);
  388. } else {
  389. $cols[$kID] = '*****';
  390. }
  391. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  392. }
  393. $tsValues = array();
  394. if (!empty($fieldsList)) {
  395. foreach ($fieldsList as $vColID => $vCol) {
  396. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  397. if ($typeSpecial) {
  398. $colValue = V::get($vCol['name'], '', $record);
  399. $specialValues = $typeSpecial->getEditSelectedValuesByIds($acl->getID(), $record['ID'], $vCol['name'], $colValue);
  400. if (!empty($specialValues)) {
  401. $tsValues[$vColID] = implode('<br>', $specialValues);
  402. }
  403. }
  404. }
  405. }
  406. DBG::log($tsValues, 'array', "editFormJson::tsValues");
  407. foreach ($tsValues as $idx => $value) {
  408. if ('<' === substr($value, 0, 1)) {
  409. // $tsValues[$idx] = UI::convertHtmlToArray($value); // TODO: ...
  410. $tsValues[$idx] = [ 'P5UI__RawHtml', [ 'rawHtml' => $tsValues[$idx] ] ];
  411. }
  412. }
  413. DBG::log($tsValues, 'array', "editFormJson::tsValues parsed");
  414. $featureFunctions = [
  415. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  416. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  417. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  418. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  419. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  420. ];
  421. $rowFunctionsOut = [ 'P5UI__FeatureRowFunctions', [
  422. 'id' => $record['ID'],
  423. 'functions' => $featureFunctions,
  424. 'showLabels' => true,
  425. 'viewMoreDropdown' => [
  426. 'primaryKey' => $record['ID'],
  427. 'uri' => $this->getLink('moreFunctionsCellAjax', [ 'namespace' => $acl->getNamespace(), 'ID' => $record['ID'] ]),
  428. ],
  429. ] ]; // TODO: $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  430. $jsFields = [];
  431. $tabindex = 0;
  432. foreach ($fieldsList as $kID => $vCol) {
  433. $fieldName = $vCol['name'];
  434. if ($acl->canWriteObjectField($fieldName, $record)) {
  435. DBG::log("editFormJson::field({$fieldName})");
  436. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  437. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  438. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  439. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  440. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label'] ],
  441. [ 'i', [ 'class' => "glyphicon glyphicon-info-sign frm-help", 'data-toggle' => "popover", 'data-trigger' => "hover", 'title' => "", 'data-content' => htmlspecialchars($vCol['opis']), 'data-original-title' => "[{$kID}] {$fieldName}" ] ],
  442. ] ],
  443. [ 'div', [ 'class' => "" ], [
  444. UI::hGetFormItem($acl, $fieldName, 'W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record),
  445. ] ]
  446. ] ];
  447. } else if ($acl->canReadObjectField($fieldName, $record)) {
  448. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  449. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  450. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label']],
  451. [ 'i', [ 'class' => "glyphicon glyphicon-info-sign frm-help", 'data-toggle' => "popover", 'data-trigger' => "hover", 'title' => "", 'data-content' => htmlspecialchars($vCol['opis']), 'data-original-title' => "[{$kID}] {$fieldName}" ] ],
  452. ] ],
  453. [ 'div', [ 'class' => "" ], [
  454. ['p', [ 'style' => [ 'margin-top' => '5px' ] ], [
  455. (!empty($tsValues[$kID]))
  456. ? $tsValues[$kID]
  457. : V::get($fieldName, '', $record)
  458. ] ],
  459. ] ]
  460. ] ];
  461. } else {
  462. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  463. "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  464. ]];
  465. }
  466. }
  467. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  468. [ 'div', [ 'class' => "" ], [
  469. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  470. ] ]
  471. ] ];
  472. $tblLabel = $acl->getNamespace();
  473. if ('default_db' == $acl->getSourceName()) {
  474. $tblLabel = array();
  475. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  476. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  477. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  478. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  479. $tblLabel = implode(" - ", $tblLabel);
  480. }
  481. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  482. $jsGui = [
  483. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  484. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  485. "Edycja rekordu Nr {$record['ID']}",
  486. [ 'small', [ 'class' => "pull-right valign-btns-bottom" ], [ $rowFunctionsOut ] ],
  487. ] ],
  488. [ 'P5UI__FeatureEditForm', [
  489. 'class' => "", 'action' => "", 'method' => "post",
  490. 'id' => "EDIT_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  491. 'ajaxSaveUrl' => "{$syncUrl}&_task=editSaveAjax", // TODO:? &_hash={$this->_htmlID}
  492. 'namespace' => $acl->getNamespace(),
  493. 'idRecord' => $record['ID'],
  494. 'tableLabelHtml' => $tblLabel,
  495. ], [
  496. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  497. ] ] // form
  498. ] ] // .container
  499. ];
  500. return [
  501. 'type' => "success",
  502. 'msg' => "Edycja rekordu nr {$id}",
  503. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  504. ];
  505. }
  506. public function editSaveAjaxAction() {
  507. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  508. }
  509. public function editSaveAjax($args) {
  510. $namespace = V::get('namespace', '', $args, 'word');
  511. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  512. $acl = Core_AclHelper::getAclByNamespace($namespace);
  513. $primaryKeyField = $acl->getPrimaryKeyField();
  514. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  515. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  516. $item = $acl->getItem($primaryKey);
  517. if (!$item) throw new HttpException("Item not exists!", 404);
  518. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  519. $response = new stdClass();
  520. $response->primaryKey = $primaryKey;
  521. try {
  522. $itemFromUser[$primaryKeyField] = $primaryKey;
  523. $affected = $acl->updateItem($itemFromUser);
  524. if ($affected > 0) {
  525. $response->type = 'success';
  526. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  527. } else if ($affected == 0) {
  528. $response->type = 'info';
  529. $response->msg = "Nie wprowadzono żadnych zmian";
  530. }
  531. $response->record = $acl->getItem($primaryKey);
  532. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  533. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  534. }
  535. catch (Exception $e) {
  536. $response->type = 'error';
  537. $response->msg = "Wystąpiły błędy!";
  538. $response->msg .= $e->getMessage();
  539. }
  540. return $response;
  541. }
  542. public function typeSpecialCellAction() {
  543. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  544. }
  545. public function typeSpecialCell($args) {
  546. $namespace = V::get('namespace', '', $args, 'word');
  547. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  548. $acl = Core_AclHelper::getAclByNamespace($namespace);
  549. $id = V::get('ID', 0, $args, 'int');
  550. $fieldName = V::get('col', '', $args);
  551. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  552. $col = $fieldName;// TODO: RM $col
  553. $jsonData = new stdClass();
  554. $idField = $acl->getFieldIdByName($fieldName);
  555. if (!$idField) throw new Exception("Wrong field");
  556. $item = $acl->getItem($id);
  557. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  558. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  559. if ($typeSpecial) {
  560. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  561. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  562. }
  563. return $jsonData;
  564. }
  565. /**
  566. * @param $_GET['namespace'] = AclNamespace
  567. * @param $_GET['format'] = 'csv' | 'html'
  568. * @param $_GET['flds'] = csv - coma separated field names
  569. * @param $_GET['sortCol'] = FieldName
  570. * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
  571. * @param $_GET['f_{$fieldName}'] = filter
  572. * @param $_GET['sf_{$fieldName}'] = force filter
  573. */
  574. public function exportAction() {
  575. $args = $_GET;
  576. $namespace = V::get('namespace', '', $args, 'word');
  577. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  578. $acl = Core_AclHelper::getAclByNamespace($namespace);
  579. $exportLimit = 10000;
  580. $params = array();
  581. $params['limit'] = $exportLimit;
  582. // $params['limitstart'] = 0;
  583. $params['order_by'] = V::get('sortCol', '', $args);
  584. $params['order_dir'] = V::get('sortDir', '', $args);
  585. $params['cols'] = array($acl->getPrimaryKeyField());
  586. $toExportFields = explode(',', V::get('flds', '', $_GET));
  587. if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
  588. $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
  589. foreach ($toExportFields as $fieldName) {
  590. if ($fieldName == $acl->getPrimaryKeyField()) continue;
  591. if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
  592. $params['cols'][] = $fieldName;
  593. }
  594. $labels = array();
  595. foreach ($toExportFields as $fieldName) {
  596. $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
  597. }
  598. foreach ($args as $k => $v) {
  599. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  600. $params[$k] = $v;
  601. }
  602. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  603. $params[$k] = $v;
  604. }
  605. }
  606. try {
  607. $queryFeatures = $acl->buildQuery($params);
  608. $total = $queryFeatures->getTotal();
  609. $listItems = $queryFeatures->getItems();
  610. $primaryKeyField = $acl->getPrimaryKeyField();
  611. $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
  612. } catch (Exception $e) {
  613. DBG::log($e);
  614. throw $e;
  615. }
  616. $format = V::get('format', 'html', $_GET);
  617. switch ($format) {
  618. case 'html': {
  619. UI::gora();
  620. echo UI::h('table', ['class'=>'table table-bordered table-hover'], [
  621. UI::h('thead', [], [
  622. UI::h('tr', [], array_map(function ($label) {
  623. return UI::h('th', [], $label);
  624. }, $labels))
  625. ]),
  626. UI::h('tbody', [], array_map(function ($item) use($labels) {
  627. return UI::h('tr', [], array_map(function ($fieldName) use ($item) {
  628. return UI::h('td', [], V::get($fieldName, '', $item));
  629. }, array_keys($labels)));
  630. }, $items)),
  631. ]);
  632. UI::dol();
  633. exit;
  634. }
  635. case 'csv_cp1250':
  636. case 'csv': {
  637. $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
  638. header('Content-Type: text/csv; charset=utf-8');
  639. header("Content-Disposition: attachment; filename={$csvFileName}.csv");
  640. $csvSeparator = ';';
  641. $csvHeader = implode($csvSeparator, array_map(function ($label) use ($item) {
  642. return '"' . addslashes($label) . '"';
  643. }, array_values($labels)));
  644. $csvRows = implode("\r\n", array_map(function ($item) use ($labels, $csvSeparator) {
  645. return implode($csvSeparator, array_map(function ($fieldName) use ($item) {
  646. return '"' . addslashes(V::get($fieldName, '', $item)) . '"';
  647. }, array_keys($labels)));
  648. }, $items));
  649. switch ($format) {
  650. case 'csv': echo $csvHeader . "\n" . $csvRows; exit;
  651. case 'csv_cp1250': echo iconv('utf-8', 'Windows-1250//IGNORE', $csvHeader) . "\r\n" . iconv('utf-8', 'Windows-1250//IGNORE', $csvRows); exit;
  652. die("Nieobsługiwane kodowanie danych csv.");
  653. }
  654. exit;
  655. }
  656. }
  657. die("Nieobsługiwany format danych.");
  658. }
  659. public function loadDataAjaxAction() {
  660. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  661. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  662. $acl = Core_AclHelper::getAclByNamespace($namespace);
  663. $tbl = $this->getTableAjaxWidget($acl);
  664. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  665. }
  666. public function uploadFilesAjaxAction() {
  667. Response::sendTryCatchJson([$this, 'uploadFilesAjax'], $args = $_POST);
  668. }
  669. public function uploadFilesAjax($args) {
  670. DBG::log($_FILES, 'array', "\$_FILES");
  671. DBG::log($args, 'array', "\$args");
  672. $namespace = V::get('namespace', '', $args, 'word');
  673. if (!$namespace) throw new Exception("Missing namespace");
  674. $primaryKey = V::get('primaryKey', '', $args, 'int');
  675. if ($primaryKey <= 0) throw new Exception("Missing primaryKey");
  676. if (empty($_FILES)) throw new Exception("Missing files");
  677. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  678. Lib::loadClass('FileUploader');
  679. Lib::loadClass('FoldersConfig');
  680. // $dbID = $acl->getDB();
  681. // $db = DB::getDB($dbID);
  682. // if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  683. $record = $acl->buildQuery([])->getItem($primaryKey);
  684. DBG::log($record, 'array', "\$record");
  685. if (!$record) throw new HttpException("No item ID({$primaryKey})", 404);
  686. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  687. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  688. $rootTableName = $acl->getRootTableName();
  689. $confTblName = "{$rootTableName}_COLUMN";
  690. $folderConfAll = FoldersConfig::getRawData();
  691. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$rootTableName})", 404);
  692. $folderConf = FoldersConfig::getAll($confTblName);
  693. DBG::log($folderConf, 'array', "\$folderConf");
  694. $uploader = new FileUploader($confTblName, (object)$record);
  695. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$rootTableName})", 404);
  696. $uploader->findFolder();
  697. DBG::log($uploader, 'array', "\$uploader");
  698. // $errorMsg = '';
  699. // if (!empty($args['SCANS_COLUMN_ADD'])) {
  700. // $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  701. // }
  702. // else {
  703. // $uploaded = $uploader->tryUploadAjax($errorMsg);
  704. // }
  705. $destPath = $uploader->getDestLocalPath($show_if_not_found = true);
  706. DBG::log($destPath, 'array', "\$destPath");
  707. if (!file_exists($destPath)) {
  708. if (!$uploader->tryCreateDestFolder($destPath)) throw new Exception("Wystąpił błąd podczas tworzenie katalogu dla rekordu '{$primaryKey}'");
  709. }
  710. $generateSafeFileName = function($destPath, $fileName) {
  711. if (!file_exists("{$destPath}/{$fileName}")) return $fileName;
  712. $infoPath = pathinfo($fileName);
  713. // pathinfo('/path/t1/t2/fileName.ext') = [
  714. // [dirname] => /path/t1/t2
  715. // [basename] => fileName.ext
  716. // [extension] => ext
  717. // [filename] => fileName
  718. // ]
  719. return $infoPath['filename'] . "--" . date("Y-m-d_H-i-s") . "." . $infoPath['extension'];
  720. };
  721. $moveActions = array_map(function ($file) use ($destPath, $generateSafeFileName) {
  722. $safeName = $generateSafeFileName($destPath, $file['name']);
  723. return [
  724. $file['tmp_name'],
  725. "{$destPath}/{$safeName}",
  726. $safeName,
  727. ];
  728. }, $_FILES);
  729. DBG::log($moveActions, 'array', "\$moveActions"); // [ [ srcPath, descPath ] ]
  730. $errorMsgs = [];
  731. $pkField = $acl->getSqlPrimaryKeyField();
  732. foreach ($moveActions as $fileMoveAction) {
  733. if (!move_uploaded_file($fileMoveAction[0], $fileMoveAction[1])) {
  734. $errorMsgs[] = "Nie udało się wgrać pliku '{$fileMoveAction[2]}'";
  735. } else {
  736. try {
  737. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  738. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  739. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  740. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  741. ]);
  742. if ($affected) {
  743. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  744. 'ID_USERS2' => $primaryKey,
  745. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  746. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  747. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  748. ]);
  749. }
  750. } catch (Exception $e) {
  751. DBG::log($e);
  752. $errorMsgs[] = $e->getMessage();
  753. }
  754. }
  755. }
  756. if (!empty($errorMsgs)) {
  757. return [
  758. 'type' => "error",
  759. 'msg' => "Wystąpiły błędy podczas wgrywania plików dla '{$primaryKey}'",
  760. 'errors' => $errorMsgs,
  761. ];
  762. }
  763. return [
  764. 'type' => "success",
  765. 'msg' => "Wgrano nowe pliki dla '{$primaryKey}'",
  766. ];
  767. }
  768. public function removeFileAjaxAction() {
  769. Response::sendTryCatchJson([$this, 'removeFileAjax'], $args = $_REQUEST);
  770. }
  771. public function removeFileAjax($args) { // ajaxFileRemove
  772. $namespace = V::get('namespace', '', $args, 'word');
  773. if (!$namespace) throw new Exception("Missing namespace");
  774. $id = V::get('ID', 0, $args, 'int');
  775. if ($id <= 0) throw new Exception("Missing ID");
  776. $filename = V::get('filename', '', $args);
  777. if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
  778. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  779. $dbID = $acl->getDB();
  780. $db = DB::getPDO($dbID);
  781. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  782. $record = $acl->buildQuery([])->getItem($id);
  783. if (!$record) throw new HttpException("No item ID({$id})", 404);
  784. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  785. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  786. Lib::loadClass('FileUploader');
  787. Lib::loadClass('FoldersConfig');
  788. $tblName = $acl->getName();
  789. $confTblName = "{$tblName}_COLUMN";
  790. $folderConfAll = FoldersConfig::getRawData();
  791. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  792. $folderConf = FoldersConfig::getAll($confTblName);
  793. $uploader = new FileUploader($confTblName, (object)$record);
  794. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  795. $uploader->findFolder();
  796. $errorMsg = '';
  797. $removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
  798. if (!$removed) throw new Exception($errorMsg);
  799. // $affected = DB::getPDO($acl->getDB())->update();
  800. $rootTableName = $acl->getRootTableName();
  801. $pkField = $acl->getSqlPrimaryKeyField();
  802. $primaryKey = $id;
  803. try {
  804. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  805. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  806. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  807. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  808. ]);
  809. if ($affected) {
  810. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  811. 'ID_USERS2' => $primaryKey,
  812. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  813. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  814. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  815. ]);
  816. }
  817. } catch (Exception $e) {
  818. DBG::log($e);
  819. }
  820. return [
  821. 'type' => 'success',
  822. 'msg' => 'Plik został usunięty',
  823. ];
  824. }
  825. public function procesInitFiltrAjaxAction() {
  826. Response::sendTryCatchJson([$this, 'procesInitFiltrAjax'], $args = $_GET);
  827. }
  828. public function procesInitFiltrAjax($args) { // ajaxFileRemove
  829. $namespace = V::get('namespace', '', $args, 'word');
  830. if (!$namespace) throw new Exception("Missing namespace");
  831. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  832. $pInitList = User::getAcl()->getTableProcesInitList($acl->getID());
  833. DBG::log($pInitList, 'array', "\$pInitList");
  834. if (!empty($pInitList)) {
  835. $procesIds = array_keys($pInitList);
  836. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  837. DBG::log($mapTree, 'array', "\$mapTree");
  838. DBG::log($pInitList, 'array', "\$pInitList");
  839. $pInitListSelected = User::getAcl()->getPermsFiltrProcesId();
  840. return [
  841. 'type' => 'success',
  842. 'msg' => 'ok',
  843. 'pInitData' => [
  844. 'pInitList' => $pInitList,
  845. 'mapTree' => $mapTree,
  846. 'pInitListSelected' => $pInitListSelected,
  847. ],
  848. ];
  849. }
  850. return [
  851. 'type' => 'success'
  852. ];
  853. }
  854. }