AntAclBase.php 28 KB

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