ViewTableAjax.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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->showUserTableFilter($this->getLink("getUserTableFilterAjax"));
  29. $tbl->setLabel($tblLabel);
  30. $tbl->addRowFunction('edit');
  31. $tbl->addRowFunction('hist');
  32. $tbl->addRowFunction('files');
  33. $tbl->addRowFunction('cp');
  34. $tbl->addRowFunction('msgs');
  35. return $tbl;
  36. }
  37. public function defaultAction() {
  38. UI::gora();
  39. UI::menu();
  40. try {
  41. $namespace = V::get('namespace', '', $_GET, 'word');
  42. if (!$namespace) {
  43. $typeName = V::get('typeName', '', $_GET, 'word');
  44. if (!$typeName) throw new Exception("Wrong param typeName");
  45. $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  46. }
  47. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  48. $forceFilterInit = array();
  49. $filterInit = new stdClass();
  50. $filterInit->currSortCol = $acl->getPrimaryKeyField();
  51. $filterInit->currSortFlip = 'desc';
  52. foreach ($_GET as $k => $v) {
  53. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
  54. $filterInit->$k = $v;
  55. }
  56. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
  57. $filterInit->$k = $v;
  58. }
  59. else if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  60. $fldName = substr($k, 3);
  61. $forceFilterInit[$fldName] = $v;
  62. }
  63. }
  64. $tbl = $this->getTableAjaxWidget($acl);
  65. $tbl->setFilterInit($filterInit);
  66. if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
  67. echo $tbl->render();
  68. if (DBG::isActive() && V::get('DBG_ACL', '', $_GET)) {// test load perms
  69. Lib::loadClass('DebugExecutionTime');
  70. $dbgExecTime = new DebugExecutionTime();
  71. $dbgExecTime->activate();
  72. $dbgExecTime->log('start');
  73. UI::startContainer(['style'=>'border:1px solid red']);
  74. UI::tag('p', null, "TEST - load perms from db");
  75. $idTable = $acl->getID();
  76. UI::tag('p', null, "DBG idTable({$idTable})");
  77. if ($idTable > 0) {
  78. $dbgExecTime->log('before sql');
  79. $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
  80. $dbgExecTime->log('after sql', ['sql']);
  81. UI::table(['caption' => "from CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW", 'rows' => $aclTableRows]);
  82. $csvIdProces = array();
  83. foreach ($aclTableRows as $row) {
  84. if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
  85. }
  86. }
  87. $tableName = $acl->getName();
  88. $databaseName = DB::getPDO()->getDatabaseName();
  89. UI::table([
  90. 'caption' => "Cell to process",
  91. 'rows' => array_map(
  92. function ($row) use ($aclTableRows, $idTable) {
  93. $row['proces'] = array();
  94. $row['id_zasob'] = 0;
  95. $row['PERM_R'] = 0;
  96. $row['PERM_W'] = 0;
  97. $row['PERM_X'] = 0;
  98. $row['PERM_C'] = 0;
  99. $row['PERM_S'] = 0;
  100. $row['PERM_O'] = 0;
  101. $row['PERM_V'] = 0;
  102. $row['PERM_E'] = 0;
  103. foreach ($aclTableRows as $aclInfo) {
  104. if (strtolower($aclInfo['CELL_NAME']) == strtolower($row['COLUMN_NAME'])) {
  105. $row['proces'][] = $aclInfo['ID_PROCES'];
  106. $row['id_zasob'] = $aclInfo['ID_CELL'];
  107. $row['PERM_R'] += $aclInfo['PERM_R'];
  108. $row['PERM_W'] += $aclInfo['PERM_W'];
  109. $row['PERM_X'] += $aclInfo['PERM_X'];
  110. $row['PERM_C'] += $aclInfo['PERM_C'];
  111. $row['PERM_S'] += $aclInfo['PERM_S'];
  112. $row['PERM_O'] += $aclInfo['PERM_O'];
  113. $row['PERM_V'] += $aclInfo['PERM_V'];
  114. $row['PERM_E'] += $aclInfo['PERM_E'];
  115. }
  116. }
  117. $row['proces'] = (empty($row['proces']))
  118. ? "<i style=\"color:red\">Brak</i>"
  119. : implode(", ", $row['proces']);
  120. 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");
  121. return $row;
  122. }, DB::getPDO()->fetchAll("
  123. select t.TABLE_NAME, t.COLUMN_NAME, t.DATA_TYPE, t.COLUMN_TYPE
  124. from `information_schema`.`COLUMNS` t
  125. where t.TABLE_SCHEMA = '{$databaseName}'
  126. and t.TABLE_NAME like '{$tableName}'
  127. ")
  128. )
  129. ]);
  130. if (!empty($csvIdProces)) {
  131. $csvIdProces = implode(",", $csvIdProces);
  132. UI::tag('p', null, "DBG csvIdProces({$csvIdProces})");
  133. $userLogin = User::getLogin();
  134. $dbgExecTime->log('before sql');
  135. $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");
  136. $dbgExecTime->log('after sql', ['sql']);
  137. UI::table(['caption' => "from CRM_PROCES_idx_USER_to_PROCES_VIEW", 'rows' => $rows]);
  138. $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
  139. $userTablePerms = array();
  140. foreach ($aclTableRows as $row) {
  141. if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
  142. if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
  143. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
  144. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
  145. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
  146. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
  147. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
  148. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
  149. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
  150. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
  151. } else {
  152. $userTablePerms[ $row['CELL_NAME'] ] = $row;
  153. unset($userTablePerms[ $row['CELL_NAME'] ][ 'TABLE_DESCRIPTION' ]);
  154. unset($userTablePerms[ $row['CELL_NAME'] ][ 'ID_PROCES' ]);
  155. unset($userTablePerms[ $row['CELL_NAME'] ][ 'FORM_TREAT' ]);
  156. }
  157. }
  158. UI::table(['caption' => "\$userTablePerms", 'rows' => $userTablePerms]);
  159. } else UI::alert('warning', "brak \$csvIdProces");
  160. $dbgExecTime->printDebug();
  161. UI::endContainer();
  162. }
  163. } catch (Exception $e) {
  164. UI::startContainer();
  165. UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
  166. UI::endContainer();
  167. DBG::log($e);
  168. }
  169. UI::dol();
  170. }
  171. public function rmUserTableFilterAjaxAction() {
  172. Response::sendTryCatchJson(array($this, 'rmUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  173. }
  174. public function rmUserTableFilterAjax($args) {
  175. $namespace = V::get('namespace', '', $args);
  176. $filtrName = V::get('filtrName', '', $args);
  177. if (!$namespace) throw new Exception("Missing namespace");
  178. if (!$filtrName) throw new Exception("Missing filtrName");
  179. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  180. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  181. if (!$currentFilters) return [
  182. 'type' => 'warning',
  183. 'msg' => "Brak filtrów w bazie",
  184. ];
  185. $currentFilters = json_decode($currentFilters, 'assoc');
  186. unset($currentFilters[$namespace][$filtrName]);
  187. $affeced = DB::getPDO()->update('CRM_CONFIG', 'CONF_KEY', $userFltrConfKey, [
  188. 'CONF_VAL' => json_encode($currentFilters)
  189. ]);
  190. return [
  191. 'type' => 'success',
  192. 'msg' => 'Zapisano nowy filtr',
  193. 'data' => $currentFilters[$namespace]
  194. ];
  195. }
  196. public function addUserTableFilterAjaxAction() {
  197. Response::sendTryCatchJson(array($this, 'addUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  198. }
  199. public function addUserTableFilterAjax($args) {
  200. $namespace = V::get('namespace', '', $args);
  201. $filtrName = V::get('filtrName', '', $args);
  202. $visibleCols = V::get('visibleCols', '', $args);
  203. if (!$namespace) throw new Exception("Missing namespace");
  204. if (!$filtrName) throw new Exception("Missing filtrName");
  205. if (!$visibleCols) throw new Exception("Missing visibleCols");
  206. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  207. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  208. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  209. $currentFilters[$namespace][$filtrName] = $visibleCols;
  210. $sqlFltr = json_encode($currentFilters);
  211. DB::getPDO()->execSql("
  212. insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  213. values ('$userFltrConfKey', '{$sqlFltr}')
  214. on duplicate key update CONF_VAL = '{$sqlFltr}'
  215. ");
  216. return [
  217. 'type' => 'success',
  218. 'msg' => 'Zapisano nowy filtr',
  219. 'data' => $currentFilters[$namespace]
  220. ];
  221. }
  222. public function getUserTableFilterAjaxAction() {
  223. Response::sendTryCatchJson(array($this, 'getUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  224. }
  225. public function getUserTableFilterAjax($args) {
  226. $namespace = V::get('namespace', '', $args);
  227. if (!$namespace) throw new Exception("Missing namespace");
  228. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  229. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  230. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  231. return [
  232. 'type' => 'success',
  233. 'msg' => 'Odczytano filtry użytkownika',
  234. 'data' => (!empty($currentFilters[$namespace])) ? $currentFilters[$namespace] : []
  235. ];
  236. }
  237. public function revertFromHistAjaxAction() {
  238. Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
  239. }
  240. public function revertFromHistAjax() {
  241. $typeName = V::get('typeName', '', $_REQUEST, 'word');
  242. if (!$typeName) throw new Exception("Wrong param typeName");
  243. // TODO: use namespace from url
  244. // $namespace = V::get('namespace', '', $_GET, 'word');
  245. // if (!$namespace) {
  246. // $typeName = V::get('typeName', '', $_GET, 'word');
  247. // if (!$typeName) throw new Exception("Wrong param typeName");
  248. // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  249. // }
  250. // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  251. $id = V::get('ID', '', $_REQUEST, 'word');
  252. if (!$id) throw new Exception("Wrong param ID");
  253. $idHist = V::get('idHist', '', $_REQUEST, 'word');
  254. if (!$idHist) throw new Exception("Wrong param idHist");
  255. $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
  256. if (!$fieldName) throw new Exception("Wrong param fieldName");
  257. $acl = Core_AclHelper::getAclByTypeName($typeName);
  258. $item = $acl->getItem($id);
  259. if (!$item) throw new HttpException("Item not found", 404);
  260. if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
  261. $histItem = $acl->getHistItem($id, $idHist);
  262. if (!$histItem) throw new HttpException("Hist Item not found", 404);
  263. $histValue = V::get($fieldName, 'N/S;', $histItem);
  264. if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
  265. if ($acl->isGeomField($fieldName)) {
  266. $wktType = strtoupper($acl->getGeomFieldType($fieldName));
  267. if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
  268. if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
  269. $coords = trim(substr($histValue, strlen($wktType)), '()');
  270. $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
  271. if (!$wktValue) throw new Exception("BUG in hist record");
  272. $sqlObj = array();
  273. $sqlObj['ID'] = $id;
  274. $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
  275. $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
  276. if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
  277. else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
  278. $jsonResponse = array();
  279. $jsonResponse['type'] = 'success';
  280. $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
  281. $jsonResponse['actions'] = array();
  282. $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
  283. return $jsonResponse;
  284. } else {
  285. throw new HttpException("Not implemented - update from hist only for the geom field", 501);
  286. }
  287. throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
  288. }
  289. public function removeTheGeomAjaxAction() {
  290. Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  291. }
  292. public function removeTheGeomAjax($args) {
  293. $namespace = V::get('namespace', '', $args, 'word');
  294. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  295. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  296. $primaryKeyField = $acl->getPrimaryKeyField();
  297. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  298. $geomFieldName = 'the_geom';
  299. $response = new stdClass();
  300. if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
  301. $record = $acl->getItem($primaryKey);
  302. if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  303. if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  304. if (empty($record->{$geomFieldName})) {
  305. $response->type = 'info';
  306. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  307. $response->record = $record;
  308. return $response;
  309. }
  310. $itemPatch = array();
  311. $itemPatch[$geomFieldName] = "NULL";
  312. $itemPatch[$primaryKeyField] = $primaryKey;
  313. $response = new stdClass();
  314. try {
  315. $affected = $acl->updateItem($itemPatch);
  316. if ($affected > 0) {
  317. $response->type = 'success';
  318. $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
  319. } else if ($affected == 0) {
  320. $response->type = 'info';
  321. $response->msg = "Nie wprowadzono żadnych zmian";
  322. }
  323. $response->record = $acl->getItem($primaryKey);
  324. }
  325. catch (Exception $e) {
  326. $response->type = 'error';
  327. $response->msg = $e->getMessage();
  328. }
  329. return $response;
  330. }
  331. public function moreFunctionsCellAjaxAction() {
  332. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  333. }
  334. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  335. $id = V::get('ID', 0, $args, 'int');
  336. if ($id <= 0) throw new HttpException("404", 404);
  337. $namespace = V::get('namespace', '', $args, 'word');
  338. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  339. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  340. $response = new stdClass();
  341. $response->type = 'success';
  342. $response->msg = 'Funkcje';
  343. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  344. return $response;
  345. }
  346. public function editFormAction() {// namespace, _hash, _primaryKey
  347. try {
  348. $args = $_REQUEST;
  349. $id = V::get('_primaryKey', 0, $args, 'int');
  350. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  351. $namespace = V::get('namespace', '', $args, 'word');
  352. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  353. $acl = Core_AclHelper::getAclByNamespace($namespace);
  354. $tbl = $this->getTableAjaxWidget($acl);
  355. $tbl->sendAjaxEdit($id, $args);
  356. } catch (Exception $e) {
  357. DBG::log($e);
  358. throw $e;
  359. }
  360. }
  361. public function editFormJsonAction() {
  362. Response::sendTryCatchJson(array($this, 'editFormJson'), $args = $_REQUEST);
  363. }
  364. public function editFormJson($args) {// namespace, _hash, _primaryKey
  365. $id = V::get('_primaryKey', 0, $args, 'int');
  366. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  367. $namespace = V::get('namespace', '', $args, 'word');
  368. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  369. $acl = Core_AclHelper::getAclByNamespace($namespace);
  370. $tbl = $this->getTableAjaxWidget($acl);
  371. $record = $acl->buildQuery([])->getItem($id);
  372. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) throw new Exception("Brak dostępu do rekordu");
  373. $fieldsList = array();
  374. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  375. if ($fieldName == 'ID') continue;
  376. $field['name'] = $fieldName;
  377. $field['opis'] = $acl->getFieldOpis($fieldName);
  378. $field['label'] = $acl->getFieldLabel($fieldName);
  379. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  380. $fieldsList[$kID] = $field;
  381. }
  382. $cols = array();
  383. foreach ($fieldsList as $kID => $field) {
  384. $cols[$kID] = '';
  385. if ($acl->canReadObjectField($field['name'], $record)) {
  386. $cols[$kID] = V::get($field['name'], '', $record);
  387. } else {
  388. $cols[$kID] = '*****';
  389. }
  390. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  391. }
  392. $tsValues = array();
  393. if (!empty($fieldsList)) {
  394. foreach ($fieldsList as $vColID => $vCol) {
  395. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  396. if ($typeSpecial) {
  397. $colValue = V::get($vCol['name'], '', $record);
  398. $specialValues = $typeSpecial->getEditSelectedValuesByIds($acl->getID(), $record['ID'], $vCol['name'], $colValue);
  399. if (!empty($specialValues)) {
  400. $tsValues[$vColID] = implode('<br>', $specialValues);
  401. }
  402. }
  403. }
  404. }
  405. DBG::log($tsValues, 'array', "editFormJson::tsValues");
  406. foreach ($tsValues as $idx => $value) {
  407. if ('<' === substr($value, 0, 1)) {
  408. // $tsValues[$idx] = UI::convertHtmlToArray($value); // TODO: ...
  409. $tsValues[$idx] = [ 'P5UI__RawHtml', [ 'rawHtml' => $tsValues[$idx] ] ];
  410. }
  411. }
  412. DBG::log($tsValues, 'array', "editFormJson::tsValues parsed");
  413. $featureFunctions = [
  414. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  415. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  416. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  417. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  418. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  419. ];
  420. $rowFunctionsOut = [ 'P5UI__FeatureRowFunctions', [
  421. 'id' => $record['ID'],
  422. 'functions' => $featureFunctions,
  423. 'showLabels' => true,
  424. 'viewMoreDropdown' => [
  425. 'primaryKey' => $record['ID'],
  426. 'uri' => $this->getLink('moreFunctionsCellAjax', [ 'namespace' => $acl->getNamespace(), 'ID' => $record['ID'] ]),
  427. ],
  428. ] ]; // TODO: $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  429. $jsFields = [];
  430. $tabindex = 0;
  431. foreach ($fieldsList as $kID => $vCol) {
  432. $fieldName = $vCol['name'];
  433. if ($acl->canWriteObjectField($fieldName, $record)) {
  434. DBG::log("editFormJson::field({$fieldName})");
  435. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  436. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  437. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  438. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  439. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label'] ],
  440. [ 'i', [ 'class' => "glyphicon glyphicon-info-sign frm-help", 'data-toggle' => "popover", 'data-trigger' => "hover", 'title' => "", 'data-content' => htmlspecialchars($vCol['opis']), 'data-original-title' => "[{$kID}] {$fieldName}" ] ],
  441. ] ],
  442. [ 'div', [ 'class' => "" ], [
  443. UI::hGetFormItem($acl, $fieldName, 'W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record),
  444. ] ]
  445. ] ];
  446. } else if ($acl->canReadObjectField($fieldName, $record)) {
  447. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  448. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  449. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label']],
  450. [ 'i', [ 'class' => "glyphicon glyphicon-info-sign frm-help", 'data-toggle' => "popover", 'data-trigger' => "hover", 'title' => "", 'data-content' => htmlspecialchars($vCol['opis']), 'data-original-title' => "[{$kID}] {$fieldName}" ] ],
  451. ] ],
  452. [ 'div', [ 'class' => "" ], [
  453. ['p', [ 'style' => [ 'margin-top' => '5px' ] ], [
  454. (!empty($tsValues[$kID]))
  455. ? $tsValues[$kID]
  456. : V::get($fieldName, '', $record)
  457. ] ],
  458. ] ]
  459. ] ];
  460. } else {
  461. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  462. "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  463. ]];
  464. }
  465. }
  466. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  467. [ 'div', [ 'class' => "" ], [
  468. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  469. ] ]
  470. ] ];
  471. $tblLabel = $acl->getNamespace();
  472. if ('default_db' == $acl->getSourceName()) {
  473. $tblLabel = array();
  474. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  475. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  476. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  477. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  478. $tblLabel = implode(" - ", $tblLabel);
  479. }
  480. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  481. $jsGui = [
  482. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  483. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  484. "Edycja rekordu Nr {$record['ID']}",
  485. [ 'small', [ 'class' => "pull-right valign-btns-bottom" ], [ $rowFunctionsOut ] ],
  486. ] ],
  487. [ 'P5UI__FeatureEditForm', [
  488. 'class' => "", 'action' => "", 'method' => "post",
  489. 'id' => "EDIT_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  490. 'ajaxSaveUrl' => "{$syncUrl}&_task=editSaveAjax", // TODO:? &_hash={$this->_htmlID}
  491. 'namespace' => $acl->getNamespace(),
  492. 'idRecord' => $record['ID'],
  493. 'tableLabelHtml' => $tblLabel,
  494. ], [
  495. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  496. ] ] // form
  497. ] ] // .container
  498. ];
  499. return [
  500. 'type' => "success",
  501. 'msg' => "Edycja rekordu nr {$id}",
  502. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  503. ];
  504. }
  505. public function editSaveAjaxAction() {
  506. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  507. }
  508. public function editSaveAjax($args) {
  509. $namespace = V::get('namespace', '', $args, 'word');
  510. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  511. $acl = Core_AclHelper::getAclByNamespace($namespace);
  512. $primaryKeyField = $acl->getPrimaryKeyField();
  513. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  514. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  515. $item = $acl->getItem($primaryKey);
  516. if (!$item) throw new HttpException("Item not exists!", 404);
  517. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  518. $response = new stdClass();
  519. $response->primaryKey = $primaryKey;
  520. try {
  521. $itemFromUser[$primaryKeyField] = $primaryKey;
  522. $affected = $acl->updateItem($itemFromUser);
  523. if ($affected > 0) {
  524. $response->type = 'success';
  525. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  526. } else if ($affected == 0) {
  527. $response->type = 'info';
  528. $response->msg = "Nie wprowadzono żadnych zmian";
  529. }
  530. $response->record = $acl->getItem($primaryKey);
  531. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  532. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  533. }
  534. catch (Exception $e) {
  535. $response->type = 'error';
  536. $response->msg = "Wystąpiły błędy!";
  537. $response->msg .= $e->getMessage();
  538. }
  539. return $response;
  540. }
  541. public function typeSpecialCellAction() {
  542. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  543. }
  544. public function typeSpecialCell($args) {
  545. $namespace = V::get('namespace', '', $args, 'word');
  546. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  547. $acl = Core_AclHelper::getAclByNamespace($namespace);
  548. $id = V::get('ID', 0, $args, 'int');
  549. $fieldName = V::get('col', '', $args);
  550. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  551. $col = $fieldName;// TODO: RM $col
  552. $jsonData = new stdClass();
  553. $idField = $acl->getFieldIdByName($fieldName);
  554. if (!$idField) throw new Exception("Wrong field");
  555. $item = $acl->getItem($id);
  556. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  557. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  558. if ($typeSpecial) {
  559. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  560. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  561. }
  562. return $jsonData;
  563. }
  564. /**
  565. * @param $_GET['namespace'] = AclNamespace
  566. * @param $_GET['format'] = 'csv' | 'html'
  567. * @param $_GET['flds'] = csv - coma separated field names
  568. * @param $_GET['sortCol'] = FieldName
  569. * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
  570. * @param $_GET['f_{$fieldName}'] = filter
  571. * @param $_GET['sf_{$fieldName}'] = force filter
  572. */
  573. public function exportAction() {
  574. $args = $_GET;
  575. $namespace = V::get('namespace', '', $args, 'word');
  576. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  577. $acl = Core_AclHelper::getAclByNamespace($namespace);
  578. $exportLimit = 10000;
  579. $params = array();
  580. $params['limit'] = $exportLimit;
  581. // $params['limitstart'] = 0;
  582. $params['order_by'] = V::get('sortCol', '', $args);
  583. $params['order_dir'] = V::get('sortDir', '', $args);
  584. $params['cols'] = array($acl->getPrimaryKeyField());
  585. $toExportFields = explode(',', V::get('flds', '', $_GET));
  586. if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
  587. $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
  588. foreach ($toExportFields as $fieldName) {
  589. if ($fieldName == $acl->getPrimaryKeyField()) continue;
  590. if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
  591. $params['cols'][] = $fieldName;
  592. }
  593. $labels = array();
  594. foreach ($toExportFields as $fieldName) {
  595. $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
  596. }
  597. foreach ($args as $k => $v) {
  598. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  599. $params[$k] = $v;
  600. }
  601. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  602. $params[$k] = $v;
  603. }
  604. }
  605. try {
  606. $queryFeatures = $acl->buildQuery($params);
  607. $total = $queryFeatures->getTotal();
  608. $listItems = $queryFeatures->getItems();
  609. $primaryKeyField = $acl->getPrimaryKeyField();
  610. $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
  611. } catch (Exception $e) {
  612. DBG::log($e);
  613. throw $e;
  614. }
  615. $format = V::get('format', 'html', $_GET);
  616. switch ($format) {
  617. case 'html': {
  618. UI::gora();
  619. echo UI::h('table', ['class'=>'table table-bordered table-hover'], [
  620. UI::h('thead', [], [
  621. UI::h('tr', [], array_map(function ($label) {
  622. return UI::h('th', [], $label);
  623. }, $labels))
  624. ]),
  625. UI::h('tbody', [], array_map(function ($item) use($labels) {
  626. return UI::h('tr', [], array_map(function ($fieldName) use ($item) {
  627. return UI::h('td', [], V::get($fieldName, '', $item));
  628. }, array_keys($labels)));
  629. }, $items)),
  630. ]);
  631. UI::dol();
  632. exit;
  633. }
  634. case 'csv_cp1250':
  635. case 'csv': {
  636. $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
  637. header('Content-Type: text/csv; charset=utf-8');
  638. header("Content-Disposition: attachment; filename={$csvFileName}.csv");
  639. $csvSeparator = ';';
  640. $csvHeader = implode($csvSeparator, array_map(function ($label) use ($item) {
  641. return '"' . addslashes($label) . '"';
  642. }, array_values($labels)));
  643. $csvRows = implode("\r\n", array_map(function ($item) use ($labels, $csvSeparator) {
  644. return implode($csvSeparator, array_map(function ($fieldName) use ($item) {
  645. return '"' . addslashes(V::get($fieldName, '', $item)) . '"';
  646. }, array_keys($labels)));
  647. }, $items));
  648. switch ($format) {
  649. case 'csv': echo $csvHeader . "\n" . $csvRows; exit;
  650. case 'csv_cp1250': echo iconv('utf-8', 'Windows-1250//IGNORE', $csvHeader) . "\r\n" . iconv('utf-8', 'Windows-1250//IGNORE', $csvRows); exit;
  651. die("Nieobsługiwane kodowanie danych csv.");
  652. }
  653. exit;
  654. }
  655. }
  656. die("Nieobsługiwany format danych.");
  657. }
  658. public function loadDataAjaxAction() {
  659. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  660. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  661. $acl = Core_AclHelper::getAclByNamespace($namespace);
  662. $tbl = $this->getTableAjaxWidget($acl);
  663. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  664. }
  665. public function uploadFilesAjaxAction() {
  666. Response::sendTryCatchJson([$this, 'uploadFilesAjax'], $args = $_POST);
  667. }
  668. public function uploadFilesAjax($args) {
  669. DBG::log($_FILES, 'array', "\$_FILES");
  670. DBG::log($args, 'array', "\$args");
  671. $namespace = V::get('namespace', '', $args, 'word');
  672. if (!$namespace) throw new Exception("Missing namespace");
  673. $primaryKey = V::get('primaryKey', '', $args, 'int');
  674. if ($primaryKey <= 0) throw new Exception("Missing primaryKey");
  675. if (empty($_FILES)) throw new Exception("Missing files");
  676. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  677. Lib::loadClass('FileUploader');
  678. Lib::loadClass('FoldersConfig');
  679. // $dbID = $acl->getDB();
  680. // $db = DB::getDB($dbID);
  681. // if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  682. $record = $acl->buildQuery([])->getItem($primaryKey);
  683. DBG::log($record, 'array', "\$record");
  684. if (!$record) throw new HttpException("No item ID({$primaryKey})", 404);
  685. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  686. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  687. $rootTableName = $acl->getRootTableName();
  688. $confTblName = "{$rootTableName}_COLUMN";
  689. $folderConfAll = FoldersConfig::getRawData();
  690. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$rootTableName})", 404);
  691. $folderConf = FoldersConfig::getAll($confTblName);
  692. DBG::log($folderConf, 'array', "\$folderConf");
  693. $uploader = new FileUploader($confTblName, (object)$record);
  694. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$rootTableName})", 404);
  695. $uploader->findFolder();
  696. DBG::log($uploader, 'array', "\$uploader");
  697. // $errorMsg = '';
  698. // if (!empty($args['SCANS_COLUMN_ADD'])) {
  699. // $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  700. // }
  701. // else {
  702. // $uploaded = $uploader->tryUploadAjax($errorMsg);
  703. // }
  704. $destPath = $uploader->getDestLocalPath($show_if_not_found = true);
  705. DBG::log($destPath, 'array', "\$destPath");
  706. if (!file_exists($destPath)) {
  707. if (!$uploader->tryCreateDestFolder($destPath)) throw new Exception("Wystąpił błąd podczas tworzenie katalogu dla rekordu '{$primaryKey}'");
  708. }
  709. $generateSafeFileName = function($path) {
  710. if (!file_exists($path)) return $path;
  711. $infoPath = pathinfo($path);
  712. // pathinfo('/path/t1/t2/fileName.ext') = [
  713. // [dirname] => /path/t1/t2
  714. // [basename] => fileName.ext
  715. // [extension] => ext
  716. // [filename] => fileName
  717. // ]
  718. return $infoPath['dirname'] . "/" . $infoPath['filename'] . "--" . date("Y-m-d_H-i-s") . "." . $infoPath['extension'];
  719. };
  720. $moveActions = array_map(function ($file) use ($destPath, $generateSafeFileName) {
  721. return [
  722. $file['tmp_name'],
  723. $generateSafeFileName("{$destPath}/{$file['name']}"),
  724. $file['name'],
  725. ];
  726. }, $_FILES);
  727. DBG::log($moveActions, 'array', "\$moveActions"); // [ [ srcPath, descPath ] ]
  728. $errorMsgs = [];
  729. $pkField = $acl->getSqlPrimaryKeyField();
  730. foreach ($moveActions as $fileMoveAction) {
  731. if (!move_uploaded_file($fileMoveAction[0], $fileMoveAction[1])) {
  732. $errorMsgs[] = "Nie udało się wgrać pliku '{$fileMoveAction[2]}'";
  733. } else {
  734. try {
  735. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  736. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  737. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  738. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  739. ]);
  740. if ($affected) {
  741. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  742. 'ID_USERS2' => $primaryKey,
  743. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  744. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  745. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  746. ]);
  747. }
  748. } catch (Exception $e) {
  749. DBG::log($e);
  750. $errorMsgs[] = $e->getMessage();
  751. }
  752. }
  753. }
  754. if (!empty($errorMsgs)) {
  755. return [
  756. 'type' => "error",
  757. 'msg' => "Wystąpiły błędy podczas wgrywania plików dla '{$primaryKey}'",
  758. 'errors' => $errorMsgs,
  759. ];
  760. }
  761. return [
  762. 'type' => "success",
  763. 'msg' => "Wgrano nowe pliki dla '{$primaryKey}'",
  764. ];
  765. }
  766. }