ViewTableAjax.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. class Route_ViewTableAjax extends RouteBase {
  13. public function defaultAction() {
  14. UI::gora();
  15. UI::menu();
  16. try {
  17. $namespace = V::get('namespace', '', $_GET, 'word');
  18. if (!$namespace) {
  19. $typeName = V::get('typeName', '', $_GET, 'word');
  20. if (!$typeName) throw new Exception("Wrong param typeName");
  21. $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  22. }
  23. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  24. $forceFilterInit = array();
  25. $filterInit = new stdClass();
  26. $filterInit->currSortCol = 'ID';
  27. $filterInit->currSortFlip = 'desc';
  28. foreach ($_GET as $k => $v) {
  29. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
  30. $filterInit->$k = $v;
  31. }
  32. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
  33. $filterInit->$k = $v;
  34. }
  35. else if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  36. $fldName = substr($k, 3);
  37. $forceFilterInit[$fldName] = $v;
  38. }
  39. }
  40. $tbl = new TableAjax($acl);
  41. $tblLabel = $typeName;
  42. if ('default_db' == $acl->getSourceName()) {
  43. $tblLabel = array();
  44. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  45. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  46. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  47. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  48. $tblLabel = implode(" - ", $tblLabel);
  49. }
  50. if (DBG::isActive() && V::get('DBG_ACL', '', $_GET)) {// test load perms
  51. Lib::loadClass('DebugExecutionTime');
  52. $dbgExecTime = new DebugExecutionTime();
  53. $dbgExecTime->activate();
  54. $dbgExecTime->log('start');
  55. UI::startContainer(['style'=>'border:1px solid red']);
  56. UI::tag('p', null, "TEST - load perms from db");
  57. $idTable = $acl->getID();
  58. UI::tag('p', null, "DBG idTable({$idTable})");
  59. $dbgExecTime->log('before sql');
  60. $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
  61. $dbgExecTime->log('after sql', ['sql']);
  62. UI::table(['caption' => "from CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW", 'rows' => $aclTableRows]);
  63. $csvIdProces = array();
  64. foreach ($aclTableRows as $row) {
  65. if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
  66. }
  67. $csvIdProces = implode(",", $csvIdProces);
  68. UI::tag('p', null, "DBG csvIdProces({$csvIdProces})");
  69. if (!empty($csvIdProces)) {
  70. $userLogin = User::getLogin();
  71. $dbgExecTime->log('before sql');
  72. $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");
  73. $dbgExecTime->log('after sql', ['sql']);
  74. UI::table(['caption' => "from CRM_PROCES_idx_USER_to_PROCES_VIEW", 'rows' => $rows]);
  75. $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
  76. $userTablePerms = array();
  77. foreach ($aclTableRows as $row) {
  78. if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
  79. if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
  80. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
  81. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
  82. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
  83. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
  84. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
  85. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
  86. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
  87. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
  88. } else {
  89. $userTablePerms[ $row['CELL_NAME'] ] = $row;
  90. unset($userTablePerms[ $row['CELL_NAME'] ][ 'TABLE_DESCRIPTION' ]);
  91. unset($userTablePerms[ $row['CELL_NAME'] ][ 'ID_PROCES' ]);
  92. unset($userTablePerms[ $row['CELL_NAME'] ][ 'FORM_TREAT' ]);
  93. }
  94. }
  95. UI::table(['caption' => "\$userTablePerms", 'rows' => $userTablePerms]);
  96. } else UI::alert('warning', "brak \$csvIdProces");
  97. $dbgExecTime->printDebug();
  98. UI::endContainer();
  99. }
  100. $tbl->setSyncUrl(Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace());
  101. $tbl->setLabel($tblLabel);
  102. $tbl->setFilterInit($filterInit);
  103. if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
  104. $tbl->addRowFunction('edit');
  105. $tbl->addRowFunction('hist');
  106. $tbl->addRowFunction('files');
  107. $tbl->addRowFunction('cp');
  108. $tbl->addRowFunction('msgs');
  109. echo $tbl->render();
  110. } catch (Exception $e) {
  111. UI::startContainer();
  112. UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
  113. UI::endContainer();
  114. }
  115. UI::dol();
  116. }
  117. public function revertFromHistAjaxAction() {
  118. Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
  119. }
  120. public function revertFromHistAjax() {
  121. $typeName = V::get('typeName', '', $_REQUEST, 'word');
  122. if (!$typeName) throw new Exception("Wrong param typeName");
  123. // TODO: use namespace from url
  124. // $namespace = V::get('namespace', '', $_GET, 'word');
  125. // if (!$namespace) {
  126. // $typeName = V::get('typeName', '', $_GET, 'word');
  127. // if (!$typeName) throw new Exception("Wrong param typeName");
  128. // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  129. // }
  130. // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  131. $id = V::get('ID', '', $_REQUEST, 'word');
  132. if (!$id) throw new Exception("Wrong param ID");
  133. $idHist = V::get('idHist', '', $_REQUEST, 'word');
  134. if (!$idHist) throw new Exception("Wrong param idHist");
  135. $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
  136. if (!$fieldName) throw new Exception("Wrong param fieldName");
  137. $acl = $this->getAclFromTypeName($typeName);
  138. $item = $acl->getItem($id);
  139. if (!$item) throw new HttpException("Item not found", 404);
  140. if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
  141. $histItem = $acl->getHistItem($id, $idHist);
  142. if (!$histItem) throw new HttpException("Hist Item not found", 404);
  143. $histValue = V::get($fieldName, 'N/S;', $histItem);
  144. if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
  145. if ($acl->isGeomField($fieldName)) {
  146. $wktType = strtoupper($acl->getGeomFieldType($fieldName));
  147. if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
  148. if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
  149. $coords = trim(substr($histValue, strlen($wktType)), '()');
  150. $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
  151. if (!$wktValue) throw new Exception("BUG in hist record");
  152. $sqlObj = array();
  153. $sqlObj['ID'] = $id;
  154. $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
  155. $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
  156. if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
  157. else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
  158. $jsonResponse = array();
  159. $jsonResponse['type'] = 'success';
  160. $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
  161. $jsonResponse['actions'] = array();
  162. $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
  163. return $jsonResponse;
  164. } else {
  165. throw new HttpException("Not implemented - update from hist only for the geom field", 501);
  166. }
  167. throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
  168. }
  169. public function removeTheGeomAjaxAction() {
  170. Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  171. }
  172. public function removeTheGeomAjax($args) {
  173. $namespace = V::get('namespace', '', $args, 'word');
  174. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  175. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  176. $primaryKeyField = $acl->getPrimaryKeyField();
  177. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  178. $geomFieldName = 'the_geom';
  179. $response = new stdClass();
  180. if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
  181. $record = $acl->getItem($primaryKey);
  182. if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  183. if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  184. if (empty($record->{$geomFieldName})) {
  185. $response->type = 'info';
  186. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  187. $response->record = $record;
  188. return $response;
  189. }
  190. $itemPatch = array();
  191. $itemPatch[$geomFieldName] = "NULL";
  192. $itemPatch[$primaryKeyField] = $primaryKey;
  193. $response = new stdClass();
  194. try {
  195. $affected = $acl->updateItem($itemPatch);
  196. if ($affected > 0) {
  197. $response->type = 'success';
  198. $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
  199. } else if ($affected == 0) {
  200. $response->type = 'info';
  201. $response->msg = "Nie wprowadzono żadnych zmian";
  202. }
  203. $response->record = $acl->getItem($primaryKey);
  204. }
  205. catch (Exception $e) {
  206. $response->type = 'error';
  207. $response->msg = $e->getMessage();
  208. }
  209. return $response;
  210. }
  211. public function moreFunctionsCellAjaxAction() {
  212. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  213. }
  214. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  215. $id = V::get('ID', 0, $args, 'int');
  216. if ($id <= 0) throw new HttpException("404", 404);
  217. $namespace = V::get('namespace', '', $args, 'word');
  218. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  219. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  220. $response = new stdClass();
  221. $response->type = 'success';
  222. $response->msg = 'Funkcje';
  223. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  224. return $response;
  225. }
  226. public function editFormAction() {// namespace, _hash, _primaryKey
  227. $args = $_REQUEST;
  228. $id = V::get('_primaryKey', 0, $args, 'int');
  229. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  230. $namespace = V::get('namespace', '', $args, 'word');
  231. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  232. $acl = Core_AclHelper::getAclByNamespace($namespace);
  233. $tbl = new TableAjax($acl);
  234. $tblLabel = $typeName;
  235. if ('default_db' == $acl->getSourceName()) {
  236. $tblLabel = array();
  237. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  238. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  239. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  240. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  241. $tblLabel = implode(" - ", $tblLabel);
  242. }
  243. $tbl->setSyncUrl(Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace());
  244. $tbl->setLabel($tblLabel);
  245. $tbl->addRowFunction('edit');
  246. $tbl->addRowFunction('hist');
  247. $tbl->addRowFunction('files');
  248. $tbl->addRowFunction('cp');
  249. $tbl->addRowFunction('msgs');
  250. $tbl->sendAjaxEdit($id, $args);
  251. }
  252. public function editSaveAjaxAction() {
  253. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  254. }
  255. public function editSaveAjax($args) {
  256. $namespace = V::get('namespace', '', $args, 'word');
  257. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  258. $acl = Core_AclHelper::getAclByNamespace($namespace);
  259. $primaryKeyField = $acl->getPrimaryKeyField();
  260. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  261. if (empty($primaryKey)) throw new HttpException("Wrong param id!", 400);
  262. $item = $acl->getItem($primaryKey);
  263. if (!$item) throw new HttpException("Item not exists!", 404);
  264. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  265. $response = new stdClass();
  266. $response->primaryKey = $primaryKey;
  267. try {
  268. $itemFromUser[$primaryKeyField] = $primaryKey;
  269. $affected = $acl->updateItem($itemFromUser);
  270. if ($affected > 0) {
  271. $response->type = 'success';
  272. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  273. } else if ($affected == 0) {
  274. $response->type = 'info';
  275. $response->msg = "Nie wprowadzono żadnych zmian";
  276. }
  277. $response->record = $acl->getItem($primaryKey);
  278. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  279. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  280. }
  281. catch (Exception $e) {
  282. $response->type = 'error';
  283. $response->msg = "Wystąpiły błędy!";
  284. $response->msg .= $e->getMessage();
  285. }
  286. return $response;
  287. }
  288. /**
  289. * @param string $typeName - 'p5_default_db:TEST_PERMS'
  290. */
  291. public function getAclFromTypeName($typeName, $forceTblAclInit) {
  292. $userAcl = User::getAcl();
  293. $userAcl->fetchGroups();
  294. $typeEx = explode(':', $typeName);
  295. if (2 != count($typeEx)) throw new Exception("Could not get acl for '{$typeName}' - syntax error");
  296. if ('p5_' != substr($typeEx[0], 0, 3)) throw new Exception("Could not get acl for '{$typeName}' - prefix error");
  297. $sourceName = substr($typeEx[0], 3);
  298. $objName = $typeEx[1];
  299. $acl = $userAcl->getObjectAcl($sourceName, $objName);
  300. if (!$acl) throw new Exception("Could not get acl for '{$typeName}'");
  301. $acl->init($forceTblAclInit);
  302. return $acl;
  303. }
  304. }