AntAclBase.php 31 KB

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