ViewTableAjax.php 49 KB

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