AntAclBase.php 27 KB

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