AntAclBase.php 28 KB

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