AntAclBase.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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. if (!$fieldName) throw new Exception("Empty field name! '{$this->_namespace}'");
  515. foreach ($this->getFields() as $field) {
  516. if ($fieldName === $field['fieldNamespace']) return $field;
  517. }
  518. throw new Exception("Field '{$fieldName}' not found '{$this->_namespace}/{$fieldName}'");
  519. }
  520. public function getSqlPrimaryKeyField() { return $this->_primaryKey; }
  521. public function getSqlFieldName($fieldName) {
  522. $field = $this->_getField($fieldName);
  523. if ($field['isLocal']) return $field['fieldNamespace'];
  524. return $fieldName; // TODO: throw new Exception("Field is not local");
  525. }
  526. public function getTotal($params = []) {
  527. return $this->buildQuery($params)->getTotal();
  528. }
  529. public function getItems($params = []) {
  530. return $this->buildQuery($params)->getItems();
  531. }
  532. public function getItem($primaryKey, $params = []) {
  533. return $this->buildQuery($params)->getItem($primaryKey);
  534. }
  535. public static function buildInstance($idZasob, $conf = []) {
  536. static $_cache;
  537. if (!$_cache) $_cache = array();
  538. if (array_key_exists($idZasob, $_cache)) {
  539. return $_cache[$idZasob];
  540. }
  541. if (empty($conf)) throw new Exception("Brak danych konfiguracyjnych do obiektu ant nr {$idZasob}");
  542. DBG::log($conf, 'array', 'AntAclBase::buildInstance $conf');
  543. $acl = new AntAclBase($idZasob);
  544. $acl->_name = $conf['name'];
  545. $acl->_rootTableName = $conf['_rootTableName'];
  546. $acl->_db = $conf['idDatabase'];
  547. $acl->_namespace = $conf['namespace'];
  548. $acl->_rootNamespace = str_replace('__x3A__', '/', $conf['nsPrefix']);
  549. $acl->_fields = $conf['field']; // TODO: lazyLoading - use getFields() in all functions - TODO: use ACL::getObjectFields
  550. $acl->_primaryKey = (!empty($conf['primaryKey'])) ? $conf['primaryKey'] : 'ID'; // $conf['primaryKey'];
  551. $acl->_hasWriteGroupField = $conf['hasWriteGroupField'];
  552. $acl->_hasReadGroupField = $conf['hasReadGroupField'];
  553. $acl->_hasOwnerField = $conf['hasOwnerField'];
  554. $_cache[$idZasob] = $acl;
  555. return $_cache[$idZasob];
  556. }
  557. public function buildQuery($params = array()) {
  558. Lib::loadClass('AclQueryFeatures');
  559. return new AclQueryFeatures($this, $params);
  560. }
  561. public function getInstanceList() {
  562. $rootTableName = $this->_rootTableName;
  563. return array_map(function ($row) use ($rootTableName) {
  564. return $row['name'];
  565. }, SchemaFactory::loadDefaultObject('SystemObject')->getItems([
  566. 'propertyName' => 'name', // TODO: SystemObject fix propertyName
  567. 'f__rootTableName' => "={$rootTableName}",
  568. 'f__type' => "=AntAcl",
  569. 'f_isObjectActive' => "=1",
  570. ])
  571. );
  572. }
  573. public function getLocalFieldList() {
  574. return array_map(function ($field) {
  575. return $field['fieldNamespace'];
  576. }, array_filter($this->getFields(), function ($field) {
  577. return ($field['isLocal']);
  578. }));
  579. }
  580. public function isLocalField($fieldName) {
  581. return $this->_getField($fieldName)['isLocal'];
  582. }
  583. public function init($force = false) { }
  584. public function isInitialized($force = false) { return true; }
  585. public function addItem($itemTodo) {
  586. if (is_object($itemTodo)) {
  587. $itemTodo = (array)$itemTodo;
  588. } else if (!is_array($itemTodo)) {
  589. throw new HttpException('Item is not array', 400);
  590. }
  591. // from convertObjectFromUserInput - fixEmptyValueFromUser
  592. $item = array();
  593. $fields = $this->getFieldListByIdZasob();
  594. foreach ($fields as $kID => $vFieldName) {
  595. if (!$this->isAllowed($kID, 'C')) {
  596. continue;
  597. }
  598. if (isset($itemTodo[$vFieldName])) {
  599. $value = $itemTodo[$vFieldName];
  600. if (empty($value) && strlen($value) == 0) {// fix bug in input type date and value="0000-00-00"
  601. $value = $this->fixEmptyValueFromUser($kID);
  602. }
  603. $item[$vFieldName] = $value;
  604. }
  605. }
  606. {// add DefaultAclGroup if no create perms ('C')
  607. $defaultAclGroup = User::getDefaultAclGroup();
  608. if ($defaultAclGroup) {
  609. $permFields = array('A_ADM_COMPANY', 'A_CLASSIFIED');
  610. foreach ($permFields as $permFldName) {
  611. $permFldId = $this->getFieldIdByName($permFldName);
  612. if (0 == $permFldId || !$this->isAllowed($permFldId, 'C')) {
  613. $item[$permFldName] = $defaultAclGroup;
  614. }
  615. }
  616. }
  617. }
  618. DBG::log($item, 'array', "insert \$item");
  619. $idItem = DB::getPDO()->insert($this->getRootTableName(), array_merge($item, [
  620. 'A_RECORD_CREATE_DATE' => 'NOW()',
  621. 'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
  622. ]));
  623. if ($idItem) {
  624. DB::getPDO()->insert($this->getRootTableName() . '_HIST', array_merge($item, [
  625. 'ID_USERS2' => $idItem,
  626. 'A_RECORD_CREATE_DATE' => 'NOW()',
  627. 'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
  628. ]));
  629. }
  630. return $idItem;
  631. }
  632. public function updateItem($itemPatch) {
  633. if (is_object($itemPatch)) {
  634. $itemPatch = (array)$itemPatch;
  635. } else if (!is_array($itemPatch)) {
  636. throw new HttpException('Item patch is not array', 400);
  637. }
  638. if (empty($itemPatch)) {
  639. DBG::log("Item patch is empty - after validation");
  640. // throw new Exception('Item patch is empty');
  641. return 0;// nothing to change
  642. }
  643. $primaryKeyField = $this->getPrimaryKeyField();
  644. if (empty($itemPatch[$primaryKeyField])) throw new HttpException("Item Primary Key not set!", 400);
  645. $primaryKey = $itemPatch[$primaryKeyField];
  646. $itemOld = (array)$this->getItem($primaryKey);
  647. if (!$itemOld) throw new HttpException("Item not exists!", 404);
  648. if (!$this->canWriteRecord($itemOld) && !$this->hasPermSuperWrite()) throw new HttpException("Brak dostępu do rekordu", 403);
  649. // $itemPatch from user input to $validPatch
  650. $validPatch = array();
  651. DBG::log($itemPatch, 'array', "Item patch - before validation");
  652. foreach ($this->getFieldListByIdZasob() as $kID => $fieldName) {
  653. if (!array_key_exists($fieldName, $itemPatch)) continue;
  654. if (!$this->isAllowed($kID, 'W', $itemOld)) continue;
  655. // default value for perms 'W' without 'R' is '*****'
  656. if (!$this->isAllowed($kID, 'R', $itemOld) && '*****' == $itemPatch[$fieldName]) continue;
  657. $value = $itemPatch[$fieldName];
  658. if (empty($itemPatch[$fieldName]) && strlen($itemPatch[$fieldName]) == 0) {// fix bug in input type date and value="0000-00-00"
  659. $value = $this->fixFieldEmptyValue($fieldName);
  660. }
  661. if ($value != $itemOld[$fieldName]) {
  662. $validPatch[$fieldName] = $value;
  663. }
  664. }
  665. DBG::log($validPatch, 'array', "Item patch - after validation");
  666. if (empty($validPatch)) {
  667. DBG::log("Item patch is empty - after validation");
  668. // throw new Exception('Item patch is empty');
  669. return 0;// nothing to change
  670. }
  671. DBG::log($validPatch, 'array', "TODO: EDIT valid item patch");
  672. $affected = DB::getPDO()->update($this->getRootTableName(), $primaryKeyField, $primaryKey, array_merge(
  673. $validPatch,
  674. [
  675. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  676. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  677. ]
  678. ));
  679. if ($affected) {
  680. $affected += $this->saveUpdateHist(array_merge(
  681. $validPatch,
  682. [
  683. 'ID_USERS2' => $primaryKey,
  684. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  685. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  686. ]
  687. ));
  688. }
  689. return $affected;
  690. }
  691. public function saveUpdateHist($histPatch) {
  692. try {
  693. $idHist = DB::getPDO()->insert($this->getRootTableName() . '_HIST', $histPatch);
  694. } catch (Exception $e) {
  695. DBG::log($e);
  696. }
  697. }
  698. public function hasWriteGroupField() { return $this->_hasWriteGroupField; }
  699. public function hasReadGroupField() { return $this->_hasReadGroupField; }
  700. public function hasOwnerField() { return $this->_hasOwnerField; }
  701. function getSpecialFilters() {
  702. $fltrs = array();
  703. $namespace = $this->getNamespace();
  704. $availableBackRefs = array_map(function($instance) {
  705. $exNs = explode('/', $instance['namespace']);
  706. $label = end($exNs);
  707. return [
  708. 'id' => $instance['idInstance'],
  709. 'namespace' => $instance['namespace'],
  710. 'label' => $label,
  711. ];
  712. }, ACL::getBackRefList($namespace));
  713. // [ 'id' => 41, 'namespace' => "default_db/TEST_PERMS/TestPermsAnt", 'label' => "TestPermsAnt" ],
  714. DBG::log($availableBackRefs, 'array', "\$availableBackRefs");
  715. $availableChildRefs = []; // TODO: ? show relation to child objects
  716. $availableChildRefs = array_map(function($instance) {
  717. $exNs = explode('/', $instance['namespace']);
  718. $label = end($exNs);
  719. return [
  720. 'id' => $instance['idInstance'],
  721. 'namespace' => $instance['namespace'],
  722. 'label' => $label,
  723. ];
  724. }, ACL::getRefList($namespace));
  725. DBG::log($availableChildRefs, 'array', "\$availableChildRefs");
  726. if (!empty($availableBackRefs) || !empty($availableChildRefs)) {
  727. $fltrs['Relations'] = (object)[
  728. 'type' => 'RELATIONS',
  729. 'icon' => 'glyphicon glyphicon-random',
  730. 'label' => 'Relacje',
  731. 'availableBackRefs' => $availableBackRefs,
  732. 'availableChildRefs' => $availableChildRefs,
  733. ];
  734. }
  735. return $fltrs;
  736. }
  737. function parseSpecialFilter($filter, $value) { // @return string | NULL
  738. if ('Ref_From_' === substr($filter, 0, strlen('Ref_From_'))) {
  739. return $this->parseSpecialFilterRefFrom(substr($filter, strlen('Ref_From_')), $value);
  740. }
  741. if ('Ref_To_' === substr($filter, 0, strlen('Ref_To_'))) {
  742. return $this->parseSpecialFilterRefTo(substr($filter, strlen('Ref_To_')), $value);
  743. }
  744. throw new Exception("Not Implemented special filter '{$filter}={$value}' ");
  745. }
  746. function parseSpecialFilterRefFrom($idInstance, $primaryKey) { // @return string | NULL
  747. $sqlPkField = $this->getSqlPrimaryKeyField();
  748. $parentNamespace = ACL::getInstanceNamespaceById($idInstance);
  749. $refTable = ACL::getRefTable($parentNamespace, Api_WfsNs::toTypeName($this->getNamespace()) );
  750. $sqlParentPk = DB::getPDO()->quote($primaryKey);
  751. return "
  752. t.{$sqlPkField} in (
  753. select `{$refAlias}`.REMOTE_PRIMARY_KEY
  754. from `{$refTable}` `{$refAlias}`
  755. where `{$refAlias}`.PRIMARY_KEY = {$sqlParentPk}
  756. )
  757. ";
  758. }
  759. function parseSpecialFilterRefTo($idInstance, $primaryKey) { // @return string | NULL
  760. $sqlPkField = $this->getSqlPrimaryKeyField();
  761. $childNamespace = ACL::getInstanceNamespaceById($idInstance);
  762. $refTable = ACL::getRefTable($this->getNamespace(), Api_WfsNs::toTypeName($childNamespace) );
  763. $sqlChildRefPk = DB::getPDO()->quote($primaryKey);
  764. return "
  765. t.{$sqlPkField} in (
  766. select refTable.PRIMARY_KEY
  767. from `{$refTable}` refTable
  768. where refTable.REMOTE_PRIMARY_KEY = {$sqlChildRefPk}
  769. )
  770. ";
  771. }
  772. function getRawLabel($posLimit = 100) {
  773. return substr( V::getValue( ACL::getAclLabel($this->_zasobID), $this->getName() ), 0, $posLimit );
  774. }
  775. function getOpis($posLimit = 1000) {
  776. return substr( V::getValue( ACL::getAclOpis($this->_zasobID), $this->getName() ), 0, $posLimit );
  777. }
  778. }