ViewTableAjax.php 41 KB

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