AntAclBase.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. <?php
  2. Lib::loadClass('ACL');
  3. Lib::loadClass('Core_AclBase');
  4. /**
  5. * SE/schema/ant-object/default_db.{rootTableName}/{name}/build.xml
  6. */
  7. class AntAclBase extends Core_AclBase {
  8. public function __construct($zasobID = 0) {
  9. $this->_zasobID = (int)$zasobID;
  10. $this->_name = '';
  11. $this->_namespace = '';
  12. $this->_rootTableName = '';
  13. $this->_db = 0; // database id zasobu
  14. $this->_rootNamespace = '';
  15. $this->_primaryKey = '';
  16. $this->_fields = [];
  17. $this->_xsdRestrictions = [];
  18. $this->_zasobyInfoFetched = false;
  19. }
  20. public function getDB() { return $this->_db; }
  21. public function getName() { return $this->_name; }
  22. public function getNamespace() { return $this->_namespace; }
  23. public function getRootNamespace() { return $this->_rootNamespace; }
  24. public function getSourceName() { return 'default_db'; } // TODO: ?
  25. public function getRootTableName() { return $this->_rootTableName; }
  26. public function getPrimaryKeyField() { return $this->_primaryKey; }
  27. public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
  28. public function getVirtualFieldListByIdZasob() { return []; }
  29. public function _fetchInfoFromZasobyIfNeeded() {
  30. if (!$this->_zasobyInfoFetched) {
  31. $zasobyIds = array_filter(
  32. array_map(function ($field) {
  33. return (int)$field['idZasob'];
  34. }, $this->_fields),
  35. function ($id) { return $id > 0; }
  36. );
  37. if (!empty($zasobyIds)) {
  38. DBG::log("DBG sort fields - TODO: ids [".implode(",", $zasobyIds)."]");
  39. $zasobyInfo = DB::getPDO()->fetchAllByKey("
  40. select z.ID, z.DESC_PL, z.OPIS, z.SORT_PRIO
  41. from CRM_LISTA_ZASOBOW z
  42. where z.ID in(".implode(",", $zasobyIds).")
  43. ", 'ID');
  44. DBG::log($zasobyInfo, 'array', "DBG sort fields - zasobyInfo");
  45. $maxSortPrio = 0;
  46. array_map(function ($zInfo) use (&$maxSortPrio) {
  47. if ($zInfo['SORT_PRIO'] > 0 && $zInfo['SORT_PRIO'] > $maxSortPrio) {
  48. $maxSortPrio = $zInfo['SORT_PRIO'];
  49. }
  50. }, $zasobyInfo);
  51. foreach ($this->_fields as $idx => $field) {
  52. // $this->_fields[$idx]['name'] = $field['fieldNamespace']; // TODO: BUG query for non existing fields - check if isLocal is used
  53. if ($field['idZasob'] > 0 && array_key_exists($field['idZasob'], $zasobyInfo)) {
  54. $this->_fields[$idx]['sort_prio'] = $zasobyInfo[ $field['idZasob'] ]['SORT_PRIO'];
  55. if (!empty($zasobyInfo[ $field['idZasob'] ]['DESC_PL'])) $this->_fields[$idx]['label'] = $zasobyInfo[ $field['idZasob'] ]['DESC_PL'];
  56. if (!empty($zasobyInfo[ $field['idZasob'] ]['OPIS'])) $this->_fields[$idx]['opis'] = $zasobyInfo[ $field['idZasob'] ]['OPIS'];
  57. } else { // !$field['idZasob'] => generate sortPrio
  58. $this->_fields[$idx]['sort_prio'] = ++$maxSortPrio;
  59. }
  60. }
  61. }
  62. $this->_zasobyInfoFetched = true;
  63. }
  64. usort($this->_fields, array($this, '_sortFieldsCallback'));
  65. DBG::log($this->_fields, 'array', "DBG sort fields - sorted \$this->_fields");
  66. }
  67. public function _sortFieldsCallback($a, $b) {
  68. if ($a['name'] == 'ID') {
  69. return -1;
  70. }
  71. else if ($b['name'] == 'ID') {
  72. return 1;
  73. }
  74. else if ($a['sort_prio'] < $b['sort_prio']) {
  75. return -1;
  76. }
  77. else if ($a['sort_prio'] > $b['sort_prio']) {
  78. return 1;
  79. }
  80. else {
  81. return 0;
  82. }
  83. }
  84. public function getVisibleFieldListByIdZasob() {
  85. $this->_fetchInfoFromZasobyIfNeeded();
  86. $fields = $this->getRealFieldListByIdZasob();
  87. $pkField = $this->getPrimaryKeyField();
  88. $cols = array();
  89. foreach ($fields as $kFieldID => $fieldName) {
  90. if ($pkField === $fieldName) {
  91. $id = $kFieldID;
  92. break;
  93. }
  94. }
  95. $cols[$id] = $pkField; // 'ID'; // TODO: why rename primary key field to ID? check JS
  96. foreach ($fields as $kFieldID => $fieldName) {
  97. if ($pkField === $fieldName) continue;
  98. $cols[$kFieldID] = $fieldName;
  99. }
  100. return $cols;
  101. }
  102. public function getRealFieldListByIdZasob() {
  103. $cols = array();
  104. foreach ($this->getFields() as $field) {
  105. if (!$field['isActive']) continue;
  106. if (!$field['idZasob']) continue;
  107. $cols[ $field['idZasob'] ] = $field['fieldNamespace'];
  108. }
  109. return $cols;
  110. }
  111. public function getRealFieldList() {
  112. $pkField = $this->getPrimaryKeyField();
  113. $cols = array_merge([ $pkField ], array_filter($this->getLocalFieldList(), function ($fieldName) use ($pkField) {
  114. if ($pkField === $fieldName) return false;
  115. return true;
  116. }));
  117. return $cols;
  118. }
  119. public function getHistItems($id, $params = array()) {
  120. DBG::log($params, 'array', "getHistItems({$id}, \$params)");
  121. $sqlPkField = $this->getSqlPrimaryKeyField();
  122. $ret = array();
  123. $sql_tbl = $this->getRootTableName() . "_HIST";
  124. $sql_cols = array_map(function ($fieldName) {
  125. return "t.`{$fieldName}`";
  126. }, $this->getRealFieldList());
  127. $sql_cols = implode(", ", $sql_cols);
  128. $sql_where = "t.`ID_USERS2`='{$id}'";
  129. $idHist = V::get('ID', 0, $params, 'int');
  130. if ($idHist > 0) {
  131. $sql_where .= "\n and t.`ID`='{$idHist}'";
  132. }
  133. $paramNotEmptyFlds = V::get('notEmptyFlds', '', $params);
  134. if (!empty($paramNotEmptyFlds) && is_array($paramNotEmptyFlds)) {
  135. $sqlWhereOr = array();
  136. foreach ($paramNotEmptyFlds as $fldName) {
  137. if (array_key_exists($fldName, $this->_cols)) {
  138. $sqlWhereOr[] = "t.`{$fldName}`!='N/S;'";
  139. }
  140. }
  141. if (!empty($sqlWhereOr)) $sql_where .= "\n and (" . implode(" or ", $sqlWhereOr) . ")";
  142. }
  143. $histRows = DB::getPDO()->fetchAllByKey("
  144. select {$sql_cols}
  145. from {$sql_tbl} as t
  146. where {$sql_where}
  147. order by ID DESC
  148. ", 'ID');
  149. return array_map(function ($row) {
  150. $r = (object)$row;
  151. $r->_author = $r->A_RECORD_UPDATE_AUTHOR;
  152. $r->_created = $r->A_RECORD_UPDATE_DATE;
  153. if (!$r->_author || $r->_author == 'N/S;') {
  154. $r->_author = $r->A_RECORD_CREATE_AUTHOR;
  155. }
  156. if (!$r->_created || $r->_created == 'N/S;') {
  157. $r->_created = $r->A_RECORD_CREATE_DATE;
  158. }
  159. return $r;
  160. }, $histRows);
  161. }
  162. public function getFieldIdByName($fieldName) {
  163. if (!$fieldName) return null;
  164. foreach ($this->getFields() as $field) {
  165. if ($fieldName !== $field['name']) continue;
  166. if (!$field['idZasob']) continue;
  167. return $field['idZasob'];
  168. }
  169. return null;
  170. }
  171. public function getFieldType($fieldName) { return null; }
  172. // try {
  173. // throw new Exception("TODO: AntAclBase::getFieldType({$fieldName})");
  174. // } catch (Exception $e) {
  175. // DBG::log($e);
  176. // }
  177. // $field = $this->_getField($fieldName);
  178. // return $field['xsdType'];
  179. // }
  180. public function getField($idField) {
  181. DBG::log($this->getFields(), 'array', "fields");
  182. foreach ($this->getFields() as $field) {
  183. if (!$field['isActive']) continue;
  184. if (!$field['idZasob']) continue;
  185. if ($idField == $field['idZasob']) {
  186. return $field;
  187. }
  188. }
  189. return null;
  190. }
  191. public function getXsdFieldType($fieldName) {
  192. $field = $this->_getField($fieldName);
  193. return $field['xsdType'];
  194. }
  195. public function getXsdMaxOccurs($fieldName) {
  196. $field = $this->_getField($fieldName);
  197. return (int)$field['maxOccurs'];
  198. }
  199. public function getXsdMinOccurs($fieldName) {
  200. $field = $this->_getField($fieldName);
  201. return (int)$field['minOccurs'];
  202. }
  203. public function getAttributesFromZasoby() {
  204. return [];// TODO: ...
  205. }
  206. public function getXsdFieldParam($fieldName, $paramKey) {
  207. switch ($paramKey) {
  208. case 'enumeration': return $this->getEnumerations($fieldName);
  209. }
  210. $xsdType = $this->getXsdFieldType($fieldName);
  211. $defaultValue = null;
  212. if ('enumeration' === $paramKey && 'p5:enum' === $xsdType) $defaultValue = [];
  213. if ('maxLength' === $paramKey && 'xsd:string' === $xsdType) $defaultValue = 255;
  214. return V::get($paramKey, $defaultValue, $this->getXsdRestrictions($fieldName));
  215. }
  216. public function getEnumerations($fieldName) {
  217. $restrictions = $this->getXsdRestrictions($fieldName);
  218. return V::get('enumeration', [], $restrictions, 'array');
  219. }
  220. public function getXsdRestrictions($fieldName) {
  221. if (array_key_exists($fieldName, $this->_xsdRestrictions)) return $this->_xsdRestrictions[$fieldName];
  222. $this->_xsdRestrictions[$fieldName] = [];
  223. $field = $this->_getField($fieldName);
  224. if (!$field['xsdRestrictions']) return [];
  225. if (is_string($field['xsdRestrictions']) && '{' === substr($field['xsdRestrictions'], 0, 1)) {
  226. $this->_xsdRestrictions[$fieldName] = @json_decode($field['xsdRestrictions'], $assoc = true);
  227. }
  228. return $this->_xsdRestrictions[$fieldName];
  229. }
  230. // public function getXsdFieldParam($fieldName, $paramKey) { // TableAcl
  231. // return ($this->_schemaClass)
  232. // ? $this->_schemaClass->getFieldParam($fieldName, $paramKey)
  233. // : null
  234. // ;
  235. // }
  236. // public function getXsdFieldParam($fieldName, $paramKey) { // SimpleSchema
  237. // if (empty($this->_simpleSchema['root'][$fieldName])) return null;
  238. // if (empty($this->_simpleSchema['root'][$fieldName]['@@params'])) return null;
  239. // if (empty($this->_simpleSchema['root'][$fieldName]['@@params'][$paramKey])) return null;
  240. // return $this->_simpleSchema['root'][$fieldName]['@@params'][$paramKey];
  241. // }
  242. public function getFieldDefaultValue($fieldName) { // TODO: get dafault value from xsd file - TODO: p5:default attribute
  243. // TODO: get from xsd file (acl cache field)
  244. // TODO: if not set then:
  245. // - 'NULL' for nillable fields
  246. // - '0' for xsd:integer, xsd:decimal
  247. // - '' else ...
  248. return '';
  249. }
  250. public function convertObjectFromUserInput($userItem, $type = 'array_by_id', $prefix = 'f') {// TODO: rename / Legacy
  251. $item = $this->parseUserItem($userItem, $type = 'array_by_id', $prefix = 'f');
  252. foreach ($item as $fieldName => $value) {
  253. $item[$fieldName] = $this->validateAndFixField($fieldName, $value);
  254. }
  255. DBG::log(['userItem' => $userItem, 'item' => $item], 'array', "after parseUserItem, validateAndFixField");
  256. return $item;
  257. }
  258. public function parseUserItem($userItem, $type = 'array_by_id', $prefix = 'f') {
  259. $item = [];
  260. foreach ($this->getFieldListByIdZasob() as $userKey => $fieldName) {
  261. if (!array_key_exists("f{$userKey}", $userItem)) continue;
  262. $item[$fieldName] = $userItem["f{$userKey}"];
  263. }
  264. return $item;
  265. }
  266. public function validateAndFixField($fieldName, $value) {
  267. if (empty($value) && 0 === strlen($value)) {// TODO: fixEmptyValueFromUser
  268. return $this->fixFieldEmptyValue($fieldName);
  269. }
  270. $xsdType = $this->getXsdFieldType($fieldName);
  271. switch ($xsdType) {
  272. case 'xsd:decimal': return str_replace([',', ' '], ['.', ''], $value);
  273. case 'p5:price': return V::convert($value, 'price');
  274. }
  275. return $value;
  276. }
  277. public function fixFieldEmptyValue($fieldName) {// TODO: legacy - TODO: FIX
  278. return $this->getFieldDefaultValue($fieldName);
  279. // $value = '';
  280. // $xsdType = $this->getXsdFieldType($fieldName);
  281. // // $type = $this->getFieldType($fieldName); // TODO: RM
  282. // // if (!$type) return '';
  283. // if ('xsd:date' === $xsdType) return $this->getFieldDefaultValue($fieldName);
  284. // if ('xsd:integer' === $xsdType) return (int)$this->getFieldDefaultValue($fieldName);
  285. // // fix bug when field is unique and is null allowed: change empty string to null
  286. // if ($type['null']) {
  287. // $value = 'NULL';
  288. // }
  289. // // fix bug when field is enum and is set to '0': for php '0' is empty
  290. // if (substr($type['type'], 0, 4) == 'enum') {// && $args["f{$fieldID}"] === '0') {
  291. // // if (false !== strpos($type['type'], "''")) {
  292. // // // enum('', '1','2')
  293. // // $value = '';
  294. // // } else if (false !== strpos($type['type'], "'0'")) {
  295. // // // enum('0', '1','2')
  296. // // $value = '0';
  297. // // } else {
  298. // $value = $this->getFieldDefaultValue($fieldName);
  299. // // }
  300. // }
  301. // return $value;
  302. }
  303. public function isGeomField($fieldName) {
  304. return ('the_geom' === $fieldName); // TODO: check by xsdType
  305. }
  306. public function isEnumerationField($fieldName) {
  307. $xsdType = $this->getXsdFieldType($fieldName);
  308. if ('p5:enum' === $xsdType) return true;
  309. return false;
  310. }
  311. public function canCreateField($fieldName) {
  312. try {
  313. $fieldAclInfo = $this->getAclInfo($fieldName);
  314. DBG::log($fieldAclInfo, 'array', "AntAclBase: canReadField({$fieldName})...");
  315. return ($fieldAclInfo['PERM_C'] > 0);
  316. } catch (Exception $e) {
  317. DBG::log($e);
  318. return false;
  319. }
  320. return false;
  321. }
  322. public function canReadField($fieldName) {
  323. try {
  324. if ('A_RECORD_CREATE_DATE' === $fieldName) return true;
  325. if ('A_RECORD_CREATE_AUTHOR' === $fieldName) return true;
  326. if ('A_RECORD_UPDATE_DATE' === $fieldName) return true;
  327. if ('A_RECORD_UPDATE_AUTHOR' === $fieldName) return true;
  328. if ($this->getPrimaryKeyField() === $fieldName) return true;
  329. $fieldAclInfo = $this->getAclInfo($fieldName);
  330. DBG::log($fieldAclInfo, 'array', "AntAclBase: canReadField({$fieldName})...");
  331. return ($fieldAclInfo['PERM_R'] > 0 || $fieldAclInfo['PERM_V'] > 0 || $fieldAclInfo['PERM_O'] > 0);
  332. } catch (Exception $e) {
  333. DBG::log($e);
  334. return false;
  335. }
  336. return false;
  337. }
  338. public function canReadObjectField($fieldName, $object) {
  339. try {
  340. if ('A_RECORD_CREATE_DATE' === $fieldName) return true;
  341. if ('A_RECORD_CREATE_AUTHOR' === $fieldName) return true;
  342. if ('A_RECORD_UPDATE_DATE' === $fieldName) return true;
  343. if ('A_RECORD_UPDATE_AUTHOR' === $fieldName) return true;
  344. if ($this->getPrimaryKeyField() === $fieldName) return true;
  345. $fieldAclInfo = $this->getAclInfo($fieldName);
  346. DBG::log([$fieldAclInfo, 'V' => ($fieldAclInfo['PERM_V'] > 0), 'R'=>($fieldAclInfo['PERM_R'] > 0 && $this->canReadRecord($record)), 'O'=>($fieldAclInfo['PERM_O'] > 0 && $this->canReadRecord($record))], 'array', "AntAclBase: canWriteObjectField({$fieldName})...");
  347. if ($fieldAclInfo['PERM_V'] > 0) return true;
  348. if ($fieldAclInfo['PERM_R'] > 0 && $this->canReadRecord($record)) return true;
  349. if ($fieldAclInfo['PERM_O'] > 0 && $this->canReadRecord($record)) return true;
  350. } catch (Exception $e) {
  351. DBG::log($e);
  352. }
  353. return false;
  354. }
  355. public function canWriteField($fieldName) {
  356. try {
  357. $fieldAclInfo = $this->getAclInfo($fieldName);
  358. DBG::log($fieldAclInfo, 'array', "AntAclBase: canReadField({$fieldName})...");
  359. if ($fieldAclInfo['PERM_W'] > 0 || $fieldAclInfo['PERM_S'] > 0) return true;
  360. } catch (Exception $e) {
  361. DBG::log($e);
  362. }
  363. return false;
  364. }
  365. public function canWriteObjectField($fieldName, $record) {
  366. try {
  367. $fieldAclInfo = $this->getAclInfo($fieldName);
  368. DBG::log($fieldAclInfo, 'array', "AntAclBase: canWriteObjectField({$fieldName})...");
  369. DBG::log([$fieldAclInfo, 'S' => $fieldAclInfo['PERM_S'] > 0, 'W'=>$fieldAclInfo['PERM_W'], 'canWrite'=>$this->canWriteRecord($record), $record], 'array', "AntAclBase: canWriteObjectField({$fieldName})...");
  370. if ($fieldAclInfo['PERM_S'] > 0) return true;
  371. if ($fieldAclInfo['PERM_W'] > 0 && $this->canWriteRecord($record)) return true;
  372. } catch (Exception $e) {
  373. DBG::log($e);
  374. }
  375. return false;
  376. }
  377. public function getAclInfo($fieldName = null) {
  378. static $_aclInfo = []; // [ fieldName => [ id => {idZasob}, perms => 'RWX...' ] // TODO: , sort_prio => {SORT_PRIO}, label => {CELL_LABEL} ]
  379. if (!array_key_exists($this->getID(), $_aclInfo)) {
  380. $_aclInfo[ $this->getID() ] = [];
  381. $fieldsConfig = User::getAcl()->getPermsForTable($this->getID()); // @returns [ permInfo group by ID_CELL ]; permInfo = [ ID_CELL, CELL_NAME, CELL_LABEL, SORT_PRIO, PERM_R, PERM_W, PERM_... ]
  382. DBG::log($fieldsConfig, 'array', "AntAclBase: User::getAcl()->getPermsForTable(".$this->getID().");");
  383. // $this->initFieldsFromConfig($fieldsConfig);
  384. $permCols = [ 'PERM_R', 'PERM_W', 'PERM_X', 'PERM_C', 'PERM_S', 'PERM_O', 'PERM_V', 'PERM_E' ];
  385. foreach ($fieldsConfig as $row) {
  386. $nameField = $row['CELL_NAME'];
  387. $_aclInfo[ $this->getID() ][ $nameField ] = [
  388. 'idZasob' => $row['ID_CELL'],
  389. 'label' => $row['CELL_LABEL'],
  390. 'sort_prio' => $row['SORT_PRIO'],
  391. ];
  392. foreach ($permCols as $colPerm) $_aclInfo[ $this->getID() ][ $nameField ][ $colPerm ] = (int)$row[ $colPerm ];
  393. }
  394. }
  395. if ($fieldName && !array_key_exists($fieldName, $_aclInfo[ $this->getID() ])) {
  396. throw new Exception("Field not exists or missing access '{$fieldName}'");
  397. }
  398. return ($fieldName) ? $_aclInfo[ $this->getID() ][ $fieldName ] : $_aclInfo[ $this->getID() ];
  399. }
  400. public function hasFieldPerm($fieldID, $perm) { // TODO: legacy
  401. $field = $this->getField();
  402. if (!$field) return false;
  403. try {
  404. $fieldAclInfo = $this->getAclInfo($fieldName);
  405. DBG::log($fieldAclInfo, 'array', "AntAclBase: hasFieldPerm({$fieldName})...");
  406. if (!array_key_exists("PERM_{$perm}", $fieldAclInfo)) return false;
  407. return ($fieldAclInfo["PERM_{$perm}"] > 0);
  408. } catch (Exception $e) {
  409. DBG::log($e);
  410. }
  411. return false;
  412. }
  413. public function isAllowed($fieldID, $taskPerm, $record = null) {// TODO: legacy - replace with canWriteField, canReadField, canWriteObjectField, canReadObjectField, canCreateField
  414. $field = $this->getField($fieldID);
  415. if (!$field) return false;
  416. $fieldName = $field['name'];
  417. switch ($taskPerm) {
  418. case 'C': return false; // 'PERM_C'
  419. case 'R': return ($record) ? $this->canReadObjectField($fieldName, $record) : $this->canReadField($fieldName);
  420. case 'W': return ($record) ? $this->canWriteObjectField($fieldName, $record) : $this->canWriteField($fieldName);
  421. default: throw new Exception("Not Implemented isAllowed perm '{$taskPerm}'");
  422. }
  423. $adminFields = array();
  424. $adminFields[] = $this->getPrimaryKeyField();
  425. $adminFields[] = 'A_RECORD_CREATE_DATE';
  426. $adminFields[] = 'A_RECORD_CREATE_AUTHOR';
  427. $adminFields[] = 'A_RECORD_UPDATE_DATE';
  428. $adminFields[] = 'A_RECORD_UPDATE_AUTHOR';
  429. if ($taskPerm == 'R' && in_array($fieldName, $adminFields)) return true;
  430. if ($taskPerm == 'W' && in_array($fieldName, $adminFields)) return false;
  431. // check perm: allow 'RS', 'WS' - can R/W field even if cant read record
  432. // check 'O' - can read field even if cant read field but can read record
  433. DBG::log([
  434. 'record' => $record,
  435. 'canReadRecord' => $this->canReadRecord($record),
  436. 'hasFieldPerm(O) || canWriteRecord'=>'"'.$this->hasFieldPerm($fieldID, 'O').'" || "'.$this->canReadRecord($record).'"',
  437. 'hasFieldPerm(S)'=>'"'.$this->hasFieldPerm($fieldID, 'S').'"',
  438. 'hasFieldPerm(V)'=>'"'.$this->hasFieldPerm($fieldID, 'V').'"',
  439. ], 'array', "isAllowed({$fieldName}[{$fieldID}], {$taskPerm})");
  440. if (!$this->hasFieldPerm($fieldID, $taskPerm)) {
  441. if ($taskPerm == 'R' && $this->hasFieldPerm($fieldID, 'V')) {
  442. return true;
  443. } else if ($taskPerm == 'R'
  444. && $record
  445. && $this->hasFieldPerm($fieldID, 'O')
  446. && ($this->canReadRecord($record) || $this->canWriteRecord($record))
  447. ) {
  448. return true;// 'WO' or 'CO'
  449. }
  450. return false;
  451. }
  452. // check 'R' - require can read record, or V - Super View
  453. if ($taskPerm == 'R') {
  454. if ($this->canReadRecord($record) || $this->hasFieldPerm($fieldID, 'V')) {
  455. return true;
  456. } else {
  457. return false;
  458. }
  459. }
  460. // // 'C' and 'W' require colType
  461. // $colType = $this->getFieldTypeById($fieldID);
  462. // if (!$colType) {
  463. // return false;
  464. // }
  465. if ($taskPerm == 'W') {
  466. if ($record) {
  467. if(V::get('DBG_ACL', '', $_REQUEST) > 1){echo '(Field: '.$fieldID.', canWriteRecord: ' . $this->canWriteRecord($record) . ' || (hasFieldPerm(S): ' . $this->hasFieldPerm($fieldID, 'S') . ' && hasFieldPerm(W): ' . $this->hasFieldPerm($fieldID, 'W') . '))';}
  468. return ($this->canWriteRecord($record) || $this->hasFieldPerm($fieldID, 'S'));
  469. }
  470. }
  471. return true;
  472. }
  473. public function getFields() { // TODO: conflict return structure with TableAcl
  474. if (empty($this->_fields)) {
  475. // TODO: fetch fields from DB
  476. // Lib::loadClass('SchemaFactory');
  477. // $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
  478. // $item = $objectStorage->getItem($namespace, [
  479. // 'propertyName' => '*,field'
  480. // ]);
  481. }
  482. $fields = array_filter($this->_fields, function ($field) {
  483. return ($field['isActive']);
  484. });
  485. return array_map(function ($field) {
  486. $field['name'] = $field['fieldNamespace'];
  487. return $field;
  488. }, $fields);
  489. }
  490. public function _getField($fieldName) {
  491. foreach ($this->getFields() as $field) {
  492. if ($fieldName === $field['fieldNamespace']) return $field;
  493. }
  494. throw new Exception("Field not found '{$this->_namespace}/{$fieldName}'");
  495. }
  496. public function getSqlPrimaryKeyField() { return $this->_primaryKey; }
  497. public function getTotal($params = []) {
  498. DBG::log($params, 'array', "AntAclBase::getTotal params");
  499. $idInstance = ACL::getInstanceId($this->_namespace);
  500. $instanceTable = ACL::getInstanceTable($this->_namespace);
  501. $sqlPrimaryKey = $this->getSqlPrimaryKeyField();
  502. return DB::getPDO()->fetchValue(" -- getTotal({$this->_namespace})
  503. select count(1)
  504. from `{$this->_rootTableName}` t
  505. join `{$instanceTable}` i on(i.pk = t.{$sqlPrimaryKey} and i.idInstance = {$idInstance})
  506. ");
  507. }
  508. public function getItems($params = []) {
  509. DBG::log($params, 'array', "AntAclBase::getItems params");
  510. // $sql->limit = V::get('limit', 10, $params, 'int');
  511. // $sql->offset = V::get('limitstart', 0, $params, 'int');
  512. $limit = V::get('limit', 0, $params, 'int');
  513. $limit = ($limit < 0) ? 0 : $limit;
  514. $offset = V::get('limitstart', 0, $params, 'int');
  515. $offset = ($offset < 0) ? 0 : $offset;
  516. $sqlLimit = ($limit > 0)
  517. ? "limit {$limit} offset {$offset}"
  518. : '';
  519. $idInstance = ACL::getInstanceId($this->_namespace);
  520. $instanceTable = ACL::getInstanceTable($this->_namespace);
  521. $sqlPrimaryKey = $this->getSqlPrimaryKeyField();
  522. {
  523. $filtrIsInstance = [$this->_namespace];
  524. $filtrIsNotInstance = [];
  525. if (!empty($params['f_is_instance'])) $filtrIsInstance = $params['f_is_instance'];
  526. if (!empty($params['f_is_not_instance'])) $filtrIsNotInstance = $params['f_is_not_instance'];
  527. }
  528. return ACL::query($this)
  529. ->isInstance($filtrIsInstance)
  530. ->isNotInstance($filtrIsNotInstance)
  531. ->select('*') // TODO: fields
  532. ->select(!empty($params['@instances']) ? '@instances' : '')
  533. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPrimaryKey} and i.idInstance = {$idInstance}" ])
  534. ->limit($limit)
  535. ->offset($offset)
  536. ->execute();
  537. }
  538. public function getItem($primaryKey, $params = []) {
  539. return $this->buildQuery($params)->getItem($primaryKey);
  540. }
  541. public static function buildInstance($idZasob, $conf = []) {
  542. static $_cache;
  543. if (!$_cache) $_cache = array();
  544. if (array_key_exists($idZasob, $_cache)) {
  545. return $_cache[$idZasob];
  546. }
  547. if (empty($conf)) throw new Exception("Brak danych konfiguracyjnych do obiektu ant nr {$idZasob}");
  548. DBG::log($conf, 'array', 'AntAclBase::buildInstance $conf');
  549. $acl = new AntAclBase($idZasob);
  550. $acl->_name = $conf['name'];
  551. $acl->_rootTableName = $conf['_rootTableName'];
  552. $acl->_db = $conf['idDatabase'];
  553. $acl->_namespace = $conf['namespace'];
  554. $acl->_rootNamespace = str_replace('__x3A__', '/', $conf['nsPrefix']);
  555. $acl->_fields = $conf['field']; // TODO: lazyLoading - use getFields() in all functions - TODO: use ACL::getObjectFields
  556. $acl->_primaryKey = (!empty($conf['primaryKey'])) ? $conf['primaryKey'] : 'ID'; // $conf['primaryKey'];
  557. $_cache[$idZasob] = $acl;
  558. return $_cache[$idZasob];
  559. }
  560. public function buildQuery($params = array()) {
  561. Lib::loadClass('AclQueryFeatures');
  562. return new AclQueryFeatures($this, $params, $legacyMode = false);
  563. }
  564. public function getInstanceList() {
  565. $rootTableName = $this->_rootTableName;
  566. return array_map(function ($row) use ($rootTableName) {
  567. return $row['name'];
  568. }, SchemaFactory::loadDefaultObject('SystemObject')->getItems([
  569. 'propertyName' => 'name', // TODO: SystemObject fix propertyName
  570. 'f__rootTableName' => "={$rootTableName}",
  571. 'f__type' => "=AntAcl",
  572. 'f_isObjectActive' => "=1",
  573. ])
  574. );
  575. }
  576. public function getLocalFieldList() {
  577. return array_map(function ($field) {
  578. return $field['fieldNamespace'];
  579. }, array_filter($this->getFields(), function ($field) {
  580. return ($field['isLocal']);
  581. }));
  582. }
  583. public function isLocalField($fieldName) {
  584. return $this->_getField($fieldName)['isLocal'];
  585. }
  586. public function init($force = false) { }
  587. public function isInitialized($force = false) { return true; }
  588. public function updateItem($itemPatch) {
  589. if (is_object($itemPatch)) {
  590. $itemPatch = (array)$itemPatch;
  591. } else if (!is_array($itemPatch)) {
  592. throw new HttpException('Item patch is not array', 400);
  593. }
  594. if (empty($itemPatch)) {
  595. DBG::log("Item patch is empty - after validation");
  596. // throw new Exception('Item patch is empty');
  597. return 0;// nothing to change
  598. }
  599. $primaryKeyField = $this->getPrimaryKeyField();
  600. if (empty($itemPatch[$primaryKeyField])) throw new HttpException("Item Primary Key not set!", 400);
  601. $primaryKey = $itemPatch[$primaryKeyField];
  602. $itemOld = (array)$this->getItem($primaryKey);
  603. if (!$itemOld) throw new HttpException("Item not exists!", 404);
  604. if (!$this->canWriteRecord($itemOld) && !$this->hasPermSuperWrite()) throw new HttpException("Brak dostępu do rekordu", 403);
  605. // $itemPatch from user input to $validPatch
  606. $validPatch = array();
  607. DBG::log($itemPatch, 'array', "Item patch - before validation");
  608. foreach ($this->getFieldListByIdZasob() as $kID => $fieldName) {
  609. if (!array_key_exists($fieldName, $itemPatch)) continue;
  610. if (!$this->isAllowed($kID, 'W', $itemOld)) continue;
  611. // default value for perms 'W' without 'R' is '*****'
  612. if (!$this->isAllowed($kID, 'R', $itemOld) && '*****' == $itemPatch[$fieldName]) continue;
  613. $value = $itemPatch[$fieldName];
  614. if (empty($itemPatch[$fieldName]) && strlen($itemPatch[$fieldName]) == 0) {// fix bug in input type date and value="0000-00-00"
  615. $value = $this->fixFieldEmptyValue($fieldName);
  616. }
  617. if ($value != $itemOld[$fieldName]) {
  618. $validPatch[$fieldName] = $value;
  619. }
  620. }
  621. DBG::log($validPatch, 'array', "Item patch - after validation");
  622. if (empty($validPatch)) {
  623. DBG::log("Item patch is empty - after validation");
  624. // throw new Exception('Item patch is empty');
  625. return 0;// nothing to change
  626. }
  627. DBG::log($validPatch, 'array', "TODO: EDIT valid item patch");
  628. $affected = DB::getPDO()->update($this->getRootTableName(), $primaryKeyField, $primaryKey, array_merge(
  629. $validPatch,
  630. [
  631. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  632. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  633. ]
  634. ));
  635. if ($affected) {
  636. $affected += $this->saveUpdateHist(array_merge(
  637. $validPatch,
  638. [
  639. 'ID_USERS2' => $primaryKey,
  640. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  641. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  642. ]
  643. ));
  644. }
  645. return $affected;
  646. }
  647. public function saveUpdateHist($histPatch) {
  648. try {
  649. $idHist = DB::getPDO()->insert($this->getRootTableName() . '_HIST', $histPatch);
  650. } catch (Exception $e) {
  651. DBG::log($e);
  652. }
  653. }
  654. }