ViewTableAjax.php 40 KB

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