AntAclBase.php 30 KB

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