ViewTableAjax.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992
  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 ($_REQUEST 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()) {
  390. return [
  391. 'type' => "success",
  392. 'msg' => "Edycja rekordu nr {$id}",
  393. 'body' => [
  394. 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak dostępu do rekordu" ]
  395. ],
  396. ];
  397. // throw new Exception("Brak dostępu do rekordu");
  398. }
  399. $fieldsList = array();
  400. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  401. if ($fieldName == 'ID') continue;
  402. $field['name'] = $fieldName;
  403. $field['opis'] = $acl->getFieldOpis($fieldName);
  404. $field['label'] = $acl->getFieldLabel($fieldName);
  405. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  406. $fieldsList[$kID] = $field;
  407. }
  408. $cols = array();
  409. foreach ($fieldsList as $kID => $field) {
  410. $cols[$kID] = '';
  411. if ($acl->canReadObjectField($field['name'], $record)) {
  412. $cols[$kID] = V::get($field['name'], '', $record);
  413. } else {
  414. $cols[$kID] = '*****';
  415. }
  416. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  417. }
  418. $tsValues = array();
  419. if (!empty($fieldsList)) {
  420. foreach ($fieldsList as $vColID => $vCol) {
  421. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  422. if ($typeSpecial) {
  423. $colValue = V::get($vCol['name'], '', $record);
  424. $specialValues = $typeSpecial->getEditSelectedValuesByIds($acl->getID(), $record['ID'], $vCol['name'], $colValue);
  425. if (!empty($specialValues)) {
  426. $tsValues[$vColID] = implode('<br>', $specialValues);
  427. }
  428. }
  429. }
  430. }
  431. DBG::log($tsValues, 'array', "editFormJson::tsValues");
  432. foreach ($tsValues as $idx => $value) {
  433. if ('<' === substr($value, 0, 1)) {
  434. // $tsValues[$idx] = UI::convertHtmlToArray($value); // TODO: ...
  435. $tsValues[$idx] = [ 'P5UI__RawHtml', [ 'rawHtml' => $tsValues[$idx] ] ];
  436. }
  437. }
  438. DBG::log($tsValues, 'array', "editFormJson::tsValues parsed");
  439. $featureFunctions = [
  440. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  441. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  442. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  443. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  444. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  445. ];
  446. $rowFunctionsOut = [ 'P5UI__FeatureRowFunctions', [
  447. 'id' => $record['ID'],
  448. 'functions' => $featureFunctions,
  449. 'showLabels' => true,
  450. 'viewMoreDropdown' => [
  451. 'primaryKey' => $record['ID'],
  452. 'uri' => $this->getLink('moreFunctionsCellAjax', [ 'namespace' => $acl->getNamespace(), 'ID' => $record['ID'] ]),
  453. ],
  454. ] ]; // TODO: $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  455. $jsFields = [];
  456. $tabindex = 0;
  457. foreach ($fieldsList as $kID => $vCol) {
  458. $fieldName = $vCol['name'];
  459. if ($acl->canWriteObjectField($fieldName, $record)) {
  460. DBG::log("editFormJson::field({$fieldName})");
  461. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  462. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  463. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  464. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  465. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label'] ],
  466. [ '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}" ] ],
  467. ] ],
  468. [ 'div', [ 'class' => "" ], [
  469. UI::hGetFormItem($acl, $fieldName, 'W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record),
  470. ] ]
  471. ] ];
  472. } else if ($acl->canReadObjectField($fieldName, $record)) {
  473. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  474. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  475. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label']],
  476. [ '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}" ] ],
  477. ] ],
  478. [ 'div', [ 'class' => "" ], [
  479. ['p', [ 'style' => [ 'margin-top' => '5px' ] ], [
  480. (!empty($tsValues[$kID]))
  481. ? $tsValues[$kID]
  482. : V::get($fieldName, '', $record)
  483. ] ],
  484. ] ]
  485. ] ];
  486. } else {
  487. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  488. "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  489. ]];
  490. }
  491. }
  492. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  493. [ 'div', [ 'class' => "" ], [
  494. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  495. ] ]
  496. ] ];
  497. $tblLabel = $acl->getNamespace();
  498. if ('default_db' == $acl->getSourceName()) {
  499. $tblLabel = array();
  500. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  501. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  502. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  503. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  504. $tblLabel = implode(" - ", $tblLabel);
  505. }
  506. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  507. $jsGui = [
  508. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  509. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  510. "Edycja rekordu Nr {$record['ID']}",
  511. [ 'small', [ 'class' => "pull-right valign-btns-bottom" ], [ $rowFunctionsOut ] ],
  512. ] ],
  513. [ 'P5UI__FeatureEditForm', [
  514. 'class' => "", 'action' => "", 'method' => "post",
  515. 'id' => "EDIT_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  516. 'ajaxSaveUrl' => "{$syncUrl}&_task=editSaveAjax", // TODO:? &_hash={$this->_htmlID}
  517. 'namespace' => $acl->getNamespace(),
  518. 'idRecord' => $record['ID'],
  519. 'tableLabelHtml' => $tblLabel,
  520. ], [
  521. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  522. ] ] // form
  523. ] ] // .container
  524. ];
  525. return [
  526. 'type' => "success",
  527. 'msg' => "Edycja rekordu nr {$id}",
  528. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  529. ];
  530. }
  531. public function editSaveAjaxAction() {
  532. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  533. }
  534. public function editSaveAjax($args) {
  535. $namespace = V::get('namespace', '', $args, 'word');
  536. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  537. $acl = Core_AclHelper::getAclByNamespace($namespace);
  538. $primaryKeyField = $acl->getPrimaryKeyField();
  539. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  540. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  541. $item = $acl->getItem($primaryKey);
  542. if (!$item) throw new HttpException("Item not exists!", 404);
  543. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  544. $response = new stdClass();
  545. $response->primaryKey = $primaryKey;
  546. try {
  547. $itemFromUser[$primaryKeyField] = $primaryKey;
  548. $affected = $acl->updateItem($itemFromUser);
  549. if ($affected > 0) {
  550. $response->type = 'success';
  551. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  552. } else if ($affected == 0) {
  553. $response->type = 'info';
  554. $response->msg = "Nie wprowadzono żadnych zmian";
  555. }
  556. $response->record = $acl->getItem($primaryKey);
  557. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  558. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  559. }
  560. catch (Exception $e) {
  561. $response->type = 'error';
  562. $response->msg = "Wystąpiły błędy!";
  563. $response->msg .= $e->getMessage();
  564. }
  565. return $response;
  566. }
  567. public function typeSpecialCellAction() {
  568. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  569. }
  570. public function typeSpecialCell($args) {
  571. $namespace = V::get('namespace', '', $args, 'word');
  572. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  573. $acl = Core_AclHelper::getAclByNamespace($namespace);
  574. $id = V::get('ID', 0, $args, 'int');
  575. $fieldName = V::get('col', '', $args);
  576. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  577. $col = $fieldName;// TODO: RM $col
  578. $jsonData = new stdClass();
  579. $idField = $acl->getFieldIdByName($fieldName);
  580. if (!$idField) throw new Exception("Wrong field");
  581. $item = $acl->getItem($id);
  582. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  583. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  584. if ($typeSpecial) {
  585. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  586. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  587. }
  588. return $jsonData;
  589. }
  590. /**
  591. * @param $_GET['namespace'] = AclNamespace
  592. * @param $_GET['format'] = 'csv' | 'html'
  593. * @param $_GET['flds'] = csv - coma separated field names
  594. * @param $_GET['sortCol'] = FieldName
  595. * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
  596. * @param $_GET['f_{$fieldName}'] = filter
  597. * @param $_GET['sf_{$fieldName}'] = force filter
  598. */
  599. public function exportAction() {
  600. $args = $_GET;
  601. $namespace = V::get('namespace', '', $args, 'word');
  602. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  603. $acl = Core_AclHelper::getAclByNamespace($namespace);
  604. $exportLimit = 10000;
  605. $params = array();
  606. $params['limit'] = $exportLimit;
  607. // $params['limitstart'] = 0;
  608. $params['order_by'] = V::get('sortCol', '', $args);
  609. $params['order_dir'] = V::get('sortDir', '', $args);
  610. $params['cols'] = array($acl->getPrimaryKeyField());
  611. $toExportFields = explode(',', V::get('flds', '', $_GET));
  612. if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
  613. $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
  614. foreach ($toExportFields as $fieldName) {
  615. if ($fieldName == $acl->getPrimaryKeyField()) continue;
  616. if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
  617. $params['cols'][] = $fieldName;
  618. }
  619. $labels = array();
  620. foreach ($toExportFields as $fieldName) {
  621. $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
  622. }
  623. foreach ($args as $k => $v) {
  624. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  625. $params[$k] = $v;
  626. }
  627. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  628. $params[$k] = $v;
  629. }
  630. }
  631. try {
  632. $queryFeatures = $acl->buildQuery($params);
  633. $total = $queryFeatures->getTotal();
  634. $listItems = $queryFeatures->getItems();
  635. $primaryKeyField = $acl->getPrimaryKeyField();
  636. $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
  637. } catch (Exception $e) {
  638. DBG::log($e);
  639. throw $e;
  640. }
  641. $format = V::get('format', 'html', $_GET);
  642. switch ($format) {
  643. case 'html': {
  644. UI::gora();
  645. echo UI::h('table', ['class'=>'table table-bordered table-hover'], [
  646. UI::h('thead', [], [
  647. UI::h('tr', [], array_map(function ($label) {
  648. return UI::h('th', [], $label);
  649. }, $labels))
  650. ]),
  651. UI::h('tbody', [], array_map(function ($item) use($labels) {
  652. return UI::h('tr', [], array_map(function ($fieldName) use ($item) {
  653. return UI::h('td', [], V::get($fieldName, '', $item));
  654. }, array_keys($labels)));
  655. }, $items)),
  656. ]);
  657. UI::dol();
  658. exit;
  659. }
  660. case 'csv_cp1250':
  661. case 'csv': {
  662. $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
  663. header('Content-Type: text/csv; charset=utf-8');
  664. header("Content-Disposition: attachment; filename={$csvFileName}.csv");
  665. $csvSeparator = ';';
  666. $csvHeader = implode($csvSeparator, array_map(function ($label) use ($item) {
  667. return '"' . addslashes($label) . '"';
  668. }, array_values($labels)));
  669. $csvRows = implode("\r\n", array_map(function ($item) use ($labels, $csvSeparator) {
  670. return implode($csvSeparator, array_map(function ($fieldName) use ($item) {
  671. return '"' . addslashes(V::get($fieldName, '', $item)) . '"';
  672. }, array_keys($labels)));
  673. }, $items));
  674. switch ($format) {
  675. case 'csv': echo $csvHeader . "\n" . $csvRows; exit;
  676. case 'csv_cp1250': echo iconv('utf-8', 'Windows-1250//IGNORE', $csvHeader) . "\r\n" . iconv('utf-8', 'Windows-1250//IGNORE', $csvRows); exit;
  677. die("Nieobsługiwane kodowanie danych csv.");
  678. }
  679. exit;
  680. }
  681. }
  682. die("Nieobsługiwany format danych.");
  683. }
  684. public function loadDataAjaxAction() {
  685. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  686. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  687. $acl = Core_AclHelper::getAclByNamespace($namespace);
  688. $backRefFilter = [
  689. 'namespace' => V::get('backRefNS', '', $_REQUEST),
  690. 'primaryKey' => V::get('backRefPK', '', $_REQUEST),
  691. 'fieldName' => V::get('backRefField', '', $_REQUEST),
  692. ];
  693. $tbl = $this->getTableAjaxWidget($acl, $backRefFilter);
  694. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  695. }
  696. public function uploadFilesAjaxAction() {
  697. Response::sendTryCatchJson([$this, 'uploadFilesAjax'], $args = $_POST);
  698. }
  699. public function uploadFilesAjax($args) {
  700. DBG::log($_FILES, 'array', "\$_FILES");
  701. DBG::log($args, 'array', "\$args");
  702. $namespace = V::get('namespace', '', $args, 'word');
  703. if (!$namespace) throw new Exception("Missing namespace");
  704. $primaryKey = V::get('primaryKey', '', $args, 'int');
  705. if ($primaryKey <= 0) throw new Exception("Missing primaryKey");
  706. if (empty($_FILES)) throw new Exception("Missing files");
  707. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  708. Lib::loadClass('FileUploader');
  709. Lib::loadClass('FoldersConfig');
  710. // $dbID = $acl->getDB();
  711. // $db = DB::getDB($dbID);
  712. // if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  713. $record = $acl->buildQuery([])->getItem($primaryKey);
  714. DBG::log($record, 'array', "\$record");
  715. if (!$record) throw new HttpException("No item ID({$primaryKey})", 404);
  716. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  717. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  718. $rootTableName = $acl->getRootTableName();
  719. $confTblName = "{$rootTableName}_COLUMN";
  720. $folderConfAll = FoldersConfig::getRawData();
  721. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$rootTableName})", 404);
  722. $folderConf = FoldersConfig::getAll($confTblName);
  723. DBG::log($folderConf, 'array', "\$folderConf");
  724. $uploader = new FileUploader($confTblName, (object)$record);
  725. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$rootTableName})", 404);
  726. $uploader->findFolder();
  727. DBG::log($uploader, 'array', "\$uploader");
  728. // $errorMsg = '';
  729. // if (!empty($args['SCANS_COLUMN_ADD'])) {
  730. // $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  731. // }
  732. // else {
  733. // $uploaded = $uploader->tryUploadAjax($errorMsg);
  734. // }
  735. $destPath = $uploader->getDestLocalPath($show_if_not_found = true);
  736. DBG::log($destPath, 'array', "\$destPath");
  737. if (!file_exists($destPath)) {
  738. if (!$uploader->tryCreateDestFolder($destPath)) throw new Exception("Wystąpił błąd podczas tworzenie katalogu dla rekordu '{$primaryKey}'");
  739. }
  740. $generateSafeFileName = function($destPath, $fileName) {
  741. if (!file_exists("{$destPath}/{$fileName}")) return $fileName;
  742. $infoPath = pathinfo($fileName);
  743. // pathinfo('/path/t1/t2/fileName.ext') = [
  744. // [dirname] => /path/t1/t2
  745. // [basename] => fileName.ext
  746. // [extension] => ext
  747. // [filename] => fileName
  748. // ]
  749. return $infoPath['filename'] . "--" . date("Y-m-d_H-i-s") . "." . $infoPath['extension'];
  750. };
  751. $moveActions = array_map(function ($file) use ($destPath, $generateSafeFileName) {
  752. $safeName = $generateSafeFileName($destPath, $file['name']);
  753. return [
  754. $file['tmp_name'],
  755. "{$destPath}/{$safeName}",
  756. $safeName,
  757. ];
  758. }, $_FILES);
  759. DBG::log($moveActions, 'array', "\$moveActions"); // [ [ srcPath, descPath ] ]
  760. $errorMsgs = [];
  761. $pkField = $acl->getSqlPrimaryKeyField();
  762. foreach ($moveActions as $fileMoveAction) {
  763. if (!move_uploaded_file($fileMoveAction[0], $fileMoveAction[1])) {
  764. $errorMsgs[] = "Nie udało się wgrać pliku '{$fileMoveAction[2]}'";
  765. } else {
  766. try {
  767. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  768. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  769. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  770. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  771. ]);
  772. if ($affected) {
  773. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  774. 'ID_USERS2' => $primaryKey,
  775. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  776. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  777. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  778. ]);
  779. }
  780. } catch (Exception $e) {
  781. DBG::log($e);
  782. $errorMsgs[] = $e->getMessage();
  783. }
  784. }
  785. }
  786. if (!empty($errorMsgs)) {
  787. return [
  788. 'type' => "error",
  789. 'msg' => "Wystąpiły błędy podczas wgrywania plików dla '{$primaryKey}'",
  790. 'errors' => $errorMsgs,
  791. ];
  792. }
  793. return [
  794. 'type' => "success",
  795. 'msg' => "Wgrano nowe pliki dla '{$primaryKey}'",
  796. ];
  797. }
  798. public function removeFileAjaxAction() {
  799. Response::sendTryCatchJson([$this, 'removeFileAjax'], $args = $_REQUEST);
  800. }
  801. public function removeFileAjax($args) { // ajaxFileRemove
  802. $namespace = V::get('namespace', '', $args, 'word');
  803. if (!$namespace) throw new Exception("Missing namespace");
  804. $id = V::get('ID', 0, $args, 'int');
  805. if ($id <= 0) throw new Exception("Missing ID");
  806. $filename = V::get('filename', '', $args);
  807. if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
  808. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  809. $dbID = $acl->getDB();
  810. $db = DB::getPDO($dbID);
  811. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  812. $record = $acl->buildQuery([])->getItem($id);
  813. if (!$record) throw new HttpException("No item ID({$id})", 404);
  814. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  815. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  816. Lib::loadClass('FileUploader');
  817. Lib::loadClass('FoldersConfig');
  818. $tblName = $acl->getName();
  819. $confTblName = "{$tblName}_COLUMN";
  820. $folderConfAll = FoldersConfig::getRawData();
  821. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  822. $folderConf = FoldersConfig::getAll($confTblName);
  823. $uploader = new FileUploader($confTblName, (object)$record);
  824. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  825. $uploader->findFolder();
  826. $errorMsg = '';
  827. $removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
  828. if (!$removed) throw new Exception($errorMsg);
  829. // $affected = DB::getPDO($acl->getDB())->update();
  830. $rootTableName = $acl->getRootTableName();
  831. $pkField = $acl->getSqlPrimaryKeyField();
  832. $primaryKey = $id;
  833. try {
  834. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  835. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  836. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  837. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  838. ]);
  839. if ($affected) {
  840. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  841. 'ID_USERS2' => $primaryKey,
  842. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  843. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  844. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  845. ]);
  846. }
  847. } catch (Exception $e) {
  848. DBG::log($e);
  849. }
  850. return [
  851. 'type' => 'success',
  852. 'msg' => 'Plik został usunięty',
  853. ];
  854. }
  855. public function procesInitFiltrAjaxAction() {
  856. Response::sendTryCatchJson([$this, 'procesInitFiltrAjax'], $args = $_GET);
  857. }
  858. public function procesInitFiltrAjax($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. $pInitList = User::getAcl()->getTableProcesInitList($acl->getID());
  863. DBG::log($pInitList, 'array', "\$pInitList");
  864. if (!empty($pInitList)) {
  865. $procesIds = array_keys($pInitList);
  866. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  867. DBG::log($mapTree, 'array', "\$mapTree");
  868. DBG::log($pInitList, 'array', "\$pInitList");
  869. $pInitListSelected = User::getAcl()->getPermsFiltrProcesId();
  870. return [
  871. 'type' => 'success',
  872. 'msg' => 'ok',
  873. 'pInitData' => [
  874. 'pInitList' => $pInitList,
  875. 'mapTree' => $mapTree,
  876. 'pInitListSelected' => $pInitListSelected,
  877. ],
  878. ];
  879. }
  880. return [
  881. 'type' => 'success'
  882. ];
  883. }
  884. public function tableToolsAjaxAction() {
  885. Response::sendTryCatchJson([$this, 'tableToolsAjax'], $args = $_GET);
  886. }
  887. public function tableToolsAjax($args) { // ajaxFileRemove
  888. $namespace = V::get('namespace', '', $args, 'word');
  889. if (!$namespace) throw new Exception("Missing namespace");
  890. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  891. $listUrlFunctions = Route_UrlAction::getTableFunctions($acl->getID(), $idRecord = 0, $acl->getName(), User::getLogin());
  892. DBG::log($listUrlFunctions, 'array', "\$listUrlFunctions");
  893. $listUrlFunctions = array_map(function ($urlFunction) use ($namespace) {
  894. if ('index.php?' === substr($urlFunction['baseLink'], 0, strlen('index.php?'))) $urlFunction['baseLink'] .= "&_fromNamespace={$namespace}";
  895. return $urlFunction;
  896. }, $listUrlFunctions);
  897. return [
  898. 'type' => "success",
  899. 'msg' => 'ok',
  900. 'body' => [
  901. 'tableTools' => array_values(array_map(function ($urlFunction) {
  902. return [
  903. 'url' => $urlFunction['baseLink'],
  904. 'label' => $urlFunction['label'],
  905. // TODO: $urlFunction['link_target'] // "_blank"
  906. // ? $urlFunction['name']
  907. ];
  908. }, array_filter($listUrlFunctions, function ($urlFunction) {
  909. return empty($urlFunction['cell_id_params']);
  910. }))),
  911. ],
  912. ];
  913. }
  914. }