ViewTableAjax.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 addUserTableFilterAjaxAction() {
  170. Response::sendTryCatchJson(array($this, 'addUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  171. }
  172. public function addUserTableFilterAjax($args) {
  173. $namespace = V::get('namespace', '', $args);
  174. $filtrName = V::get('filtrName', '', $args);
  175. $visibleCols = V::get('visibleCols', '', $args);
  176. if (!$namespace) throw new Exception("Missing namespace");
  177. if (!$filtrName) throw new Exception("Missing filtrName");
  178. if (!$visibleCols) throw new Exception("Missing visibleCols");
  179. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  180. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  181. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  182. $currentFilters[$namespace][$filtrName] = $visibleCols;
  183. $sqlFltr = json_encode($currentFilters);
  184. DB::getPDO()->execSql("
  185. insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  186. values ('$userFltrConfKey', '{$sqlFltr}')
  187. on duplicate key update CONF_VAL = '{$sqlFltr}'
  188. ");
  189. return [
  190. 'type' => 'success',
  191. 'msg' => 'Zapisano nowy filtr',
  192. 'data' => $currentFilters[$namespace]
  193. ];
  194. }
  195. public function getUserTableFilterAjaxAction() {
  196. Response::sendTryCatchJson(array($this, 'getUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  197. }
  198. public function getUserTableFilterAjax($args) {
  199. $namespace = V::get('namespace', '', $args);
  200. if (!$namespace) throw new Exception("Missing namespace");
  201. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  202. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  203. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  204. return [
  205. 'type' => 'success',
  206. 'msg' => 'Odczytano filtry użytkownika',
  207. 'data' => (!empty($currentFilters[$namespace])) ? $currentFilters[$namespace] : []
  208. ];
  209. }
  210. public function revertFromHistAjaxAction() {
  211. Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
  212. }
  213. public function revertFromHistAjax() {
  214. $typeName = V::get('typeName', '', $_REQUEST, 'word');
  215. if (!$typeName) throw new Exception("Wrong param typeName");
  216. // TODO: use namespace from url
  217. // $namespace = V::get('namespace', '', $_GET, 'word');
  218. // if (!$namespace) {
  219. // $typeName = V::get('typeName', '', $_GET, 'word');
  220. // if (!$typeName) throw new Exception("Wrong param typeName");
  221. // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  222. // }
  223. // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  224. $id = V::get('ID', '', $_REQUEST, 'word');
  225. if (!$id) throw new Exception("Wrong param ID");
  226. $idHist = V::get('idHist', '', $_REQUEST, 'word');
  227. if (!$idHist) throw new Exception("Wrong param idHist");
  228. $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
  229. if (!$fieldName) throw new Exception("Wrong param fieldName");
  230. $acl = Core_AclHelper::getAclByTypeName($typeName);
  231. $item = $acl->getItem($id);
  232. if (!$item) throw new HttpException("Item not found", 404);
  233. if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
  234. $histItem = $acl->getHistItem($id, $idHist);
  235. if (!$histItem) throw new HttpException("Hist Item not found", 404);
  236. $histValue = V::get($fieldName, 'N/S;', $histItem);
  237. if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
  238. if ($acl->isGeomField($fieldName)) {
  239. $wktType = strtoupper($acl->getGeomFieldType($fieldName));
  240. if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
  241. if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
  242. $coords = trim(substr($histValue, strlen($wktType)), '()');
  243. $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
  244. if (!$wktValue) throw new Exception("BUG in hist record");
  245. $sqlObj = array();
  246. $sqlObj['ID'] = $id;
  247. $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
  248. $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
  249. if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
  250. else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
  251. $jsonResponse = array();
  252. $jsonResponse['type'] = 'success';
  253. $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
  254. $jsonResponse['actions'] = array();
  255. $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
  256. return $jsonResponse;
  257. } else {
  258. throw new HttpException("Not implemented - update from hist only for the geom field", 501);
  259. }
  260. throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
  261. }
  262. public function removeTheGeomAjaxAction() {
  263. Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  264. }
  265. public function removeTheGeomAjax($args) {
  266. $namespace = V::get('namespace', '', $args, 'word');
  267. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  268. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  269. $primaryKeyField = $acl->getPrimaryKeyField();
  270. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  271. $geomFieldName = 'the_geom';
  272. $response = new stdClass();
  273. if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
  274. $record = $acl->getItem($primaryKey);
  275. if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  276. if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  277. if (empty($record->{$geomFieldName})) {
  278. $response->type = 'info';
  279. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  280. $response->record = $record;
  281. return $response;
  282. }
  283. $itemPatch = array();
  284. $itemPatch[$geomFieldName] = "NULL";
  285. $itemPatch[$primaryKeyField] = $primaryKey;
  286. $response = new stdClass();
  287. try {
  288. $affected = $acl->updateItem($itemPatch);
  289. if ($affected > 0) {
  290. $response->type = 'success';
  291. $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
  292. } else if ($affected == 0) {
  293. $response->type = 'info';
  294. $response->msg = "Nie wprowadzono żadnych zmian";
  295. }
  296. $response->record = $acl->getItem($primaryKey);
  297. }
  298. catch (Exception $e) {
  299. $response->type = 'error';
  300. $response->msg = $e->getMessage();
  301. }
  302. return $response;
  303. }
  304. public function moreFunctionsCellAjaxAction() {
  305. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  306. }
  307. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  308. $id = V::get('ID', 0, $args, 'int');
  309. if ($id <= 0) throw new HttpException("404", 404);
  310. $namespace = V::get('namespace', '', $args, 'word');
  311. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  312. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  313. $response = new stdClass();
  314. $response->type = 'success';
  315. $response->msg = 'Funkcje';
  316. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  317. return $response;
  318. }
  319. public function editFormAction() {// namespace, _hash, _primaryKey
  320. $args = $_REQUEST;
  321. $id = V::get('_primaryKey', 0, $args, 'int');
  322. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  323. $namespace = V::get('namespace', '', $args, 'word');
  324. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  325. $acl = Core_AclHelper::getAclByNamespace($namespace);
  326. $tbl = $this->getTableAjaxWidget($acl);
  327. $tbl->sendAjaxEdit($id, $args);
  328. }
  329. public function editSaveAjaxAction() {
  330. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  331. }
  332. public function editSaveAjax($args) {
  333. $namespace = V::get('namespace', '', $args, 'word');
  334. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  335. $acl = Core_AclHelper::getAclByNamespace($namespace);
  336. $primaryKeyField = $acl->getPrimaryKeyField();
  337. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  338. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  339. $item = $acl->getItem($primaryKey);
  340. if (!$item) throw new HttpException("Item not exists!", 404);
  341. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  342. $response = new stdClass();
  343. $response->primaryKey = $primaryKey;
  344. try {
  345. $itemFromUser[$primaryKeyField] = $primaryKey;
  346. $affected = $acl->updateItem($itemFromUser);
  347. if ($affected > 0) {
  348. $response->type = 'success';
  349. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  350. } else if ($affected == 0) {
  351. $response->type = 'info';
  352. $response->msg = "Nie wprowadzono żadnych zmian";
  353. }
  354. $response->record = $acl->getItem($primaryKey);
  355. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  356. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  357. }
  358. catch (Exception $e) {
  359. $response->type = 'error';
  360. $response->msg = "Wystąpiły błędy!";
  361. $response->msg .= $e->getMessage();
  362. }
  363. return $response;
  364. }
  365. public function typeSpecialCellAction() {
  366. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  367. }
  368. public function typeSpecialCell($args) {
  369. $namespace = V::get('namespace', '', $args, 'word');
  370. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  371. $acl = Core_AclHelper::getAclByNamespace($namespace);
  372. $id = V::get('ID', 0, $args, 'int');
  373. $fieldName = V::get('col', '', $args);
  374. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  375. $col = $fieldName;// TODO: RM $col
  376. $jsonData = new stdClass();
  377. $idField = $acl->getFieldIdByName($fieldName);
  378. if (!$idField) throw new Exception("Wrong field");
  379. $item = $acl->getItem($id);
  380. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  381. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  382. if ($typeSpecial) {
  383. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  384. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  385. }
  386. return $jsonData;
  387. }
  388. /**
  389. * @param $_GET['namespace'] = AclNamespace
  390. * @param $_GET['format'] = 'csv' | 'html'
  391. * @param $_GET['flds'] = csv - coma separated field names
  392. * @param $_GET['sortCol'] = FieldName
  393. * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
  394. * @param $_GET['f_{$fieldName}'] = filter
  395. * @param $_GET['sf_{$fieldName}'] = force filter
  396. */
  397. public function exportAction() {
  398. $args = $_GET;
  399. $namespace = V::get('namespace', '', $args, 'word');
  400. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  401. $acl = Core_AclHelper::getAclByNamespace($namespace);
  402. $exportLimit = 10000;
  403. $params = array();
  404. $params['limit'] = $exportLimit;
  405. // $params['limitstart'] = 0;
  406. $params['order_by'] = V::get('sortCol', '', $args);
  407. $params['order_dir'] = V::get('sortDir', '', $args);
  408. $params['cols'] = array($acl->getPrimaryKeyField());
  409. $toExportFields = explode(',', V::get('flds', '', $_GET));
  410. if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
  411. $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
  412. foreach ($toExportFields as $fieldName) {
  413. if ($fieldName == $acl->getPrimaryKeyField()) continue;
  414. if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
  415. $params['cols'][] = $fieldName;
  416. }
  417. $labels = array();
  418. foreach ($toExportFields as $fieldName) {
  419. $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
  420. }
  421. foreach ($args as $k => $v) {
  422. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  423. $params[$k] = $v;
  424. }
  425. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  426. $params[$k] = $v;
  427. }
  428. }
  429. $total = $acl->getTotal($params);
  430. // if ($total > $exportLimit) $params['limit'] = $exportLimit;
  431. $items = $acl->getItems($params);
  432. $format = V::get('format', 'html', $_GET);
  433. if ('html' == $format) {
  434. UI::gora();
  435. UI::startTag('table', ['class'=>'table table-bordered table-hover']);
  436. UI::startTag('thead');
  437. UI::startTag('tr');
  438. foreach ($labels as $fldName => $label) {
  439. UI::tag('th', [], $label);
  440. }
  441. UI::endTag('tr');
  442. UI::endTag('thead');
  443. UI::startTag('tbody');
  444. foreach ($items as $item) :
  445. UI::startTag('tr');
  446. foreach ($labels as $fldName => $label) :
  447. UI::tag('td', [], $item->{$fldName});
  448. endforeach;
  449. UI::endTag('tr');
  450. endforeach;
  451. UI::endTag('tbody');
  452. UI::endTag('table');
  453. UI::dol();
  454. }
  455. else if ('csv' == $format) {
  456. $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
  457. header('Content-Type: text/csv; charset=utf-8');
  458. header("Content-Disposition: attachment; filename={$csvFileName}.csv");
  459. $csvSeparator = ';';
  460. $labelsLine = array();
  461. foreach ($labels as $fldName => $label) {
  462. $labelsLine[] = '"' . addslashes($label) . '"';
  463. }
  464. echo implode($csvSeparator, $labelsLine) . "\n";
  465. foreach ($items as $item) {
  466. $itemLine = array();
  467. foreach ($labels as $fldName => $label) {
  468. $itemLine[] = '"' . addslashes($item->{$fldName}) . '"';
  469. }
  470. echo implode($csvSeparator, $itemLine) . "\n";
  471. }
  472. }
  473. else {
  474. die("Nieobsługiwany format danych.");
  475. }
  476. }
  477. public function loadDataAjaxAction() {
  478. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  479. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  480. $acl = Core_AclHelper::getAclByNamespace($namespace);
  481. $tbl = $this->getTableAjaxWidget($acl);
  482. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  483. }
  484. }