ViewTableAjax.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. $dbgExecTime->log('before sql');
  77. $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
  78. $dbgExecTime->log('after sql', ['sql']);
  79. UI::table(['caption' => "from CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW", 'rows' => $aclTableRows]);
  80. $csvIdProces = array();
  81. foreach ($aclTableRows as $row) {
  82. if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
  83. }
  84. $csvIdProces = implode(",", $csvIdProces);
  85. UI::tag('p', null, "DBG csvIdProces({$csvIdProces})");
  86. if (!empty($csvIdProces)) {
  87. $userLogin = User::getLogin();
  88. $dbgExecTime->log('before sql');
  89. $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");
  90. $dbgExecTime->log('after sql', ['sql']);
  91. UI::table(['caption' => "from CRM_PROCES_idx_USER_to_PROCES_VIEW", 'rows' => $rows]);
  92. $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
  93. $userTablePerms = array();
  94. foreach ($aclTableRows as $row) {
  95. if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
  96. if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
  97. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
  98. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
  99. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
  100. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
  101. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
  102. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
  103. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
  104. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
  105. } else {
  106. $userTablePerms[ $row['CELL_NAME'] ] = $row;
  107. unset($userTablePerms[ $row['CELL_NAME'] ][ 'TABLE_DESCRIPTION' ]);
  108. unset($userTablePerms[ $row['CELL_NAME'] ][ 'ID_PROCES' ]);
  109. unset($userTablePerms[ $row['CELL_NAME'] ][ 'FORM_TREAT' ]);
  110. }
  111. }
  112. UI::table(['caption' => "\$userTablePerms", 'rows' => $userTablePerms]);
  113. } else UI::alert('warning', "brak \$csvIdProces");
  114. $dbgExecTime->printDebug();
  115. UI::endContainer();
  116. }
  117. } catch (Exception $e) {
  118. UI::startContainer();
  119. UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
  120. UI::endContainer();
  121. }
  122. UI::dol();
  123. }
  124. public function revertFromHistAjaxAction() {
  125. Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
  126. }
  127. public function revertFromHistAjax() {
  128. $typeName = V::get('typeName', '', $_REQUEST, 'word');
  129. if (!$typeName) throw new Exception("Wrong param typeName");
  130. // TODO: use namespace from url
  131. // $namespace = V::get('namespace', '', $_GET, 'word');
  132. // if (!$namespace) {
  133. // $typeName = V::get('typeName', '', $_GET, 'word');
  134. // if (!$typeName) throw new Exception("Wrong param typeName");
  135. // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  136. // }
  137. // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  138. $id = V::get('ID', '', $_REQUEST, 'word');
  139. if (!$id) throw new Exception("Wrong param ID");
  140. $idHist = V::get('idHist', '', $_REQUEST, 'word');
  141. if (!$idHist) throw new Exception("Wrong param idHist");
  142. $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
  143. if (!$fieldName) throw new Exception("Wrong param fieldName");
  144. $acl = $this->getAclFromTypeName($typeName);
  145. $item = $acl->getItem($id);
  146. if (!$item) throw new HttpException("Item not found", 404);
  147. if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
  148. $histItem = $acl->getHistItem($id, $idHist);
  149. if (!$histItem) throw new HttpException("Hist Item not found", 404);
  150. $histValue = V::get($fieldName, 'N/S;', $histItem);
  151. if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
  152. if ($acl->isGeomField($fieldName)) {
  153. $wktType = strtoupper($acl->getGeomFieldType($fieldName));
  154. if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
  155. if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
  156. $coords = trim(substr($histValue, strlen($wktType)), '()');
  157. $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
  158. if (!$wktValue) throw new Exception("BUG in hist record");
  159. $sqlObj = array();
  160. $sqlObj['ID'] = $id;
  161. $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
  162. $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
  163. if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
  164. else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
  165. $jsonResponse = array();
  166. $jsonResponse['type'] = 'success';
  167. $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
  168. $jsonResponse['actions'] = array();
  169. $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
  170. return $jsonResponse;
  171. } else {
  172. throw new HttpException("Not implemented - update from hist only for the geom field", 501);
  173. }
  174. throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
  175. }
  176. public function removeTheGeomAjaxAction() {
  177. Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  178. }
  179. public function removeTheGeomAjax($args) {
  180. $namespace = V::get('namespace', '', $args, 'word');
  181. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  182. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  183. $primaryKeyField = $acl->getPrimaryKeyField();
  184. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  185. $geomFieldName = 'the_geom';
  186. $response = new stdClass();
  187. if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
  188. $record = $acl->getItem($primaryKey);
  189. if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  190. if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  191. if (empty($record->{$geomFieldName})) {
  192. $response->type = 'info';
  193. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  194. $response->record = $record;
  195. return $response;
  196. }
  197. $itemPatch = array();
  198. $itemPatch[$geomFieldName] = "NULL";
  199. $itemPatch[$primaryKeyField] = $primaryKey;
  200. $response = new stdClass();
  201. try {
  202. $affected = $acl->updateItem($itemPatch);
  203. if ($affected > 0) {
  204. $response->type = 'success';
  205. $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
  206. } else if ($affected == 0) {
  207. $response->type = 'info';
  208. $response->msg = "Nie wprowadzono żadnych zmian";
  209. }
  210. $response->record = $acl->getItem($primaryKey);
  211. }
  212. catch (Exception $e) {
  213. $response->type = 'error';
  214. $response->msg = $e->getMessage();
  215. }
  216. return $response;
  217. }
  218. public function moreFunctionsCellAjaxAction() {
  219. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  220. }
  221. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  222. $id = V::get('ID', 0, $args, 'int');
  223. if ($id <= 0) throw new HttpException("404", 404);
  224. $namespace = V::get('namespace', '', $args, 'word');
  225. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  226. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  227. $response = new stdClass();
  228. $response->type = 'success';
  229. $response->msg = 'Funkcje';
  230. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  231. return $response;
  232. }
  233. public function editFormAction() {// namespace, _hash, _primaryKey
  234. $args = $_REQUEST;
  235. $id = V::get('_primaryKey', 0, $args, 'int');
  236. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  237. $namespace = V::get('namespace', '', $args, 'word');
  238. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  239. $acl = Core_AclHelper::getAclByNamespace($namespace);
  240. $tbl = $this->getTableAjaxWidget($acl);
  241. $tbl->sendAjaxEdit($id, $args);
  242. }
  243. public function editSaveAjaxAction() {
  244. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  245. }
  246. public function editSaveAjax($args) {
  247. $namespace = V::get('namespace', '', $args, 'word');
  248. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  249. $acl = Core_AclHelper::getAclByNamespace($namespace);
  250. $primaryKeyField = $acl->getPrimaryKeyField();
  251. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  252. if (empty($primaryKey)) throw new HttpException("Wrong param id!", 400);
  253. $item = $acl->getItem($primaryKey);
  254. if (!$item) throw new HttpException("Item not exists!", 404);
  255. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  256. $response = new stdClass();
  257. $response->primaryKey = $primaryKey;
  258. try {
  259. $itemFromUser[$primaryKeyField] = $primaryKey;
  260. $affected = $acl->updateItem($itemFromUser);
  261. if ($affected > 0) {
  262. $response->type = 'success';
  263. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  264. } else if ($affected == 0) {
  265. $response->type = 'info';
  266. $response->msg = "Nie wprowadzono żadnych zmian";
  267. }
  268. $response->record = $acl->getItem($primaryKey);
  269. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  270. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  271. }
  272. catch (Exception $e) {
  273. $response->type = 'error';
  274. $response->msg = "Wystąpiły błędy!";
  275. $response->msg .= $e->getMessage();
  276. }
  277. return $response;
  278. }
  279. public function loadDataAjaxAction() {
  280. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  281. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  282. $acl = Core_AclHelper::getAclByNamespace($namespace);
  283. $tbl = $this->getTableAjaxWidget($acl);
  284. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  285. }
  286. /**
  287. * @param string $typeName - 'p5_default_db:TEST_PERMS'
  288. */
  289. public function getAclFromTypeName($typeName, $forceTblAclInit) {
  290. $userAcl = User::getAcl();
  291. $userAcl->fetchGroups();
  292. $typeEx = explode(':', $typeName);
  293. if (2 != count($typeEx)) throw new Exception("Could not get acl for '{$typeName}' - syntax error");
  294. if ('p5_' != substr($typeEx[0], 0, 3)) throw new Exception("Could not get acl for '{$typeName}' - prefix error");
  295. $sourceName = substr($typeEx[0], 3);
  296. $objName = $typeEx[1];
  297. $acl = $userAcl->getObjectAcl($sourceName, $objName);
  298. if (!$acl) throw new Exception("Could not get acl for '{$typeName}'");
  299. $acl->init($forceTblAclInit);
  300. return $acl;
  301. }
  302. }