ViewTableAjax.php 39 KB

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