ViewTableAjax.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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) {
  16. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  17. $tbl = new TableAjax($acl);
  18. $tblLabel = $acl->getNamespace();
  19. if ('default_db' == $acl->getSourceName()) {
  20. $tblLabel = array();
  21. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  22. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  23. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  24. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  25. $tblLabel = implode(" - ", $tblLabel);
  26. }
  27. $tbl->setSyncUrl($syncUrl);
  28. $tbl->showUserTableFilter($this->getLink("getUserTableFilterAjax"));
  29. $tbl->setLabel($tblLabel);
  30. $tbl->addRowFunction('edit');
  31. $tbl->addRowFunction('hist');
  32. $tbl->addRowFunction('files');
  33. $tbl->addRowFunction('cp');
  34. $tbl->addRowFunction('msgs');
  35. return $tbl;
  36. }
  37. public function defaultAction() {
  38. UI::gora();
  39. UI::menu();
  40. try {
  41. $namespace = V::get('namespace', '', $_GET, 'word');
  42. if (!$namespace) {
  43. $typeName = V::get('typeName', '', $_GET, 'word');
  44. if (!$typeName) throw new Exception("Wrong param typeName");
  45. $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  46. }
  47. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  48. $forceFilterInit = array();
  49. $filterInit = new stdClass();
  50. $filterInit->currSortCol = $acl->getPrimaryKeyField();
  51. $filterInit->currSortFlip = 'desc';
  52. foreach ($_GET as $k => $v) {
  53. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
  54. $filterInit->$k = $v;
  55. }
  56. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
  57. $filterInit->$k = $v;
  58. }
  59. else if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  60. $fldName = substr($k, 3);
  61. $forceFilterInit[$fldName] = $v;
  62. }
  63. }
  64. $tbl = $this->getTableAjaxWidget($acl);
  65. $tbl->setFilterInit($filterInit);
  66. if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
  67. echo $tbl->render();
  68. if (DBG::isActive() && V::get('DBG_ACL', '', $_GET)) {// test load perms
  69. Lib::loadClass('DebugExecutionTime');
  70. $dbgExecTime = new DebugExecutionTime();
  71. $dbgExecTime->activate();
  72. $dbgExecTime->log('start');
  73. UI::startContainer(['style'=>'border:1px solid red']);
  74. UI::tag('p', null, "TEST - load perms from db");
  75. $idTable = $acl->getID();
  76. UI::tag('p', null, "DBG idTable({$idTable})");
  77. if ($idTable > 0) {
  78. $dbgExecTime->log('before sql');
  79. $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
  80. $dbgExecTime->log('after sql', ['sql']);
  81. UI::table(['caption' => "from CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW", 'rows' => $aclTableRows]);
  82. $csvIdProces = array();
  83. foreach ($aclTableRows as $row) {
  84. if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
  85. }
  86. }
  87. $tableName = $acl->getName();
  88. $databaseName = DB::getPDO()->getDatabaseName();
  89. UI::table([
  90. 'caption' => "Cell to process",
  91. 'rows' => array_map(
  92. function ($row) use ($aclTableRows, $idTable) {
  93. $row['proces'] = array();
  94. $row['id_zasob'] = 0;
  95. $row['PERM_R'] = 0;
  96. $row['PERM_W'] = 0;
  97. $row['PERM_X'] = 0;
  98. $row['PERM_C'] = 0;
  99. $row['PERM_S'] = 0;
  100. $row['PERM_O'] = 0;
  101. $row['PERM_V'] = 0;
  102. $row['PERM_E'] = 0;
  103. foreach ($aclTableRows as $aclInfo) {
  104. if (strtolower($aclInfo['CELL_NAME']) == strtolower($row['COLUMN_NAME'])) {
  105. $row['proces'][] = $aclInfo['ID_PROCES'];
  106. $row['id_zasob'] = $aclInfo['ID_CELL'];
  107. $row['PERM_R'] += $aclInfo['PERM_R'];
  108. $row['PERM_W'] += $aclInfo['PERM_W'];
  109. $row['PERM_X'] += $aclInfo['PERM_X'];
  110. $row['PERM_C'] += $aclInfo['PERM_C'];
  111. $row['PERM_S'] += $aclInfo['PERM_S'];
  112. $row['PERM_O'] += $aclInfo['PERM_O'];
  113. $row['PERM_V'] += $aclInfo['PERM_V'];
  114. $row['PERM_E'] += $aclInfo['PERM_E'];
  115. }
  116. }
  117. $row['proces'] = (empty($row['proces']))
  118. ? "<i style=\"color:red\">Brak</i>"
  119. : implode(", ", $row['proces']);
  120. 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");
  121. return $row;
  122. }, DB::getPDO()->fetchAll("
  123. select t.TABLE_NAME, t.COLUMN_NAME, t.DATA_TYPE, t.COLUMN_TYPE
  124. from `information_schema`.`COLUMNS` t
  125. where t.TABLE_SCHEMA = '{$databaseName}'
  126. and t.TABLE_NAME like '{$tableName}'
  127. ")
  128. )
  129. ]);
  130. if (!empty($csvIdProces)) {
  131. $csvIdProces = implode(",", $csvIdProces);
  132. UI::tag('p', null, "DBG csvIdProces({$csvIdProces})");
  133. $userLogin = User::getLogin();
  134. $dbgExecTime->log('before sql');
  135. $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");
  136. $dbgExecTime->log('after sql', ['sql']);
  137. UI::table(['caption' => "from CRM_PROCES_idx_USER_to_PROCES_VIEW", 'rows' => $rows]);
  138. $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
  139. $userTablePerms = array();
  140. foreach ($aclTableRows as $row) {
  141. if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
  142. if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
  143. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
  144. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
  145. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
  146. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
  147. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
  148. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
  149. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
  150. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
  151. } else {
  152. $userTablePerms[ $row['CELL_NAME'] ] = $row;
  153. unset($userTablePerms[ $row['CELL_NAME'] ][ 'TABLE_DESCRIPTION' ]);
  154. unset($userTablePerms[ $row['CELL_NAME'] ][ 'ID_PROCES' ]);
  155. unset($userTablePerms[ $row['CELL_NAME'] ][ 'FORM_TREAT' ]);
  156. }
  157. }
  158. UI::table(['caption' => "\$userTablePerms", 'rows' => $userTablePerms]);
  159. } else UI::alert('warning', "brak \$csvIdProces");
  160. $dbgExecTime->printDebug();
  161. UI::endContainer();
  162. }
  163. } catch (Exception $e) {
  164. UI::startContainer();
  165. UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
  166. UI::endContainer();
  167. DBG::log($e);
  168. }
  169. UI::dol();
  170. }
  171. public function rmUserTableFilterAjaxAction() {
  172. Response::sendTryCatchJson(array($this, 'rmUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  173. }
  174. public function rmUserTableFilterAjax($args) {
  175. $namespace = V::get('namespace', '', $args);
  176. $filtrName = V::get('filtrName', '', $args);
  177. if (!$namespace) throw new Exception("Missing namespace");
  178. if (!$filtrName) throw new Exception("Missing filtrName");
  179. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  180. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  181. if (!$currentFilters) return [
  182. 'type' => 'warning',
  183. 'msg' => "Brak filtrów w bazie",
  184. ];
  185. $currentFilters = json_decode($currentFilters, 'assoc');
  186. unset($currentFilters[$namespace][$filtrName]);
  187. $affeced = DB::getPDO()->update('CRM_CONFIG', 'CONF_KEY', $userFltrConfKey, [
  188. 'CONF_VAL' => json_encode($currentFilters)
  189. ]);
  190. return [
  191. 'type' => 'success',
  192. 'msg' => 'Zapisano nowy filtr',
  193. 'data' => $currentFilters[$namespace]
  194. ];
  195. }
  196. public function addUserTableFilterAjaxAction() {
  197. Response::sendTryCatchJson(array($this, 'addUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  198. }
  199. public function addUserTableFilterAjax($args) {
  200. $namespace = V::get('namespace', '', $args);
  201. $filtrName = V::get('filtrName', '', $args);
  202. $visibleCols = V::get('visibleCols', '', $args);
  203. if (!$namespace) throw new Exception("Missing namespace");
  204. if (!$filtrName) throw new Exception("Missing filtrName");
  205. if (!$visibleCols) throw new Exception("Missing visibleCols");
  206. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  207. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  208. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  209. $currentFilters[$namespace][$filtrName] = $visibleCols;
  210. $sqlFltr = json_encode($currentFilters);
  211. DB::getPDO()->execSql("
  212. insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  213. values ('$userFltrConfKey', '{$sqlFltr}')
  214. on duplicate key update CONF_VAL = '{$sqlFltr}'
  215. ");
  216. return [
  217. 'type' => 'success',
  218. 'msg' => 'Zapisano nowy filtr',
  219. 'data' => $currentFilters[$namespace]
  220. ];
  221. }
  222. public function getUserTableFilterAjaxAction() {
  223. Response::sendTryCatchJson(array($this, 'getUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  224. }
  225. public function getUserTableFilterAjax($args) {
  226. $namespace = V::get('namespace', '', $args);
  227. if (!$namespace) throw new Exception("Missing namespace");
  228. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  229. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  230. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  231. return [
  232. 'type' => 'success',
  233. 'msg' => 'Odczytano filtry użytkownika',
  234. 'data' => (!empty($currentFilters[$namespace])) ? $currentFilters[$namespace] : []
  235. ];
  236. }
  237. public function revertFromHistAjaxAction() {
  238. Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
  239. }
  240. public function revertFromHistAjax() {
  241. $typeName = V::get('typeName', '', $_REQUEST, 'word');
  242. if (!$typeName) throw new Exception("Wrong param typeName");
  243. // TODO: use namespace from url
  244. // $namespace = V::get('namespace', '', $_GET, 'word');
  245. // if (!$namespace) {
  246. // $typeName = V::get('typeName', '', $_GET, 'word');
  247. // if (!$typeName) throw new Exception("Wrong param typeName");
  248. // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  249. // }
  250. // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  251. $id = V::get('ID', '', $_REQUEST, 'word');
  252. if (!$id) throw new Exception("Wrong param ID");
  253. $idHist = V::get('idHist', '', $_REQUEST, 'word');
  254. if (!$idHist) throw new Exception("Wrong param idHist");
  255. $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
  256. if (!$fieldName) throw new Exception("Wrong param fieldName");
  257. $acl = Core_AclHelper::getAclByTypeName($typeName);
  258. $item = $acl->getItem($id);
  259. if (!$item) throw new HttpException("Item not found", 404);
  260. if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
  261. $histItem = $acl->getHistItem($id, $idHist);
  262. if (!$histItem) throw new HttpException("Hist Item not found", 404);
  263. $histValue = V::get($fieldName, 'N/S;', $histItem);
  264. if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
  265. if ($acl->isGeomField($fieldName)) {
  266. $wktType = strtoupper($acl->getGeomFieldType($fieldName));
  267. if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
  268. if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
  269. $coords = trim(substr($histValue, strlen($wktType)), '()');
  270. $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
  271. if (!$wktValue) throw new Exception("BUG in hist record");
  272. $sqlObj = array();
  273. $sqlObj['ID'] = $id;
  274. $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
  275. $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
  276. if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
  277. else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
  278. $jsonResponse = array();
  279. $jsonResponse['type'] = 'success';
  280. $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
  281. $jsonResponse['actions'] = array();
  282. $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
  283. return $jsonResponse;
  284. } else {
  285. throw new HttpException("Not implemented - update from hist only for the geom field", 501);
  286. }
  287. throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
  288. }
  289. public function removeTheGeomAjaxAction() {
  290. Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  291. }
  292. public function removeTheGeomAjax($args) {
  293. $namespace = V::get('namespace', '', $args, 'word');
  294. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  295. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  296. $primaryKeyField = $acl->getPrimaryKeyField();
  297. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  298. $geomFieldName = 'the_geom';
  299. $response = new stdClass();
  300. if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
  301. $record = $acl->getItem($primaryKey);
  302. if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  303. if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  304. if (empty($record->{$geomFieldName})) {
  305. $response->type = 'info';
  306. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  307. $response->record = $record;
  308. return $response;
  309. }
  310. $itemPatch = array();
  311. $itemPatch[$geomFieldName] = "NULL";
  312. $itemPatch[$primaryKeyField] = $primaryKey;
  313. $response = new stdClass();
  314. try {
  315. $affected = $acl->updateItem($itemPatch);
  316. if ($affected > 0) {
  317. $response->type = 'success';
  318. $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
  319. } else if ($affected == 0) {
  320. $response->type = 'info';
  321. $response->msg = "Nie wprowadzono żadnych zmian";
  322. }
  323. $response->record = $acl->getItem($primaryKey);
  324. }
  325. catch (Exception $e) {
  326. $response->type = 'error';
  327. $response->msg = $e->getMessage();
  328. }
  329. return $response;
  330. }
  331. public function moreFunctionsCellAjaxAction() {
  332. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  333. }
  334. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  335. $id = V::get('ID', 0, $args, 'int');
  336. if ($id <= 0) throw new HttpException("404", 404);
  337. $namespace = V::get('namespace', '', $args, 'word');
  338. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  339. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  340. $response = new stdClass();
  341. $response->type = 'success';
  342. $response->msg = 'Funkcje';
  343. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  344. return $response;
  345. }
  346. public function editFormAction() {// namespace, _hash, _primaryKey
  347. $args = $_REQUEST;
  348. $id = V::get('_primaryKey', 0, $args, 'int');
  349. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  350. $namespace = V::get('namespace', '', $args, 'word');
  351. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  352. $acl = Core_AclHelper::getAclByNamespace($namespace);
  353. $tbl = $this->getTableAjaxWidget($acl);
  354. $tbl->sendAjaxEdit($id, $args);
  355. }
  356. public function editSaveAjaxAction() {
  357. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  358. }
  359. public function editSaveAjax($args) {
  360. $namespace = V::get('namespace', '', $args, 'word');
  361. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  362. $acl = Core_AclHelper::getAclByNamespace($namespace);
  363. $primaryKeyField = $acl->getPrimaryKeyField();
  364. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  365. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  366. $item = $acl->getItem($primaryKey);
  367. if (!$item) throw new HttpException("Item not exists!", 404);
  368. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  369. $response = new stdClass();
  370. $response->primaryKey = $primaryKey;
  371. try {
  372. $itemFromUser[$primaryKeyField] = $primaryKey;
  373. $affected = $acl->updateItem($itemFromUser);
  374. if ($affected > 0) {
  375. $response->type = 'success';
  376. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  377. } else if ($affected == 0) {
  378. $response->type = 'info';
  379. $response->msg = "Nie wprowadzono żadnych zmian";
  380. }
  381. $response->record = $acl->getItem($primaryKey);
  382. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  383. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  384. }
  385. catch (Exception $e) {
  386. $response->type = 'error';
  387. $response->msg = "Wystąpiły błędy!";
  388. $response->msg .= $e->getMessage();
  389. }
  390. return $response;
  391. }
  392. public function typeSpecialCellAction() {
  393. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  394. }
  395. public function typeSpecialCell($args) {
  396. $namespace = V::get('namespace', '', $args, 'word');
  397. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  398. $acl = Core_AclHelper::getAclByNamespace($namespace);
  399. $id = V::get('ID', 0, $args, 'int');
  400. $fieldName = V::get('col', '', $args);
  401. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  402. $col = $fieldName;// TODO: RM $col
  403. $jsonData = new stdClass();
  404. $idField = $acl->getFieldIdByName($fieldName);
  405. if (!$idField) throw new Exception("Wrong field");
  406. $item = $acl->getItem($id);
  407. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  408. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  409. if ($typeSpecial) {
  410. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  411. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  412. }
  413. return $jsonData;
  414. }
  415. /**
  416. * @param $_GET['namespace'] = AclNamespace
  417. * @param $_GET['format'] = 'csv' | 'html'
  418. * @param $_GET['flds'] = csv - coma separated field names
  419. * @param $_GET['sortCol'] = FieldName
  420. * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
  421. * @param $_GET['f_{$fieldName}'] = filter
  422. * @param $_GET['sf_{$fieldName}'] = force filter
  423. */
  424. public function exportAction() {
  425. $args = $_GET;
  426. $namespace = V::get('namespace', '', $args, 'word');
  427. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  428. $acl = Core_AclHelper::getAclByNamespace($namespace);
  429. $exportLimit = 10000;
  430. $params = array();
  431. $params['limit'] = $exportLimit;
  432. // $params['limitstart'] = 0;
  433. $params['order_by'] = V::get('sortCol', '', $args);
  434. $params['order_dir'] = V::get('sortDir', '', $args);
  435. $params['cols'] = array($acl->getPrimaryKeyField());
  436. $toExportFields = explode(',', V::get('flds', '', $_GET));
  437. if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
  438. $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
  439. foreach ($toExportFields as $fieldName) {
  440. if ($fieldName == $acl->getPrimaryKeyField()) continue;
  441. if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
  442. $params['cols'][] = $fieldName;
  443. }
  444. $labels = array();
  445. foreach ($toExportFields as $fieldName) {
  446. $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
  447. }
  448. foreach ($args as $k => $v) {
  449. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  450. $params[$k] = $v;
  451. }
  452. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  453. $params[$k] = $v;
  454. }
  455. }
  456. $total = $acl->getTotal($params);
  457. // if ($total > $exportLimit) $params['limit'] = $exportLimit;
  458. $items = $acl->getItems($params);
  459. $format = V::get('format', 'html', $_GET);
  460. switch ($format) {
  461. case 'html': {
  462. UI::gora();
  463. echo UI::h('table', ['class'=>'table table-bordered table-hover'], [
  464. UI::h('thead', [], [
  465. UI::h('tr', [], array_map(function ($label) {
  466. return UI::h('th', [], $label);
  467. }, $labels))
  468. ]),
  469. UI::h('tbody', [], array_map(function ($item) use($labels) {
  470. return UI::h('tr', [], array_map(function ($fieldName) use ($item) {
  471. return UI::h('td', [], V::get($fieldName, '', $item));
  472. }, array_keys($labels)));
  473. }, $items)),
  474. ]);
  475. UI::dol();
  476. exit;
  477. }
  478. case 'csv_cp1250':
  479. case 'csv': {
  480. $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
  481. header('Content-Type: text/csv; charset=utf-8');
  482. header("Content-Disposition: attachment; filename={$csvFileName}.csv");
  483. $csvSeparator = ';';
  484. $csvHeader = implode($csvSeparator, array_map(function ($label) use ($item) {
  485. return '"' . addslashes($label) . '"';
  486. }, array_values($labels)));
  487. $csvRows = implode("\r\n", array_map(function ($item) use ($labels, $csvSeparator) {
  488. return implode($csvSeparator, array_map(function ($fieldName) use ($item) {
  489. return '"' . addslashes(V::get($fieldName, '', $item)) . '"';
  490. }, array_keys($labels)));
  491. }, $items));
  492. switch ($format) {
  493. case 'csv': echo $csvHeader . "\n" . $csvRows; exit;
  494. case 'csv_cp1250': echo iconv('utf-8', 'Windows-1250//IGNORE', $csvHeader) . "\r\n" . iconv('utf-8', 'Windows-1250//IGNORE', $csvRows); exit;
  495. die("Nieobsługiwane kodowanie danych csv.");
  496. }
  497. exit;
  498. }
  499. }
  500. die("Nieobsługiwany format danych.");
  501. }
  502. public function loadDataAjaxAction() {
  503. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  504. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  505. $acl = Core_AclHelper::getAclByNamespace($namespace);
  506. $tbl = $this->getTableAjaxWidget($acl);
  507. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  508. }
  509. }