ViewTableAjax.php 22 KB

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