ViewTableAjax.php 22 KB

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