ViewTableAjax.php 42 KB

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