ViewTableAjax.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  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, $backRefFilter = [], $childRefFilter = []) {
  16. $syncUrl = $this->getLink('', [ 'namespace' => $acl->getNamespace() ]);
  17. $tbl = new TableAjax($acl);
  18. $tbl->setRootUrl($syncUrl);
  19. if (!empty($backRefFilter['namespace']) && !empty($backRefFilter['primaryKey'])) {
  20. $tbl->setBackRefFilter($backRefFilter);
  21. $syncUrl = $this->getLink('', [
  22. 'namespace' => $acl->getNamespace(),
  23. 'backRefNS' => $backRefFilter['namespace'],
  24. 'backRefPK' => $backRefFilter['primaryKey'],
  25. 'backRefField' => $backRefFilter['fieldName'],
  26. ]);
  27. }
  28. if (!empty($childRefFilter['namespace']) && !empty($childRefFilter['primaryKey'])) {
  29. $tbl->setChildRefFilter($childRefFilter);
  30. $syncUrl = $this->getLink('', [
  31. 'namespace' => $acl->getNamespace(),
  32. 'childRefNS' => $childRefFilter['namespace'],
  33. 'childRefPK' => $childRefFilter['primaryKey'],
  34. ]);
  35. }
  36. $tblLabel = $acl->getNamespace();
  37. if ('default_db' == $acl->getSourceName()) {
  38. $tblLabel = array();
  39. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  40. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  41. if (!empty($zasobObj->DESC_PL)) $tblLabel[] = $zasobObj->DESC_PL;
  42. if (!empty($zasobObj->OPIS)) $tblLabel[] = $zasobObj->OPIS;
  43. $tblLabel = implode(" - ", $tblLabel);
  44. }
  45. $tbl->setSyncUrl($syncUrl);
  46. $tbl->showProcesInitFiltr = $this->getLink("procesInitFiltrAjax", [ 'namespace' => $acl->getNamespace() ]);
  47. $tbl->showTableTools = $this->getLink("tableToolsAjax", [ 'namespace' => $acl->getNamespace() ]);
  48. $tbl->useUserTableFilter = $this->getLink("getUserTableFilterAjax");
  49. $tbl->setLabel($tblLabel);
  50. $tbl->addRowFunction('edit');
  51. $tbl->addRowFunction('hist');
  52. $tbl->addRowFunction('files');
  53. $tbl->addRowFunction('cp');
  54. $tbl->addRowFunction('msgs');
  55. return $tbl;
  56. }
  57. public function defaultAction() {
  58. UI::gora();
  59. UI::menu();
  60. try {
  61. $namespace = V::get('namespace', '', $_GET, 'word');
  62. if (!$namespace) {
  63. $typeName = V::get('typeName', '', $_GET, 'word');
  64. if (!$typeName) throw new Exception("Wrong param typeName");
  65. $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  66. }
  67. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  68. $forceFilterInit = array();
  69. $filterInit = new stdClass();
  70. $filterInit->currSortCol = $acl->getPrimaryKeyField();
  71. $filterInit->currSortFlip = 'desc';
  72. foreach ($_REQUEST as $k => $v) {
  73. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && !empty($v)) {// filter prefix
  74. $filterInit->$k = $v;
  75. }
  76. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && !empty($v)) {// special filter prefix
  77. $filterInit->$k = $v;
  78. }
  79. else if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  80. $fldName = substr($k, 3);
  81. $forceFilterInit[$fldName] = $v;
  82. }
  83. }
  84. $backRefFilter = [
  85. 'namespace' => V::get('backRefNS', '', $_GET),
  86. 'primaryKey' => V::get('backRefPK', '', $_GET),
  87. 'fieldName' => V::get('backRefField', '', $_GET),
  88. ];
  89. $childRefFilter = [
  90. 'namespace' => V::get('childRefNS', '', $_GET),
  91. 'primaryKey' => V::get('childRefPK', '', $_GET),
  92. ];
  93. $tbl = $this->getTableAjaxWidget($acl, $backRefFilter, $childRefFilter);
  94. $tbl->setFilterInit($filterInit);
  95. if (!empty($forceFilterInit)) $tbl->setForceFilterInit($forceFilterInit);
  96. echo $tbl->render();
  97. if (DBG::isActive() && V::get('DBG_ACL', '', $_GET)) {// test load perms
  98. Lib::loadClass('DebugExecutionTime');
  99. $dbgExecTime = new DebugExecutionTime();
  100. $dbgExecTime->activate();
  101. $dbgExecTime->log('start');
  102. UI::startContainer(['style'=>'border:1px solid red']);
  103. UI::tag('p', null, "TEST - load perms from db");
  104. $idTable = $acl->getID();
  105. UI::tag('p', null, "DBG idTable({$idTable})");
  106. if ($idTable > 0) {
  107. $dbgExecTime->log('before sql');
  108. $aclTableRows = DB::getPDO()->fetchAll("select * from `CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW` where ID_TABLE = {$idTable}");
  109. $dbgExecTime->log('after sql', ['sql']);
  110. UI::table(['caption' => "from CRM_PROCES_idx_TABLE_TO_PROCES_PERMS_VIEW", 'rows' => $aclTableRows]);
  111. $csvIdProces = array();
  112. foreach ($aclTableRows as $row) {
  113. if (!in_array($row['ID_PROCES'], $csvIdProces)) $csvIdProces[] = $row['ID_PROCES'];
  114. }
  115. }
  116. $tableName = $acl->getName();
  117. $databaseName = DB::getPDO()->getDatabaseName();
  118. UI::table([
  119. 'caption' => "Cell to process",
  120. 'rows' => array_map(
  121. function ($row) use ($aclTableRows, $idTable) {
  122. $row['proces'] = array();
  123. $row['id_zasob'] = 0;
  124. $row['PERM_R'] = 0;
  125. $row['PERM_W'] = 0;
  126. $row['PERM_X'] = 0;
  127. $row['PERM_C'] = 0;
  128. $row['PERM_S'] = 0;
  129. $row['PERM_O'] = 0;
  130. $row['PERM_V'] = 0;
  131. $row['PERM_E'] = 0;
  132. foreach ($aclTableRows as $aclInfo) {
  133. if (strtolower($aclInfo['CELL_NAME']) == strtolower($row['COLUMN_NAME'])) {
  134. $row['proces'][] = $aclInfo['ID_PROCES'];
  135. $row['id_zasob'] = $aclInfo['ID_CELL'];
  136. $row['PERM_R'] += $aclInfo['PERM_R'];
  137. $row['PERM_W'] += $aclInfo['PERM_W'];
  138. $row['PERM_X'] += $aclInfo['PERM_X'];
  139. $row['PERM_C'] += $aclInfo['PERM_C'];
  140. $row['PERM_S'] += $aclInfo['PERM_S'];
  141. $row['PERM_O'] += $aclInfo['PERM_O'];
  142. $row['PERM_V'] += $aclInfo['PERM_V'];
  143. $row['PERM_E'] += $aclInfo['PERM_E'];
  144. }
  145. }
  146. $row['proces'] = (empty($row['proces']))
  147. ? "<i style=\"color:red\">Brak</i>"
  148. : implode(", ", $row['proces']);
  149. 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");
  150. return $row;
  151. }, DB::getPDO()->fetchAll("
  152. select t.TABLE_NAME, t.COLUMN_NAME, t.DATA_TYPE, t.COLUMN_TYPE
  153. from `information_schema`.`COLUMNS` t
  154. where t.TABLE_SCHEMA = '{$databaseName}'
  155. and t.TABLE_NAME like '{$tableName}'
  156. ")
  157. )
  158. ]);
  159. if (!empty($csvIdProces)) {
  160. $csvIdProces = implode(",", $csvIdProces);
  161. UI::tag('p', null, "DBG csvIdProces({$csvIdProces})");
  162. $userLogin = User::getLogin();
  163. $dbgExecTime->log('before sql');
  164. $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");
  165. $dbgExecTime->log('after sql', ['sql']);
  166. UI::table(['caption' => "from CRM_PROCES_idx_USER_to_PROCES_VIEW", 'rows' => $rows]);
  167. $userIdProces = array(); foreach ($rows as $row) $userIdProces[] = $row['ID_PROCES'];
  168. $userTablePerms = array();
  169. foreach ($aclTableRows as $row) {
  170. if (!in_array($row['ID_PROCES'], $userIdProces)) continue;
  171. if (array_key_exists($row['CELL_NAME'], $userTablePerms)) {
  172. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_R' ] += $row['PERM_R'];
  173. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_W' ] += $row['PERM_W'];
  174. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_X' ] += $row['PERM_X'];
  175. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_C' ] += $row['PERM_C'];
  176. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_S' ] += $row['PERM_S'];
  177. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_O' ] += $row['PERM_O'];
  178. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_V' ] += $row['PERM_V'];
  179. $userTablePerms[ $row['CELL_NAME'] ][ 'PERM_E' ] += $row['PERM_E'];
  180. } else {
  181. $userTablePerms[ $row['CELL_NAME'] ] = $row;
  182. unset($userTablePerms[ $row['CELL_NAME'] ][ 'TABLE_DESCRIPTION' ]);
  183. unset($userTablePerms[ $row['CELL_NAME'] ][ 'ID_PROCES' ]);
  184. unset($userTablePerms[ $row['CELL_NAME'] ][ 'FORM_TREAT' ]);
  185. }
  186. }
  187. UI::table(['caption' => "\$userTablePerms", 'rows' => $userTablePerms]);
  188. } else UI::alert('warning', "brak \$csvIdProces");
  189. $dbgExecTime->printDebug();
  190. UI::endContainer();
  191. }
  192. } catch (Exception $e) {
  193. UI::startContainer();
  194. UI::alert('danger', "<strong>Wystąpiły błędy!</strong> " . $e->getMessage());
  195. UI::endContainer();
  196. DBG::log($e);
  197. }
  198. UI::dol();
  199. }
  200. public function rmUserTableFilterAjaxAction() {
  201. Response::sendTryCatchJson(array($this, 'rmUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  202. }
  203. public function rmUserTableFilterAjax($args) {
  204. $namespace = V::get('namespace', '', $args);
  205. $filtrName = V::get('filtrName', '', $args);
  206. if (!$namespace) throw new Exception("Missing namespace");
  207. if (!$filtrName) throw new Exception("Missing filtrName");
  208. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  209. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  210. if (!$currentFilters) return [
  211. 'type' => 'warning',
  212. 'msg' => "Brak filtrów w bazie",
  213. ];
  214. $currentFilters = json_decode($currentFilters, 'assoc');
  215. unset($currentFilters[$namespace][$filtrName]);
  216. $affeced = DB::getPDO()->update('CRM_CONFIG', 'CONF_KEY', $userFltrConfKey, [
  217. 'CONF_VAL' => json_encode($currentFilters)
  218. ]);
  219. return [
  220. 'type' => 'success',
  221. 'msg' => 'Zapisano nowy filtr',
  222. 'data' => $currentFilters[$namespace]
  223. ];
  224. }
  225. public function addUserTableFilterAjaxAction() {
  226. Response::sendTryCatchJson(array($this, 'addUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  227. }
  228. public function addUserTableFilterAjax($args) {
  229. $namespace = V::get('namespace', '', $args);
  230. $filtrName = V::get('filtrName', '', $args);
  231. $visibleCols = V::get('visibleCols', '', $args);
  232. if (!$namespace) throw new Exception("Missing namespace");
  233. if (!$filtrName) throw new Exception("Missing filtrName");
  234. if (!$visibleCols) throw new Exception("Missing visibleCols");
  235. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  236. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  237. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  238. $currentFilters[$namespace][$filtrName] = $visibleCols;
  239. $sqlFltr = json_encode($currentFilters);
  240. DB::getPDO()->execSql("
  241. insert into CRM_CONFIG (CONF_KEY, CONF_VAL)
  242. values ('$userFltrConfKey', '{$sqlFltr}')
  243. on duplicate key update CONF_VAL = '{$sqlFltr}'
  244. ");
  245. return [
  246. 'type' => 'success',
  247. 'msg' => 'Zapisano nowy filtr',
  248. 'data' => $currentFilters[$namespace]
  249. ];
  250. }
  251. public function getUserTableFilterAjaxAction() {
  252. Response::sendTryCatchJson(array($this, 'getUserTableFilterAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  253. }
  254. public function getUserTableFilterAjax($args) {
  255. $namespace = V::get('namespace', '', $args);
  256. if (!$namespace) throw new Exception("Missing namespace");
  257. $userFltrConfKey = "tableColFilters__" . User::getLogin();
  258. $currentFilters = DB::getPDO()->fetchValue(" select CONF_VAL from CRM_CONFIG where CONF_KEY = '{$userFltrConfKey}' ");
  259. $currentFilters = ($currentFilters) ? json_decode($currentFilters, 'assoc') : [];
  260. return [
  261. 'type' => 'success',
  262. 'msg' => 'Odczytano filtry użytkownika',
  263. 'data' => (!empty($currentFilters[$namespace])) ? $currentFilters[$namespace] : []
  264. ];
  265. }
  266. public function revertFromHistAjaxAction() {
  267. Response::sendTryCatchJson(array($this, 'revertFromHistAjax'));
  268. }
  269. public function revertFromHistAjax() {
  270. $typeName = V::get('typeName', '', $_REQUEST, 'word');
  271. if (!$typeName) throw new Exception("Wrong param typeName");
  272. // TODO: use namespace from url
  273. // $namespace = V::get('namespace', '', $_GET, 'word');
  274. // if (!$namespace) {
  275. // $typeName = V::get('typeName', '', $_GET, 'word');
  276. // if (!$typeName) throw new Exception("Wrong param typeName");
  277. // $namespace = Api_WfsNs::getBaseWfsUri() . '/' . str_replace(':', '/', $typeName);
  278. // }
  279. // $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  280. $id = V::get('ID', '', $_REQUEST, 'word');
  281. if (!$id) throw new Exception("Wrong param ID");
  282. $idHist = V::get('idHist', '', $_REQUEST, 'word');
  283. if (!$idHist) throw new Exception("Wrong param idHist");
  284. $fieldName = V::get('fieldName', '', $_REQUEST, 'word');
  285. if (!$fieldName) throw new Exception("Wrong param fieldName");
  286. $acl = Core_AclHelper::getAclByTypeName($typeName);
  287. $item = $acl->getItem($id);
  288. if (!$item) throw new HttpException("Item not found", 404);
  289. if (!$acl->canWriteObjectField($fieldName, $record)) throw new Exception("Missing perm Write for field {$fieldName}");
  290. $histItem = $acl->getHistItem($id, $idHist);
  291. if (!$histItem) throw new HttpException("Hist Item not found", 404);
  292. $histValue = V::get($fieldName, 'N/S;', $histItem);
  293. if ('N/S;' == $histValue) throw new Exception("Missing field value in hist[{$idHist}] for field({$fieldName}) from item[{$id}]");
  294. if ($acl->isGeomField($fieldName)) {
  295. $wktType = strtoupper($acl->getGeomFieldType($fieldName));
  296. if (!$wktType) throw new Exception("Wrong geometry type for field {$fieldName}");
  297. if ($wktType != strtoupper(substr($histValue, 0, strlen($wktType)))) throw new Exception("Wrong geometry type for field {$fieldName} in hist value");
  298. $coords = trim(substr($histValue, strlen($wktType)), '()');
  299. $wktValue = $acl->convertGmlCoordsToWkt($wktType, $coords, ['cs'=>' ', 'ts'=>',']);
  300. if (!$wktValue) throw new Exception("BUG in hist record");
  301. $sqlObj = array();
  302. $sqlObj['ID'] = $id;
  303. $sqlObj[$fieldName] = "GeomFromText('{$wktValue}')";
  304. $affected = DB::getDB()->UPDATE_OBJ($acl->getName(), (object)$sqlObj);
  305. if (0 == $affected) throw new AlertInfoException("Nie wprowadzono żadnych zmian");
  306. else if ($affected < 0) throw new Exception("Wystąpiły błędy podczas aktualizacji rekordu [{$id}]");
  307. $jsonResponse = array();
  308. $jsonResponse['type'] = 'success';
  309. $jsonResponse['msg'] = "Zaktualizowano dane na podstawie wcześniejszej wartości dla rekordu [{$id}]";
  310. $jsonResponse['actions'] = array();
  311. $jsonResponse['actions'][] = ['jsFunction'=>'TableAjax__HIST_Route', 'args'=>[$id]];
  312. return $jsonResponse;
  313. } else {
  314. throw new HttpException("Not implemented - update from hist only for the geom field", 501);
  315. }
  316. throw new Exception("BUG: update field '{$fieldName}' in item[{$id}] from hist[{$idHist}]", 501);
  317. }
  318. public function removeTheGeomAjaxAction() {
  319. Response::sendTryCatchJson(array($this, 'removeTheGeomAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  320. }
  321. public function removeTheGeomAjax($args) {
  322. $namespace = V::get('namespace', '', $args, 'word');
  323. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  324. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  325. $primaryKeyField = $acl->getPrimaryKeyField();
  326. $primaryKey = V::get($primaryKeyField, 0, $args, 'int');
  327. $geomFieldName = 'the_geom';
  328. $response = new stdClass();
  329. if ($primaryKey <= 0) throw new HttpException("Bad Request - Wrong param ID", 400);
  330. $record = $acl->getItem($primaryKey);
  331. if (!$record) throw new HttpException("Nie odnaleziono rekordu nr {$primaryKey}", 404);
  332. if (!$acl->canWriteObjectField($geomFieldName, $record)) throw new HttpException("Brak dostępu do zapisu dla pola {$geomFieldName}", 403);
  333. if (empty($record->{$geomFieldName})) {
  334. $response->type = 'info';
  335. $response->msg = "Rekord nie jest powiązany z żadnym obiektem na mapie";
  336. $response->record = $record;
  337. return $response;
  338. }
  339. $itemPatch = array();
  340. $itemPatch[$geomFieldName] = "NULL";
  341. $itemPatch[$primaryKeyField] = $primaryKey;
  342. $response = new stdClass();
  343. try {
  344. $affected = $acl->updateItem($itemPatch);
  345. if ($affected > 0) {
  346. $response->type = 'success';
  347. $response->msg = "Usunięto obiekt z mapy dla rekordu {$primaryKey}";// Rekord zapisany pomyślnie
  348. } else if ($affected == 0) {
  349. $response->type = 'info';
  350. $response->msg = "Nie wprowadzono żadnych zmian";
  351. }
  352. $response->record = $acl->getItem($primaryKey);
  353. }
  354. catch (Exception $e) {
  355. $response->type = 'error';
  356. $response->msg = $e->getMessage();
  357. }
  358. return $response;
  359. }
  360. public function moreFunctionsCellAjaxAction() {
  361. Response::sendTryCatchJson(array($this, 'moreFunctionsCell'), $args = $_GET);
  362. }
  363. public function moreFunctionsCell($args) {// ajax task 'MORE_FUNCTIONS_CELL'
  364. $id = V::get('ID', 0, $args, 'int');
  365. if ($id <= 0) throw new HttpException("404", 404);
  366. $namespace = V::get('namespace', '', $args, 'word');
  367. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  368. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $args)));
  369. $response = new stdClass();
  370. $response->type = 'success';
  371. $response->msg = 'Funkcje';
  372. $response->rowFunctions = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key' => $id));
  373. return $response;
  374. }
  375. public function createFormAction() {// TODO: move to createFormJsonAction
  376. try {
  377. $args = $_REQUEST;
  378. $namespace = V::get('namespace', '', $args, 'word');
  379. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  380. $acl = Core_AclHelper::getAclByNamespace($namespace);
  381. $tbl = $this->getTableAjaxWidget($acl);
  382. $tbl->sendAjaxCreate();
  383. } catch (Exception $e) {
  384. DBG::log($e);
  385. throw $e;
  386. }
  387. }
  388. public function createFormJsonAction() {
  389. Response::sendTryCatchJson(array($this, 'createFormJson'), $args = $_REQUEST);
  390. }
  391. public function createFormJson($args) { // namespace, _hash, _primaryKey
  392. $namespace = V::get('namespace', '', $args, 'word');
  393. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  394. $acl = Core_AclHelper::getAclByNamespace($namespace);
  395. $tbl = $this->getTableAjaxWidget($acl);
  396. if (!Core_AclHelper::hasCreatePerms($acl)) {
  397. return [
  398. 'type' => "success",
  399. 'msg' => "Dodaj nowy rekord",
  400. 'body' => [
  401. 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak uprawnień do utworzenia nowego rekordu." ]
  402. ],
  403. ];
  404. // throw new Exception("Brak uprawnień do utworzenia nowego rekordu.");
  405. }
  406. $fieldsList = array();
  407. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  408. if ($fieldName == 'ID') continue;
  409. $field['name'] = $fieldName;
  410. $field['opis'] = $acl->getFieldOpis($fieldName);
  411. $field['label'] = $acl->getFieldLabel($fieldName);
  412. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  413. $fieldsList[$kID] = $field;
  414. }
  415. $cols = array();
  416. $forceFilterInit = array();
  417. $defaultAclGroup = User::getDefaultAclGroup();
  418. if ($defaultAclGroup) {
  419. $forceFilterInit['A_ADM_COMPANY'] = $defaultAclGroup;
  420. $forceFilterInit['A_CLASSIFIED'] = $defaultAclGroup;
  421. }
  422. foreach ($_GET as $k => $v) { // TODO: read from $args ?
  423. if (strlen($k) > 4 && substr($k, 0, 3) == 'ff_' && !empty($v)) {// force filter prefix
  424. $fldName = substr($k, 3);
  425. $forceFilterInit[$fldName] = $v;
  426. }
  427. }
  428. foreach ($fieldsList as $kID => $field) {
  429. $defaultValue = '';
  430. if (!empty($forceFilterInit[$field['name']])) {
  431. $defaultValue = $forceFilterInit[$field['name']];
  432. }
  433. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  434. }
  435. $tsValues = array();
  436. $featureFunctions = [
  437. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  438. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  439. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  440. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  441. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  442. ];
  443. $jsFields = [];
  444. $tabindex = 0;
  445. foreach ($fieldsList as $kID => $vCol) {
  446. $fieldName = $vCol['name'];
  447. DBG::log(['$fieldName'=>$fieldName, 'canCreate'=>$acl->canCreateField($fieldName)], 'array', "form field");
  448. if ($acl->canCreateField($fieldName)) {
  449. DBG::log("editFormJson::field({$fieldName})");
  450. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  451. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  452. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  453. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  454. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label'] ],
  455. [ '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}" ] ],
  456. ] ],
  457. [ 'div', [ 'class' => "" ], [
  458. UI::hGetFormItem($acl, $fieldName, 'C', $kID, "f{$kID}", $cols[$kID], $fieldParams),
  459. ] ]
  460. ] ];
  461. // } else {
  462. // $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  463. // "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  464. // ]];
  465. }
  466. }
  467. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  468. [ 'div', [ 'class' => "" ], [
  469. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  470. ] ]
  471. ] ];
  472. $tblLabel = $acl->getNamespace();
  473. if ('default_db' == $acl->getSourceName()) {
  474. $tblLabel = array();
  475. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  476. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  477. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  478. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  479. $tblLabel = implode(" - ", $tblLabel);
  480. }
  481. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  482. $jsGui = [
  483. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  484. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  485. "Dodaj nowy rekord",
  486. ] ],
  487. [ 'P5UI__FeatureCreateForm', [
  488. 'class' => "", 'action' => "", 'method' => "post",
  489. 'id' => "CREATE_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  490. 'ajaxSaveUrl' => "{$syncUrl}&_task=createSaveAjax", // TODO:? &_hash={$this->_htmlID}
  491. 'ajaxSaveLegacyUrl' => "{$syncUrl}&_task=createSaveLegacy", // TODO: Legacy RM
  492. 'namespace' => $acl->getNamespace(),
  493. 'tableLabelHtml' => $tblLabel,
  494. '_htmlID' => $acl->getName(),
  495. ], [
  496. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  497. ] ] // form
  498. ] ] // .container
  499. ];
  500. return [
  501. 'type' => "success",
  502. 'msg' => "Dodaj nowy rekord",
  503. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  504. ];
  505. }
  506. public function createSaveAjaxAction() {
  507. Response::sendTryCatchJson(array($this, 'createSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  508. }
  509. public function createSaveAjax($args) {
  510. throw new Exception("TODO: ...");
  511. }
  512. public function createSaveLegacyAction() { // TODO: Legacy RM
  513. $args = [
  514. 'namespace' => V::get('namespace', '', $_GET),
  515. 'body' => Request::getRequestJson(),
  516. ];
  517. DBG::log($args, 'array', 'createSaveLegacyAction');
  518. Response::sendTryCatchJson(array($this, 'createSaveLegacy'), $args);
  519. }
  520. public function createSaveLegacy($args) { // TODO: Legacy RM
  521. $namespace = V::get('namespace', '', $args, 'word');
  522. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  523. $body = V::get('body', null, $args);
  524. if (!$body) throw new HttpException("Bad Request - missing body", 400);
  525. $acl = Core_AclHelper::getAclByNamespace($namespace);
  526. $tbl = $this->getTableAjaxWidget($acl);
  527. DBG::log($args, 'array', "ajaxCreateSave");
  528. $createdId = null;
  529. try {
  530. $item = $acl->convertObjectFromUserInput($body, $type = 'array_by_id', $prefix = 'f');
  531. $createdId = $acl->addItem($item);
  532. if ($createdId) {
  533. return [
  534. 'type' => 'success',
  535. 'msg' => "Utworzono pomyślnie rekord nr {$createdId}",
  536. 'id' => $createdId,
  537. 'record' => $acl->buildQuery([])->getItem($createdId),
  538. ];
  539. }
  540. else {
  541. return [
  542. 'type' => 'error',
  543. 'msg' => "Nie udało się utworzyć nowego rekordu!",
  544. ];
  545. }
  546. }
  547. catch (Exception $e) {
  548. return [
  549. 'type' => 'error',
  550. 'msg' => $e->getMessage(),
  551. ];
  552. }
  553. }
  554. public function editFormAction() { // TODO: not used - moved to editFormJsonAction
  555. try {
  556. $args = $_REQUEST;
  557. $id = V::get('_primaryKey', 0, $args, 'int');
  558. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  559. $namespace = V::get('namespace', '', $args, 'word');
  560. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  561. $acl = Core_AclHelper::getAclByNamespace($namespace);
  562. $tbl = $this->getTableAjaxWidget($acl);
  563. $tbl->sendAjaxEdit($id, $args);
  564. } catch (Exception $e) {
  565. DBG::log($e);
  566. throw $e;
  567. }
  568. }
  569. public function editFormJsonAction() {
  570. Response::sendTryCatchJson(array($this, 'editFormJson'), $args = $_REQUEST);
  571. }
  572. public function editFormJson($args) { // namespace, _hash, _primaryKey
  573. $id = V::get('_primaryKey', 0, $args, 'int');
  574. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  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. $tbl = $this->getTableAjaxWidget($acl);
  579. $record = $acl->buildQuery([])->getItem($id);
  580. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
  581. return [
  582. 'type' => "success",
  583. 'msg' => "Edycja rekordu nr {$id}",
  584. 'body' => [
  585. 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak dostępu do rekordu" ]
  586. ],
  587. ];
  588. // throw new Exception("Brak dostępu do rekordu");
  589. }
  590. $fieldsList = array();
  591. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  592. if ($fieldName == 'ID') continue;
  593. $field['name'] = $fieldName;
  594. $field['opis'] = $acl->getFieldOpis($fieldName);
  595. $field['label'] = $acl->getFieldLabel($fieldName);
  596. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  597. $fieldsList[$kID] = $field;
  598. }
  599. $cols = array();
  600. foreach ($fieldsList as $kID => $field) {
  601. $cols[$kID] = '';
  602. if ($acl->canReadObjectField($field['name'], $record)) {
  603. $cols[$kID] = V::get($field['name'], '', $record);
  604. } else {
  605. $cols[$kID] = '*****';
  606. }
  607. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  608. }
  609. $tsValues = array();
  610. if (!empty($fieldsList)) {
  611. foreach ($fieldsList as $vColID => $vCol) {
  612. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  613. if ($typeSpecial) {
  614. $colValue = V::get($vCol['name'], '', $record);
  615. $specialValues = $typeSpecial->getEditSelectedValuesByIds($acl->getID(), $record['ID'], $vCol['name'], $colValue);
  616. if (!empty($specialValues)) {
  617. $tsValues[$vColID] = implode('<br>', $specialValues);
  618. }
  619. }
  620. }
  621. }
  622. DBG::log($tsValues, 'array', "editFormJson::tsValues");
  623. foreach ($tsValues as $idx => $value) {
  624. if ('<' === substr($value, 0, 1)) {
  625. // $tsValues[$idx] = UI::convertHtmlToArray($value); // TODO: ...
  626. $tsValues[$idx] = [ 'P5UI__RawHtml', [ 'rawHtml' => $tsValues[$idx] ] ];
  627. }
  628. }
  629. DBG::log($tsValues, 'array', "editFormJson::tsValues parsed");
  630. $featureFunctions = [
  631. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  632. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  633. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  634. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  635. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  636. ];
  637. $rowFunctionsOut = [ 'P5UI__FeatureRowFunctions', [
  638. 'id' => $record[ $acl->getPrimaryKeyField() ],
  639. 'functions' => $featureFunctions,
  640. 'showLabels' => true,
  641. 'viewMoreDropdown' => [
  642. 'primaryKey' => $record['ID'],
  643. 'uri' => $this->getLink('moreFunctionsCellAjax', [ 'namespace' => $acl->getNamespace(), 'ID' => $record['ID'] ]),
  644. ],
  645. ] ]; // TODO: $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  646. $jsFields = [];
  647. $tabindex = 0;
  648. foreach ($fieldsList as $kID => $vCol) {
  649. $fieldName = $vCol['name'];
  650. DBG::log(['$fieldName'=>$fieldName, '$record'=>$record, 'canWrite'=>$acl->canWriteObjectField($fieldName, $record), 'canRead'=>$acl->canReadObjectField($fieldName, $record)], 'array', "form field");
  651. if ($acl->canWriteObjectField($fieldName, $record)) {
  652. DBG::log("editFormJson::field({$fieldName})");
  653. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  654. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  655. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  656. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  657. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label'] ],
  658. [ '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}" ] ],
  659. ] ],
  660. [ 'div', [ 'class' => "" ], [
  661. UI::hGetFormItem($acl, $fieldName, 'W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record),
  662. ] ]
  663. ] ];
  664. } else if ($acl->canReadObjectField($fieldName, $record)) {
  665. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  666. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  667. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label']],
  668. [ '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}" ] ],
  669. ] ],
  670. [ 'div', [ 'class' => "" ], [
  671. ['p', [ 'style' => [ 'margin-top' => '5px' ] ], [
  672. (!empty($tsValues[$kID]))
  673. ? $tsValues[$kID]
  674. : V::get($fieldName, '', $record)
  675. ] ],
  676. ] ]
  677. ] ];
  678. // } else {
  679. // $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  680. // "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  681. // ]];
  682. }
  683. }
  684. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  685. [ 'div', [ 'class' => "" ], [
  686. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  687. ] ]
  688. ] ];
  689. $tblLabel = $acl->getNamespace();
  690. if ('default_db' == $acl->getSourceName()) {
  691. $tblLabel = array();
  692. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  693. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  694. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  695. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  696. $tblLabel = implode(" - ", $tblLabel);
  697. }
  698. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  699. $jsGui = [
  700. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  701. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  702. "Edycja rekordu Nr {$record['ID']}",
  703. [ 'small', [ 'class' => "pull-right valign-btns-bottom" ], [ $rowFunctionsOut ] ],
  704. ] ],
  705. [ 'P5UI__FeatureEditForm', [
  706. 'class' => "", 'action' => "", 'method' => "post",
  707. 'id' => "EDIT_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  708. 'ajaxSaveUrl' => "{$syncUrl}&_task=editSaveAjax", // TODO:? &_hash={$this->_htmlID}
  709. 'namespace' => $acl->getNamespace(),
  710. 'idRecord' => $record['ID'],
  711. 'tableLabelHtml' => $tblLabel,
  712. ], [
  713. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  714. ] ] // form
  715. ] ] // .container
  716. ];
  717. return [
  718. 'type' => "success",
  719. 'msg' => "Edycja rekordu nr {$id}",
  720. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  721. ];
  722. }
  723. public function editSaveAjaxAction() {
  724. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  725. }
  726. public function editSaveAjax($args) {
  727. $namespace = V::get('namespace', '', $args, 'word');
  728. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  729. $acl = Core_AclHelper::getAclByNamespace($namespace);
  730. $primaryKeyField = $acl->getPrimaryKeyField();
  731. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  732. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  733. $item = $acl->getItem($primaryKey);
  734. if (!$item) throw new HttpException("Item not exists!", 404);
  735. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  736. $response = new stdClass();
  737. $response->primaryKey = $primaryKey;
  738. try {
  739. $itemFromUser[$primaryKeyField] = $primaryKey;
  740. $affected = $acl->updateItem($itemFromUser);
  741. if ($affected > 0) {
  742. $response->type = 'success';
  743. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  744. } else if ($affected == 0) {
  745. $response->type = 'info';
  746. $response->msg = "Nie wprowadzono żadnych zmian";
  747. }
  748. $response->record = $acl->getItem($primaryKey);
  749. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  750. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  751. }
  752. catch (Exception $e) {
  753. $response->type = 'error';
  754. $response->msg = "Wystąpiły błędy!";
  755. $response->msg .= $e->getMessage();
  756. }
  757. return $response;
  758. }
  759. public function typeSpecialCellAction() {
  760. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  761. }
  762. public function typeSpecialCell($args) {
  763. $namespace = V::get('namespace', '', $args, 'word');
  764. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  765. $acl = Core_AclHelper::getAclByNamespace($namespace);
  766. $id = V::get('ID', 0, $args, 'int');
  767. $fieldName = V::get('col', '', $args);
  768. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  769. $col = $fieldName;// TODO: RM $col
  770. $jsonData = new stdClass();
  771. $idField = $acl->getFieldIdByName($fieldName);
  772. if (!$idField) throw new Exception("Wrong field");
  773. $item = $acl->getItem($id);
  774. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  775. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  776. if ($typeSpecial) {
  777. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  778. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  779. }
  780. return $jsonData;
  781. }
  782. /**
  783. * @param $_GET['namespace'] = AclNamespace
  784. * @param $_GET['format'] = 'csv' | 'html'
  785. * @param $_GET['flds'] = csv - coma separated field names
  786. * @param $_GET['sortCol'] = FieldName
  787. * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
  788. * @param $_GET['f_{$fieldName}'] = filter
  789. * @param $_GET['sf_{$fieldName}'] = force filter
  790. */
  791. public function exportAction() {
  792. $args = $_GET;
  793. $namespace = V::get('namespace', '', $args, 'word');
  794. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  795. $acl = Core_AclHelper::getAclByNamespace($namespace);
  796. $exportLimit = 10000;
  797. $params = array();
  798. $params['limit'] = $exportLimit;
  799. // $params['limitstart'] = 0;
  800. $params['order_by'] = V::get('sortCol', '', $args);
  801. $params['order_dir'] = V::get('sortDir', '', $args);
  802. $params['cols'] = array($acl->getPrimaryKeyField());
  803. $toExportFields = explode(',', V::get('flds', '', $_GET));
  804. if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
  805. $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
  806. foreach ($toExportFields as $fieldName) {
  807. if ($fieldName == $acl->getPrimaryKeyField()) continue;
  808. if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
  809. $params['cols'][] = $fieldName;
  810. }
  811. $labels = array();
  812. foreach ($toExportFields as $fieldName) {
  813. $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
  814. }
  815. foreach ($args as $k => $v) {
  816. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  817. $params[$k] = $v;
  818. }
  819. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  820. $params[$k] = $v;
  821. }
  822. }
  823. try {
  824. $queryFeatures = $acl->buildQuery($params);
  825. $total = $queryFeatures->getTotal();
  826. $listItems = $queryFeatures->getItems();
  827. $primaryKeyField = $acl->getPrimaryKeyField();
  828. $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
  829. } catch (Exception $e) {
  830. DBG::log($e);
  831. throw $e;
  832. }
  833. $format = V::get('format', 'html', $_GET);
  834. switch ($format) {
  835. case 'html': {
  836. UI::gora();
  837. echo UI::h('table', ['class'=>'table table-bordered table-hover'], [
  838. UI::h('thead', [], [
  839. UI::h('tr', [], array_map(function ($label) {
  840. return UI::h('th', [], $label);
  841. }, $labels))
  842. ]),
  843. UI::h('tbody', [], array_map(function ($item) use($labels) {
  844. return UI::h('tr', [], array_map(function ($fieldName) use ($item) {
  845. return UI::h('td', [], V::get($fieldName, '', $item));
  846. }, array_keys($labels)));
  847. }, $items)),
  848. ]);
  849. UI::dol();
  850. exit;
  851. }
  852. case 'csv_cp1250':
  853. case 'csv': {
  854. $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
  855. header('Content-Type: text/csv; charset=utf-8');
  856. header("Content-Disposition: attachment; filename={$csvFileName}.csv");
  857. $csvSeparator = ';';
  858. $csvHeader = implode($csvSeparator, array_map(function ($label) use ($item) {
  859. return '"' . addslashes($label) . '"';
  860. }, array_values($labels)));
  861. $csvRows = implode("\r\n", array_map(function ($item) use ($labels, $csvSeparator) {
  862. return implode($csvSeparator, array_map(function ($fieldName) use ($item) {
  863. return '"' . addslashes(V::get($fieldName, '', $item)) . '"';
  864. }, array_keys($labels)));
  865. }, $items));
  866. switch ($format) {
  867. case 'csv': echo $csvHeader . "\n" . $csvRows; exit;
  868. case 'csv_cp1250': echo iconv('utf-8', 'Windows-1250//IGNORE', $csvHeader) . "\r\n" . iconv('utf-8', 'Windows-1250//IGNORE', $csvRows); exit;
  869. die("Nieobsługiwane kodowanie danych csv.");
  870. }
  871. exit;
  872. }
  873. }
  874. die("Nieobsługiwany format danych.");
  875. }
  876. public function loadDataAjaxAction() {
  877. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  878. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  879. $acl = Core_AclHelper::getAclByNamespace($namespace);
  880. $backRefFilter = [
  881. 'namespace' => V::get('backRefNS', '', $_REQUEST),
  882. 'primaryKey' => V::get('backRefPK', '', $_REQUEST),
  883. 'fieldName' => V::get('backRefField', '', $_REQUEST),
  884. ];
  885. $childRefFilter = [
  886. 'namespace' => V::get('childRefNS', '', $_GET),
  887. 'primaryKey' => V::get('childRefPK', '', $_GET),
  888. ];
  889. $tbl = $this->getTableAjaxWidget($acl, $backRefFilter, $childRefFilter);
  890. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  891. }
  892. public function uploadFilesAjaxAction() {
  893. Response::sendTryCatchJson([$this, 'uploadFilesAjax'], $args = $_POST);
  894. }
  895. public function uploadFilesAjax($args) {
  896. DBG::log($_FILES, 'array', "\$_FILES");
  897. DBG::log($args, 'array', "\$args");
  898. $namespace = V::get('namespace', '', $args, 'word');
  899. if (!$namespace) throw new Exception("Missing namespace");
  900. $primaryKey = V::get('primaryKey', '', $args, 'int');
  901. if ($primaryKey <= 0) throw new Exception("Missing primaryKey");
  902. if (empty($_FILES)) throw new Exception("Missing files");
  903. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  904. Lib::loadClass('FileUploader');
  905. Lib::loadClass('FoldersConfig');
  906. // $dbID = $acl->getDB();
  907. // $db = DB::getDB($dbID);
  908. // if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  909. $record = $acl->buildQuery([])->getItem($primaryKey);
  910. DBG::log($record, 'array', "\$record");
  911. if (!$record) throw new HttpException("No item ID({$primaryKey})", 404);
  912. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  913. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  914. $rootTableName = $acl->getRootTableName();
  915. $confTblName = "{$rootTableName}_COLUMN";
  916. $folderConfAll = FoldersConfig::getRawData();
  917. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$rootTableName})", 404);
  918. $folderConf = FoldersConfig::getAll($confTblName);
  919. DBG::log($folderConf, 'array', "\$folderConf");
  920. $uploader = new FileUploader($confTblName, (object)$record);
  921. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$rootTableName})", 404);
  922. $uploader->findFolder();
  923. DBG::log($uploader, 'array', "\$uploader");
  924. // $errorMsg = '';
  925. // if (!empty($args['SCANS_COLUMN_ADD'])) {
  926. // $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  927. // }
  928. // else {
  929. // $uploaded = $uploader->tryUploadAjax($errorMsg);
  930. // }
  931. $destPath = $uploader->getDestLocalPath($show_if_not_found = true);
  932. DBG::log($destPath, 'array', "\$destPath");
  933. if (!file_exists($destPath)) {
  934. if (!$uploader->tryCreateDestFolder($destPath)) throw new Exception("Wystąpił błąd podczas tworzenie katalogu dla rekordu '{$primaryKey}'");
  935. }
  936. $generateSafeFileName = function($destPath, $fileName) {
  937. if (!file_exists("{$destPath}/{$fileName}")) return $fileName;
  938. $infoPath = pathinfo($fileName);
  939. // pathinfo('/path/t1/t2/fileName.ext') = [
  940. // [dirname] => /path/t1/t2
  941. // [basename] => fileName.ext
  942. // [extension] => ext
  943. // [filename] => fileName
  944. // ]
  945. return $infoPath['filename'] . "--" . date("Y-m-d_H-i-s") . "." . $infoPath['extension'];
  946. };
  947. $moveActions = array_map(function ($file) use ($destPath, $generateSafeFileName) {
  948. $safeName = $generateSafeFileName($destPath, $file['name']);
  949. return [
  950. $file['tmp_name'],
  951. "{$destPath}/{$safeName}",
  952. $safeName,
  953. ];
  954. }, $_FILES);
  955. DBG::log($moveActions, 'array', "\$moveActions"); // [ [ srcPath, descPath ] ]
  956. $errorMsgs = [];
  957. $pkField = $acl->getSqlPrimaryKeyField();
  958. foreach ($moveActions as $fileMoveAction) {
  959. if (!move_uploaded_file($fileMoveAction[0], $fileMoveAction[1])) {
  960. $errorMsgs[] = "Nie udało się wgrać pliku '{$fileMoveAction[2]}'";
  961. } else {
  962. try {
  963. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  964. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  965. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  966. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  967. ]);
  968. if ($affected) {
  969. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  970. 'ID_USERS2' => $primaryKey,
  971. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  972. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  973. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  974. ]);
  975. }
  976. } catch (Exception $e) {
  977. DBG::log($e);
  978. $errorMsgs[] = $e->getMessage();
  979. }
  980. }
  981. }
  982. if (!empty($errorMsgs)) {
  983. return [
  984. 'type' => "error",
  985. 'msg' => "Wystąpiły błędy podczas wgrywania plików dla '{$primaryKey}'",
  986. 'errors' => $errorMsgs,
  987. ];
  988. }
  989. return [
  990. 'type' => "success",
  991. 'msg' => "Wgrano nowe pliki dla '{$primaryKey}'",
  992. ];
  993. }
  994. public function removeFileAjaxAction() {
  995. Response::sendTryCatchJson([$this, 'removeFileAjax'], $args = $_REQUEST);
  996. }
  997. public function removeFileAjax($args) { // ajaxFileRemove
  998. $namespace = V::get('namespace', '', $args, 'word');
  999. if (!$namespace) throw new Exception("Missing namespace");
  1000. $id = V::get('ID', 0, $args, 'int');
  1001. if ($id <= 0) throw new Exception("Missing ID");
  1002. $filename = V::get('filename', '', $args);
  1003. if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
  1004. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1005. $dbID = $acl->getDB();
  1006. $db = DB::getPDO($dbID);
  1007. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  1008. $record = $acl->buildQuery([])->getItem($id);
  1009. if (!$record) throw new HttpException("No item ID({$id})", 404);
  1010. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  1011. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  1012. Lib::loadClass('FileUploader');
  1013. Lib::loadClass('FoldersConfig');
  1014. $tblName = $acl->getName();
  1015. $confTblName = "{$tblName}_COLUMN";
  1016. $folderConfAll = FoldersConfig::getRawData();
  1017. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  1018. $folderConf = FoldersConfig::getAll($confTblName);
  1019. $uploader = new FileUploader($confTblName, (object)$record);
  1020. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  1021. $uploader->findFolder();
  1022. $errorMsg = '';
  1023. $removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
  1024. if (!$removed) throw new Exception($errorMsg);
  1025. // $affected = DB::getPDO($acl->getDB())->update();
  1026. $rootTableName = $acl->getRootTableName();
  1027. $pkField = $acl->getSqlPrimaryKeyField();
  1028. $primaryKey = $id;
  1029. try {
  1030. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  1031. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  1032. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1033. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1034. ]);
  1035. if ($affected) {
  1036. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  1037. 'ID_USERS2' => $primaryKey,
  1038. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  1039. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  1040. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  1041. ]);
  1042. }
  1043. } catch (Exception $e) {
  1044. DBG::log($e);
  1045. }
  1046. return [
  1047. 'type' => 'success',
  1048. 'msg' => 'Plik został usunięty',
  1049. ];
  1050. }
  1051. public function procesInitFiltrAjaxAction() {
  1052. Response::sendTryCatchJson([$this, 'procesInitFiltrAjax'], $args = $_GET);
  1053. }
  1054. public function procesInitFiltrAjax($args) { // ajaxFileRemove
  1055. $namespace = V::get('namespace', '', $args, 'word');
  1056. if (!$namespace) throw new Exception("Missing namespace");
  1057. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1058. $pInitList = User::getAcl()->getTableProcesInitList($acl->getID());
  1059. DBG::log($pInitList, 'array', "\$pInitList");
  1060. if (!empty($pInitList)) {
  1061. $procesIds = array_keys($pInitList);
  1062. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  1063. DBG::log($mapTree, 'array', "\$mapTree");
  1064. DBG::log($pInitList, 'array', "\$pInitList");
  1065. $pInitListSelected = User::getAcl()->getPermsFiltrProcesId();
  1066. return [
  1067. 'type' => 'success',
  1068. 'msg' => 'ok',
  1069. 'pInitData' => [
  1070. 'pInitList' => $pInitList,
  1071. 'mapTree' => $mapTree,
  1072. 'pInitListSelected' => $pInitListSelected,
  1073. ],
  1074. ];
  1075. }
  1076. return [
  1077. 'type' => 'success'
  1078. ];
  1079. }
  1080. public function tableToolsAjaxAction() {
  1081. Response::sendTryCatchJson([$this, 'tableToolsAjax'], $args = $_GET);
  1082. }
  1083. public function tableToolsAjax($args) { // ajaxFileRemove
  1084. $namespace = V::get('namespace', '', $args, 'word');
  1085. if (!$namespace) throw new Exception("Missing namespace");
  1086. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  1087. $listUrlFunctions = Route_UrlAction::getTableFunctions($acl->getID(), $idRecord = 0, $acl->getName(), User::getLogin());
  1088. DBG::log($listUrlFunctions, 'array', "\$listUrlFunctions");
  1089. $listUrlFunctions = array_map(function ($urlFunction) use ($namespace) {
  1090. if ('index.php?' === substr($urlFunction['baseLink'], 0, strlen('index.php?'))) $urlFunction['baseLink'] .= "&_fromNamespace={$namespace}";
  1091. return $urlFunction;
  1092. }, $listUrlFunctions);
  1093. return [
  1094. 'type' => "success",
  1095. 'msg' => 'ok',
  1096. 'body' => [
  1097. 'tableTools' => array_values(array_map(function ($urlFunction) {
  1098. return [
  1099. 'url' => $urlFunction['baseLink'],
  1100. 'label' => $urlFunction['label'],
  1101. // TODO: $urlFunction['link_target'] // "_blank"
  1102. // ? $urlFunction['name']
  1103. ];
  1104. }, array_filter($listUrlFunctions, function ($urlFunction) {
  1105. return empty($urlFunction['cell_id_params']);
  1106. }))),
  1107. ],
  1108. ];
  1109. }
  1110. }