ViewTableAjax.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034
  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. throw new Exception("TODO: ...");
  393. }
  394. public function createSaveAjaxAction() {
  395. Response::sendTryCatchJson(array($this, 'createSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  396. }
  397. public function createSaveAjax($args) {
  398. throw new Exception("TODO: ...");
  399. }
  400. public function editFormAction() { // TODO: not used - moved to editFormJsonAction
  401. try {
  402. $args = $_REQUEST;
  403. $id = V::get('_primaryKey', 0, $args, 'int');
  404. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  405. $namespace = V::get('namespace', '', $args, 'word');
  406. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  407. $acl = Core_AclHelper::getAclByNamespace($namespace);
  408. $tbl = $this->getTableAjaxWidget($acl);
  409. $tbl->sendAjaxEdit($id, $args);
  410. } catch (Exception $e) {
  411. DBG::log($e);
  412. throw $e;
  413. }
  414. }
  415. public function editFormJsonAction() {
  416. Response::sendTryCatchJson(array($this, 'editFormJson'), $args = $_REQUEST);
  417. }
  418. public function editFormJson($args) { // namespace, _hash, _primaryKey
  419. $id = V::get('_primaryKey', 0, $args, 'int');
  420. if ($id <= 0) throw new HttpException("Bad Request - missing primaryKey", 400);
  421. $namespace = V::get('namespace', '', $args, 'word');
  422. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  423. $acl = Core_AclHelper::getAclByNamespace($namespace);
  424. $tbl = $this->getTableAjaxWidget($acl);
  425. $record = $acl->buildQuery([])->getItem($id);
  426. if (!$acl->canWriteRecord($record) && !$acl->hasPermSuperWrite()) {
  427. return [
  428. 'type' => "success",
  429. 'msg' => "Edycja rekordu nr {$id}",
  430. 'body' => [
  431. 'reactNode' => [ 'div', [ 'class' => "alert alert-danger" ], "Brak dostępu do rekordu" ]
  432. ],
  433. ];
  434. // throw new Exception("Brak dostępu do rekordu");
  435. }
  436. $fieldsList = array();
  437. foreach ($acl->getFieldListByIdZasob() as $kID => $fieldName) {
  438. if ($fieldName == 'ID') continue;
  439. $field['name'] = $fieldName;
  440. $field['opis'] = $acl->getFieldOpis($fieldName);
  441. $field['label'] = $acl->getFieldLabel($fieldName);
  442. if (empty($field['label'])) $field['label'] = str_replace('_', ' ', $fieldName);
  443. $fieldsList[$kID] = $field;
  444. }
  445. $cols = array();
  446. foreach ($fieldsList as $kID => $field) {
  447. $cols[$kID] = '';
  448. if ($acl->canReadObjectField($field['name'], $record)) {
  449. $cols[$kID] = V::get($field['name'], '', $record);
  450. } else {
  451. $cols[$kID] = '*****';
  452. }
  453. $cols[$kID] = V::get("f{$kID}", $cols[$kID], $_POST);
  454. }
  455. $tsValues = array();
  456. if (!empty($fieldsList)) {
  457. foreach ($fieldsList as $vColID => $vCol) {
  458. $typeSpecial = Typespecial::getInstance($vColID, $vCol['name']);
  459. if ($typeSpecial) {
  460. $colValue = V::get($vCol['name'], '', $record);
  461. $specialValues = $typeSpecial->getEditSelectedValuesByIds($acl->getID(), $record['ID'], $vCol['name'], $colValue);
  462. if (!empty($specialValues)) {
  463. $tsValues[$vColID] = implode('<br>', $specialValues);
  464. }
  465. }
  466. }
  467. }
  468. DBG::log($tsValues, 'array', "editFormJson::tsValues");
  469. foreach ($tsValues as $idx => $value) {
  470. if ('<' === substr($value, 0, 1)) {
  471. // $tsValues[$idx] = UI::convertHtmlToArray($value); // TODO: ...
  472. $tsValues[$idx] = [ 'P5UI__RawHtml', [ 'rawHtml' => $tsValues[$idx] ] ];
  473. }
  474. }
  475. DBG::log($tsValues, 'array', "editFormJson::tsValues parsed");
  476. $featureFunctions = [
  477. // 'edit' => [ 'href' => '#EDIT/{0}', 'ico' => 'glyphicon glyphicon-pencil', 'title' => "Edytuj rekord"],
  478. 'hist' => [ 'href' => '#HIST/{0}', 'ico' => 'glyphicon glyphicon-book', 'title' => "Historia" ],
  479. 'files' => [ 'href' => '#FILES/{0}', 'ico' => 'glyphicon glyphicon-folder-open', 'title' => "Pliki" ],
  480. // 'cp' => [ 'href' => '#', 'ico' => 'glyphicon glyphicon-plus-sign', 'title' => "Kopiuj rekord", 'onclick' => 'return tableAjaxCopy({0});' ],
  481. 'msgs' => [ 'href' => "index.php?_route=TableMsgs&_task=tableRow&idTable=".$acl->getID()."&idRow={0}", 'ico' => 'glyphicon glyphicon-envelope', 'title' => "Wiadomości" ],
  482. ];
  483. $rowFunctionsOut = [ 'P5UI__FeatureRowFunctions', [
  484. 'id' => $record[ $acl->getPrimaryKeyField() ],
  485. 'functions' => $featureFunctions,
  486. 'showLabels' => true,
  487. 'viewMoreDropdown' => [
  488. 'primaryKey' => $record['ID'],
  489. 'uri' => $this->getLink('moreFunctionsCellAjax', [ 'namespace' => $acl->getNamespace(), 'ID' => $record['ID'] ]),
  490. ],
  491. ] ]; // TODO: $this->_showRowFunctions($record['ID'], array('edit', 'cp'), true);
  492. $jsFields = [];
  493. $tabindex = 0;
  494. foreach ($fieldsList as $kID => $vCol) {
  495. $fieldName = $vCol['name'];
  496. if ($acl->canWriteObjectField($fieldName, $record)) {
  497. DBG::log("editFormJson::field({$fieldName})");
  498. $fieldParams = [ 'appendBack' => true, 'tabindex' => (++$tabindex), 'maxGrid' => 8 ];
  499. if (!empty($tsValues[$kID])) $fieldParams['typespecialValue'] = $tsValues[$kID];
  500. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  501. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  502. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label'] ],
  503. [ '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}" ] ],
  504. ] ],
  505. [ 'div', [ 'class' => "" ], [
  506. UI::hGetFormItem($acl, $fieldName, 'W', $kID, "f{$kID}", $cols[$kID], $fieldParams, $record),
  507. ] ]
  508. ] ];
  509. } else if ($acl->canReadObjectField($fieldName, $record)) {
  510. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  511. [ 'label', [ 'class' => "control-label", 'for' => "f{$kID}" ], [
  512. [ 'span', [ 'style' => ['padding-right'=>'4px'] ], $vCol['label']],
  513. [ '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}" ] ],
  514. ] ],
  515. [ 'div', [ 'class' => "" ], [
  516. ['p', [ 'style' => [ 'margin-top' => '5px' ] ], [
  517. (!empty($tsValues[$kID]))
  518. ? $tsValues[$kID]
  519. : V::get($fieldName, '', $record)
  520. ] ],
  521. ] ]
  522. ] ];
  523. } else {
  524. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  525. "TODO: SKIP field ({$fieldName}) - ! canWriteObjectField && ! canReadObjectField"
  526. ]];
  527. }
  528. }
  529. $jsFields[] = [ 'div', [ 'class' => "form-group" ], [
  530. [ 'div', [ 'class' => "" ], [
  531. ['button', [ 'type' => "submit", 'class' => "btn btn-primary", 'tabindex' => ++$tabindex ], "Zapisz" ]
  532. ] ]
  533. ] ];
  534. $tblLabel = $acl->getNamespace();
  535. if ('default_db' == $acl->getSourceName()) {
  536. $tblLabel = array();
  537. $zasobObj = ProcesHelper::getZasobTableInfo($acl->getID());
  538. if (!$zasobObj) throw new Exception("Zasob TABELA ID=" . $acl->getID() . " nie istnieje");
  539. if (!empty($zasobObj->DESC_PL)) $tblLabel []= $zasobObj->DESC_PL;
  540. if (!empty($zasobObj->OPIS)) $tblLabel []= $zasobObj->OPIS;
  541. $tblLabel = implode(" - ", $tblLabel);
  542. }
  543. $syncUrl = Request::getPathUri() . 'index.php?_route=ViewTableAjax&namespace=' . $acl->getNamespace();
  544. $jsGui = [
  545. 'reactNode' => [ 'div', [ 'class' => "container AjaxFrmHorizontalEdit", 'style' => [ "max-width" => "940px" ] ], [
  546. [ 'h4', [ 'style' => [ "padding-bottom" => "3px", "border-bottom" => "1px solid #ddd" ] ], [
  547. "Edycja rekordu Nr {$record['ID']}",
  548. [ 'small', [ 'class' => "pull-right valign-btns-bottom" ], [ $rowFunctionsOut ] ],
  549. ] ],
  550. [ 'P5UI__FeatureEditForm', [
  551. 'class' => "", 'action' => "", 'method' => "post",
  552. 'id' => "EDIT_FRM_{$this->_htmlID}", // TODO: rm - use React nodes // TODO: $this->_htmlID not exists!
  553. 'ajaxSaveUrl' => "{$syncUrl}&_task=editSaveAjax", // TODO:? &_hash={$this->_htmlID}
  554. 'namespace' => $acl->getNamespace(),
  555. 'idRecord' => $record['ID'],
  556. 'tableLabelHtml' => $tblLabel,
  557. ], [
  558. [ 'fieldset', [ 'style' => [ "padding-bottom" => "100px" ] ], $jsFields ] // fieldset
  559. ] ] // form
  560. ] ] // .container
  561. ];
  562. return [
  563. 'type' => "success",
  564. 'msg' => "Edycja rekordu nr {$id}",
  565. 'body' => $jsGui, // TODO: action for GUI: array to render by function h, js to trigger
  566. ];
  567. }
  568. public function editSaveAjaxAction() {
  569. Response::sendTryCatchJson(array($this, 'editSaveAjax'), $args = 'JSON_FROM_REQUEST_BODY');
  570. }
  571. public function editSaveAjax($args) {
  572. $namespace = V::get('namespace', '', $args, 'word');
  573. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  574. $acl = Core_AclHelper::getAclByNamespace($namespace);
  575. $primaryKeyField = $acl->getPrimaryKeyField();
  576. $primaryKey = V::get('primaryKey', 0, $args, 'int');
  577. if (empty($primaryKey)) throw new HttpException("Bad Request - missing primaryKey!", 400);
  578. $item = $acl->getItem($primaryKey);
  579. if (!$item) throw new HttpException("Item not exists!", 404);
  580. $itemFromUser = $acl->convertObjectFromUserInput($args['form'], $type = 'array_by_id', $prefix = 'f');
  581. $response = new stdClass();
  582. $response->primaryKey = $primaryKey;
  583. try {
  584. $itemFromUser[$primaryKeyField] = $primaryKey;
  585. $affected = $acl->updateItem($itemFromUser);
  586. if ($affected > 0) {
  587. $response->type = 'success';
  588. $response->msg = "Rekord zapisany pomyślnie";//"Record saved successfully";
  589. } else if ($affected == 0) {
  590. $response->type = 'info';
  591. $response->msg = "Nie wprowadzono żadnych zmian";
  592. }
  593. $response->record = $acl->getItem($primaryKey);
  594. $rowFunList = Core_AclHelper::getMoreFunctionsCell($acl, array('primary_key'=>$primaryKey, 'record'=>$response->record));
  595. if (!empty($rowFunList)) $response->rowFunctions = $rowFunList;
  596. }
  597. catch (Exception $e) {
  598. $response->type = 'error';
  599. $response->msg = "Wystąpiły błędy!";
  600. $response->msg .= $e->getMessage();
  601. }
  602. return $response;
  603. }
  604. public function typeSpecialCellAction() {
  605. Response::sendTryCatchJson(array($this, 'typeSpecialCell'), $args = $_REQUEST);
  606. }
  607. public function typeSpecialCell($args) {
  608. $namespace = V::get('namespace', '', $args, 'word');
  609. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  610. $acl = Core_AclHelper::getAclByNamespace($namespace);
  611. $id = V::get('ID', 0, $args, 'int');
  612. $fieldName = V::get('col', '', $args);
  613. if ($id <= 0 || empty($fieldName)) throw new HttpException("Bad Request - missing id or col", 400);
  614. $col = $fieldName;// TODO: RM $col
  615. $jsonData = new stdClass();
  616. $idField = $acl->getFieldIdByName($fieldName);
  617. if (!$idField) throw new Exception("Wrong field");
  618. $item = $acl->getItem($id);
  619. if (!$acl->canReadObjectField($fieldName, $item)) throw new Exception("Brak dostępu");
  620. $typeSpecial = Typespecial::getInstance($idField, $fieldName);
  621. if ($typeSpecial) {
  622. $jsonData->data = $typeSpecial->getReturnData($acl->getID(), $id, $fieldName, '');
  623. $jsonData->namespace = 'default_db/' . V::get('tbl_name', '', $jsonData->data);
  624. }
  625. return $jsonData;
  626. }
  627. /**
  628. * @param $_GET['namespace'] = AclNamespace
  629. * @param $_GET['format'] = 'csv' | 'html'
  630. * @param $_GET['flds'] = csv - coma separated field names
  631. * @param $_GET['sortCol'] = FieldName
  632. * @param $_GET['sortDir'] = SortDir ('desc' | 'asc')
  633. * @param $_GET['f_{$fieldName}'] = filter
  634. * @param $_GET['sf_{$fieldName}'] = force filter
  635. */
  636. public function exportAction() {
  637. $args = $_GET;
  638. $namespace = V::get('namespace', '', $args, 'word');
  639. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  640. $acl = Core_AclHelper::getAclByNamespace($namespace);
  641. $exportLimit = 10000;
  642. $params = array();
  643. $params['limit'] = $exportLimit;
  644. // $params['limitstart'] = 0;
  645. $params['order_by'] = V::get('sortCol', '', $args);
  646. $params['order_dir'] = V::get('sortDir', '', $args);
  647. $params['cols'] = array($acl->getPrimaryKeyField());
  648. $toExportFields = explode(',', V::get('flds', '', $_GET));
  649. if (empty($toExportFields)) throw new Exception("Nie wybrano żandych pól do exportu.");
  650. $allowedExportFieldList = Core_AclHelper::getExportFieldList($acl);
  651. foreach ($toExportFields as $fieldName) {
  652. if ($fieldName == $acl->getPrimaryKeyField()) continue;
  653. if (!in_array($fieldName, $allowedExportFieldList)) throw new Exception("Brak uprawnień do exportu pola '{$fieldName}'");
  654. $params['cols'][] = $fieldName;
  655. }
  656. $labels = array();
  657. foreach ($toExportFields as $fieldName) {
  658. $labels[ $fieldName ] = $acl->getFieldLabel($fieldName);
  659. }
  660. foreach ($args as $k => $v) {
  661. if (strlen($k) > 3 && substr($k, 0, 2) == 'f_' && strlen($v) > 0) {// filter prefix
  662. $params[$k] = $v;
  663. }
  664. else if (strlen($k) > 4 && substr($k, 0, 3) == 'sf_' && strlen($v) > 0) {// special filter prefix
  665. $params[$k] = $v;
  666. }
  667. }
  668. try {
  669. $queryFeatures = $acl->buildQuery($params);
  670. $total = $queryFeatures->getTotal();
  671. $listItems = $queryFeatures->getItems();
  672. $primaryKeyField = $acl->getPrimaryKeyField();
  673. $items = []; foreach ($listItems as $item) $items[ $item[$primaryKeyField] ] = $item;
  674. } catch (Exception $e) {
  675. DBG::log($e);
  676. throw $e;
  677. }
  678. $format = V::get('format', 'html', $_GET);
  679. switch ($format) {
  680. case 'html': {
  681. UI::gora();
  682. echo UI::h('table', ['class'=>'table table-bordered table-hover'], [
  683. UI::h('thead', [], [
  684. UI::h('tr', [], array_map(function ($label) {
  685. return UI::h('th', [], $label);
  686. }, $labels))
  687. ]),
  688. UI::h('tbody', [], array_map(function ($item) use($labels) {
  689. return UI::h('tr', [], array_map(function ($fieldName) use ($item) {
  690. return UI::h('td', [], V::get($fieldName, '', $item));
  691. }, array_keys($labels)));
  692. }, $items)),
  693. ]);
  694. UI::dol();
  695. exit;
  696. }
  697. case 'csv_cp1250':
  698. case 'csv': {
  699. $csvFileName = "Tabela-" . $acl->getName() . "-" . date("Y-m-d_H_s");
  700. header('Content-Type: text/csv; charset=utf-8');
  701. header("Content-Disposition: attachment; filename={$csvFileName}.csv");
  702. $csvSeparator = ';';
  703. $csvHeader = implode($csvSeparator, array_map(function ($label) use ($item) {
  704. return '"' . addslashes($label) . '"';
  705. }, array_values($labels)));
  706. $csvRows = implode("\r\n", array_map(function ($item) use ($labels, $csvSeparator) {
  707. return implode($csvSeparator, array_map(function ($fieldName) use ($item) {
  708. return '"' . addslashes(V::get($fieldName, '', $item)) . '"';
  709. }, array_keys($labels)));
  710. }, $items));
  711. switch ($format) {
  712. case 'csv': echo $csvHeader . "\n" . $csvRows; exit;
  713. case 'csv_cp1250': echo iconv('utf-8', 'Windows-1250//IGNORE', $csvHeader) . "\r\n" . iconv('utf-8', 'Windows-1250//IGNORE', $csvRows); exit;
  714. die("Nieobsługiwane kodowanie danych csv.");
  715. }
  716. exit;
  717. }
  718. }
  719. die("Nieobsługiwany format danych.");
  720. }
  721. public function loadDataAjaxAction() {
  722. $namespace = V::get('namespace', '', $_REQUEST, 'word');
  723. if (!$namespace) throw new HttpException("Bad Request - missing namespace", 400);
  724. $acl = Core_AclHelper::getAclByNamespace($namespace);
  725. $backRefFilter = [
  726. 'namespace' => V::get('backRefNS', '', $_REQUEST),
  727. 'primaryKey' => V::get('backRefPK', '', $_REQUEST),
  728. 'fieldName' => V::get('backRefField', '', $_REQUEST),
  729. ];
  730. $childRefFilter = [
  731. 'namespace' => V::get('childRefNS', '', $_GET),
  732. 'primaryKey' => V::get('childRefPK', '', $_GET),
  733. ];
  734. $tbl = $this->getTableAjaxWidget($acl, $backRefFilter, $childRefFilter);
  735. Response::sendTryCatchJson(array($tbl, 'ajaxData'), $args = $_GET);
  736. }
  737. public function uploadFilesAjaxAction() {
  738. Response::sendTryCatchJson([$this, 'uploadFilesAjax'], $args = $_POST);
  739. }
  740. public function uploadFilesAjax($args) {
  741. DBG::log($_FILES, 'array', "\$_FILES");
  742. DBG::log($args, 'array', "\$args");
  743. $namespace = V::get('namespace', '', $args, 'word');
  744. if (!$namespace) throw new Exception("Missing namespace");
  745. $primaryKey = V::get('primaryKey', '', $args, 'int');
  746. if ($primaryKey <= 0) throw new Exception("Missing primaryKey");
  747. if (empty($_FILES)) throw new Exception("Missing files");
  748. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  749. Lib::loadClass('FileUploader');
  750. Lib::loadClass('FoldersConfig');
  751. // $dbID = $acl->getDB();
  752. // $db = DB::getDB($dbID);
  753. // if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  754. $record = $acl->buildQuery([])->getItem($primaryKey);
  755. DBG::log($record, 'array', "\$record");
  756. if (!$record) throw new HttpException("No item ID({$primaryKey})", 404);
  757. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  758. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  759. $rootTableName = $acl->getRootTableName();
  760. $confTblName = "{$rootTableName}_COLUMN";
  761. $folderConfAll = FoldersConfig::getRawData();
  762. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$rootTableName})", 404);
  763. $folderConf = FoldersConfig::getAll($confTblName);
  764. DBG::log($folderConf, 'array', "\$folderConf");
  765. $uploader = new FileUploader($confTblName, (object)$record);
  766. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$rootTableName})", 404);
  767. $uploader->findFolder();
  768. DBG::log($uploader, 'array', "\$uploader");
  769. // $errorMsg = '';
  770. // if (!empty($args['SCANS_COLUMN_ADD'])) {
  771. // $uploaded = $uploader->tryMoveFromScanAjax($errorMsg);
  772. // }
  773. // else {
  774. // $uploaded = $uploader->tryUploadAjax($errorMsg);
  775. // }
  776. $destPath = $uploader->getDestLocalPath($show_if_not_found = true);
  777. DBG::log($destPath, 'array', "\$destPath");
  778. if (!file_exists($destPath)) {
  779. if (!$uploader->tryCreateDestFolder($destPath)) throw new Exception("Wystąpił błąd podczas tworzenie katalogu dla rekordu '{$primaryKey}'");
  780. }
  781. $generateSafeFileName = function($destPath, $fileName) {
  782. if (!file_exists("{$destPath}/{$fileName}")) return $fileName;
  783. $infoPath = pathinfo($fileName);
  784. // pathinfo('/path/t1/t2/fileName.ext') = [
  785. // [dirname] => /path/t1/t2
  786. // [basename] => fileName.ext
  787. // [extension] => ext
  788. // [filename] => fileName
  789. // ]
  790. return $infoPath['filename'] . "--" . date("Y-m-d_H-i-s") . "." . $infoPath['extension'];
  791. };
  792. $moveActions = array_map(function ($file) use ($destPath, $generateSafeFileName) {
  793. $safeName = $generateSafeFileName($destPath, $file['name']);
  794. return [
  795. $file['tmp_name'],
  796. "{$destPath}/{$safeName}",
  797. $safeName,
  798. ];
  799. }, $_FILES);
  800. DBG::log($moveActions, 'array', "\$moveActions"); // [ [ srcPath, descPath ] ]
  801. $errorMsgs = [];
  802. $pkField = $acl->getSqlPrimaryKeyField();
  803. foreach ($moveActions as $fileMoveAction) {
  804. if (!move_uploaded_file($fileMoveAction[0], $fileMoveAction[1])) {
  805. $errorMsgs[] = "Nie udało się wgrać pliku '{$fileMoveAction[2]}'";
  806. } else {
  807. try {
  808. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  809. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  810. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  811. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  812. ]);
  813. if ($affected) {
  814. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  815. 'ID_USERS2' => $primaryKey,
  816. 'M_DIST_FILES' => "Wrano plik '{$fileMoveAction[2]}'",
  817. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  818. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  819. ]);
  820. }
  821. } catch (Exception $e) {
  822. DBG::log($e);
  823. $errorMsgs[] = $e->getMessage();
  824. }
  825. }
  826. }
  827. if (!empty($errorMsgs)) {
  828. return [
  829. 'type' => "error",
  830. 'msg' => "Wystąpiły błędy podczas wgrywania plików dla '{$primaryKey}'",
  831. 'errors' => $errorMsgs,
  832. ];
  833. }
  834. return [
  835. 'type' => "success",
  836. 'msg' => "Wgrano nowe pliki dla '{$primaryKey}'",
  837. ];
  838. }
  839. public function removeFileAjaxAction() {
  840. Response::sendTryCatchJson([$this, 'removeFileAjax'], $args = $_REQUEST);
  841. }
  842. public function removeFileAjax($args) { // ajaxFileRemove
  843. $namespace = V::get('namespace', '', $args, 'word');
  844. if (!$namespace) throw new Exception("Missing namespace");
  845. $id = V::get('ID', 0, $args, 'int');
  846. if ($id <= 0) throw new Exception("Missing ID");
  847. $filename = V::get('filename', '', $args);
  848. if (empty($filename)) throw new Exception("Nie wybrano pliku do usunięcia");
  849. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  850. $dbID = $acl->getDB();
  851. $db = DB::getPDO($dbID);
  852. if (!$db) throw new HttpException("No DB ({$dbID})", 406);
  853. $record = $acl->buildQuery([])->getItem($id);
  854. if (!$record) throw new HttpException("No item ID({$id})", 404);
  855. if (!$acl->canReadRecord($record)) throw new Exception("Brak uprawnień do odczytu");
  856. if (!$acl->canWriteRecord($record)) throw new Exception("Brak uprawnień do zapisu");
  857. Lib::loadClass('FileUploader');
  858. Lib::loadClass('FoldersConfig');
  859. $tblName = $acl->getName();
  860. $confTblName = "{$tblName}_COLUMN";
  861. $folderConfAll = FoldersConfig::getRawData();
  862. if (!FoldersConfig::hasConfig($confTblName)) throw new HttpException("Brak danych konfiguracyjnych ({$tblName})", 404);
  863. $folderConf = FoldersConfig::getAll($confTblName);
  864. $uploader = new FileUploader($confTblName, (object)$record);
  865. if (!$uploader->setConfig($folderConf)) throw new HttpException("Błąd danych konfiguracyjnych ({$tblName})", 404);
  866. $uploader->findFolder();
  867. $errorMsg = '';
  868. $removed = $uploader->tryRemoveFromAjax($filename, $errorMsg);
  869. if (!$removed) throw new Exception($errorMsg);
  870. // $affected = DB::getPDO($acl->getDB())->update();
  871. $rootTableName = $acl->getRootTableName();
  872. $pkField = $acl->getSqlPrimaryKeyField();
  873. $primaryKey = $id;
  874. try {
  875. $affected = DB::getPDO($acl->getDB())->update($rootTableName, $pkField, $primaryKey, [
  876. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  877. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  878. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  879. ]);
  880. if ($affected) {
  881. DB::getPDO($acl->getDB())->insert("{$rootTableName}_HIST", [
  882. 'ID_USERS2' => $primaryKey,
  883. 'M_DIST_FILES' => "Usunięto plik '{$filename}'",
  884. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  885. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  886. ]);
  887. }
  888. } catch (Exception $e) {
  889. DBG::log($e);
  890. }
  891. return [
  892. 'type' => 'success',
  893. 'msg' => 'Plik został usunięty',
  894. ];
  895. }
  896. public function procesInitFiltrAjaxAction() {
  897. Response::sendTryCatchJson([$this, 'procesInitFiltrAjax'], $args = $_GET);
  898. }
  899. public function procesInitFiltrAjax($args) { // ajaxFileRemove
  900. $namespace = V::get('namespace', '', $args, 'word');
  901. if (!$namespace) throw new Exception("Missing namespace");
  902. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  903. $pInitList = User::getAcl()->getTableProcesInitList($acl->getID());
  904. DBG::log($pInitList, 'array', "\$pInitList");
  905. if (!empty($pInitList)) {
  906. $procesIds = array_keys($pInitList);
  907. $mapTree = ACL::getProcesInitMapTreeOnlyIds($procesIds);
  908. DBG::log($mapTree, 'array', "\$mapTree");
  909. DBG::log($pInitList, 'array', "\$pInitList");
  910. $pInitListSelected = User::getAcl()->getPermsFiltrProcesId();
  911. return [
  912. 'type' => 'success',
  913. 'msg' => 'ok',
  914. 'pInitData' => [
  915. 'pInitList' => $pInitList,
  916. 'mapTree' => $mapTree,
  917. 'pInitListSelected' => $pInitListSelected,
  918. ],
  919. ];
  920. }
  921. return [
  922. 'type' => 'success'
  923. ];
  924. }
  925. public function tableToolsAjaxAction() {
  926. Response::sendTryCatchJson([$this, 'tableToolsAjax'], $args = $_GET);
  927. }
  928. public function tableToolsAjax($args) { // ajaxFileRemove
  929. $namespace = V::get('namespace', '', $args, 'word');
  930. if (!$namespace) throw new Exception("Missing namespace");
  931. $acl = Core_AclHelper::getAclByNamespace($namespace, $forceTblAclInit = ('1' == V::get('_force', '', $_GET)));
  932. $listUrlFunctions = Route_UrlAction::getTableFunctions($acl->getID(), $idRecord = 0, $acl->getName(), User::getLogin());
  933. DBG::log($listUrlFunctions, 'array', "\$listUrlFunctions");
  934. $listUrlFunctions = array_map(function ($urlFunction) use ($namespace) {
  935. if ('index.php?' === substr($urlFunction['baseLink'], 0, strlen('index.php?'))) $urlFunction['baseLink'] .= "&_fromNamespace={$namespace}";
  936. return $urlFunction;
  937. }, $listUrlFunctions);
  938. return [
  939. 'type' => "success",
  940. 'msg' => 'ok',
  941. 'body' => [
  942. 'tableTools' => array_values(array_map(function ($urlFunction) {
  943. return [
  944. 'url' => $urlFunction['baseLink'],
  945. 'label' => $urlFunction['label'],
  946. // TODO: $urlFunction['link_target'] // "_blank"
  947. // ? $urlFunction['name']
  948. ];
  949. }, array_filter($listUrlFunctions, function ($urlFunction) {
  950. return empty($urlFunction['cell_id_params']);
  951. }))),
  952. ],
  953. ];
  954. }
  955. }