AntAclBase.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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 isDateField($fieldName) {
  355. $xsdType = $this->getXsdFieldType($fieldName);
  356. switch ($xsdType) {
  357. case "xsd:date": return true;
  358. default: return false;
  359. }
  360. }
  361. public function isDateTimeField($fieldName) {
  362. $xsdType = $this->getXsdFieldType($fieldName);
  363. switch ($xsdType) {
  364. case "xsd:dateTime": return true;
  365. default: return false;
  366. }
  367. }
  368. public function canCreateField($fieldName) {
  369. try {
  370. $fieldAclInfo = $this->getAclInfo($fieldName);
  371. // DBG::log($fieldAclInfo, 'array', "AntAclBase: canReadField({$fieldName})...");
  372. return ($fieldAclInfo['PERM_C'] > 0);
  373. } catch (Exception $e) {
  374. DBG::log($e);
  375. return false;
  376. }
  377. return false;
  378. }
  379. public function canReadField($fieldName) {
  380. try {
  381. if ('A_RECORD_CREATE_DATE' === $fieldName) return true;
  382. if ('A_RECORD_CREATE_AUTHOR' === $fieldName) return true;
  383. if ('A_RECORD_UPDATE_DATE' === $fieldName) return true;
  384. if ('A_RECORD_UPDATE_AUTHOR' === $fieldName) return true;
  385. if ($this->getPrimaryKeyField() === $fieldName) return true;
  386. $fieldAclInfo = $this->getAclInfo($fieldName);
  387. // DBG::log($fieldAclInfo, 'array', "AntAclBase: canReadField({$fieldName})...");
  388. return ($fieldAclInfo['PERM_R'] > 0 || $fieldAclInfo['PERM_V'] > 0 || $fieldAclInfo['PERM_O'] > 0);
  389. } catch (Exception $e) {
  390. DBG::log($e);
  391. return false;
  392. }
  393. return false;
  394. }
  395. public function canReadObjectField($fieldName, $object) {
  396. try {
  397. if ('A_RECORD_CREATE_DATE' === $fieldName) return true;
  398. if ('A_RECORD_CREATE_AUTHOR' === $fieldName) return true;
  399. if ('A_RECORD_UPDATE_DATE' === $fieldName) return true;
  400. if ('A_RECORD_UPDATE_AUTHOR' === $fieldName) return true;
  401. if ($this->getPrimaryKeyField() === $fieldName) return true;
  402. $fieldAclInfo = $this->getAclInfo($fieldName);
  403. // 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})...");
  404. if ($fieldAclInfo['PERM_V'] > 0) return true;
  405. if ($fieldAclInfo['PERM_R'] > 0 && $this->canReadRecord($object)) return true;
  406. if ($fieldAclInfo['PERM_O'] > 0 && $this->canReadRecord($object)) return true;
  407. } catch (Exception $e) {
  408. DBG::log($e);
  409. }
  410. return false;
  411. }
  412. public function canWriteField($fieldName) {
  413. try {
  414. $fieldAclInfo = $this->getAclInfo($fieldName);
  415. // DBG::log($fieldAclInfo, 'array', "AntAclBase: canReadField({$fieldName})...");
  416. if ($fieldAclInfo['PERM_W'] > 0 || $fieldAclInfo['PERM_S'] > 0) return true;
  417. } catch (Exception $e) {
  418. DBG::log($e);
  419. }
  420. return false;
  421. }
  422. public function canWriteObjectField($fieldName, $record) {
  423. try {
  424. $fieldAclInfo = $this->getAclInfo($fieldName);
  425. // DBG::log($fieldAclInfo, 'array', "AntAclBase: canWriteObjectField({$fieldName})...");
  426. DBG::log([$fieldAclInfo, 'S' => $fieldAclInfo['PERM_S'] > 0, 'W'=>$fieldAclInfo['PERM_W'], 'canWrite'=>$this->canWriteRecord($record), $record], 'array', "AntAclBase: canWriteObjectField({$fieldName})...");
  427. if ($fieldAclInfo['PERM_S'] > 0) return true;
  428. if ($fieldAclInfo['PERM_W'] > 0 && $this->canWriteRecord($record)) return true;
  429. } catch (Exception $e) {
  430. DBG::log($e);
  431. }
  432. return false;
  433. }
  434. public function getAclInfo($fieldName = null) {
  435. static $_aclInfo = []; // [ fieldName => [ id => {idZasob}, perms => 'RWX...' ] // TODO: , sort_prio => {SORT_PRIO}, label => {CELL_LABEL} ]
  436. if (!array_key_exists($this->getID(), $_aclInfo)) {
  437. $_aclInfo[ $this->getID() ] = [];
  438. $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_... ]
  439. // DBG::log($fieldsConfig, 'array', "AntAclBase: User::getAcl()->getPermsForTable(".$this->getID().");");
  440. // $this->initFieldsFromConfig($fieldsConfig);
  441. $permCols = [ 'PERM_R', 'PERM_W', 'PERM_X', 'PERM_C', 'PERM_S', 'PERM_O', 'PERM_V', 'PERM_E' ];
  442. foreach ($fieldsConfig as $row) {
  443. $nameField = $row['CELL_NAME'];
  444. $_aclInfo[ $this->getID() ][ $nameField ] = [
  445. 'idZasob' => $row['ID_CELL'],
  446. 'label' => $row['CELL_LABEL'],
  447. 'sort_prio' => $row['SORT_PRIO'],
  448. ];
  449. foreach ($permCols as $colPerm) $_aclInfo[ $this->getID() ][ $nameField ][ $colPerm ] = (int)$row[ $colPerm ];
  450. }
  451. }
  452. if ($fieldName && !array_key_exists($fieldName, $_aclInfo[ $this->getID() ])) {
  453. throw new Exception("Field not exists or missing access '{$fieldName}'");
  454. }
  455. return ($fieldName) ? $_aclInfo[ $this->getID() ][ $fieldName ] : $_aclInfo[ $this->getID() ];
  456. }
  457. public function hasFieldPerm($fieldID, $perm) { // TODO: legacy
  458. $field = $this->getField($fieldID);
  459. if (!$field) return false;
  460. try {
  461. $fieldAclInfo = $this->getAclInfo($fieldName);
  462. DBG::log($fieldAclInfo, 'array', "AntAclBase: hasFieldPerm({$fieldName})...");
  463. if (!array_key_exists("PERM_{$perm}", $fieldAclInfo)) return false;
  464. return ($fieldAclInfo["PERM_{$perm}"] > 0);
  465. } catch (Exception $e) {
  466. DBG::log($e);
  467. }
  468. return false;
  469. }
  470. public function isAllowed($fieldID, $taskPerm, $record = null) {// TODO: legacy - replace with canWriteField, canReadField, canWriteObjectField, canReadObjectField, canCreateField
  471. $field = $this->getField($fieldID);
  472. if (!$field) return false;
  473. $fieldName = $field['name'];
  474. switch ($taskPerm) {
  475. case 'C': return $this->canCreateField($fieldName);
  476. case 'R': return ($record) ? $this->canReadObjectField($fieldName, $record) : $this->canReadField($fieldName);
  477. case 'W': return ($record) ? $this->canWriteObjectField($fieldName, $record) : $this->canWriteField($fieldName);
  478. default: throw new Exception("Not Implemented isAllowed perm '{$taskPerm}'");
  479. }
  480. $adminFields = array();
  481. $adminFields[] = $this->getPrimaryKeyField();
  482. $adminFields[] = 'A_RECORD_CREATE_DATE';
  483. $adminFields[] = 'A_RECORD_CREATE_AUTHOR';
  484. $adminFields[] = 'A_RECORD_UPDATE_DATE';
  485. $adminFields[] = 'A_RECORD_UPDATE_AUTHOR';
  486. if ($taskPerm == 'R' && in_array($fieldName, $adminFields)) return true;
  487. if ($taskPerm == 'W' && in_array($fieldName, $adminFields)) return false;
  488. // check perm: allow 'RS', 'WS' - can R/W field even if cant read record
  489. // check 'O' - can read field even if cant read field but can read record
  490. DBG::log([
  491. 'record' => $record,
  492. 'canReadRecord' => $this->canReadRecord($record),
  493. 'hasFieldPerm(O) || canWriteRecord'=>'"'.$this->hasFieldPerm($fieldID, 'O').'" || "'.$this->canReadRecord($record).'"',
  494. 'hasFieldPerm(S)'=>'"'.$this->hasFieldPerm($fieldID, 'S').'"',
  495. 'hasFieldPerm(V)'=>'"'.$this->hasFieldPerm($fieldID, 'V').'"',
  496. ], 'array', "isAllowed({$fieldName}[{$fieldID}], {$taskPerm})");
  497. if (!$this->hasFieldPerm($fieldID, $taskPerm)) {
  498. if ($taskPerm == 'R' && $this->hasFieldPerm($fieldID, 'V')) {
  499. return true;
  500. } else if ($taskPerm == 'R'
  501. && $record
  502. && $this->hasFieldPerm($fieldID, 'O')
  503. && ($this->canReadRecord($record) || $this->canWriteRecord($record))
  504. ) {
  505. return true;// 'WO' or 'CO'
  506. }
  507. return false;
  508. }
  509. // check 'R' - require can read record, or V - Super View
  510. if ($taskPerm == 'R') {
  511. if ($this->canReadRecord($record) || $this->hasFieldPerm($fieldID, 'V')) {
  512. return true;
  513. } else {
  514. return false;
  515. }
  516. }
  517. // // 'C' and 'W' require colType
  518. // $colType = $this->getFieldTypeById($fieldID);
  519. // if (!$colType) {
  520. // return false;
  521. // }
  522. if ($taskPerm == 'W') {
  523. if ($record) {
  524. 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') . '))';}
  525. return ($this->canWriteRecord($record) || $this->hasFieldPerm($fieldID, 'S'));
  526. }
  527. }
  528. return true;
  529. }
  530. public function getFields() { // TODO: conflict return structure with TableAcl
  531. if (empty($this->_fields)) {
  532. // TODO: fetch fields from DB
  533. // Lib::loadClass('SchemaFactory');
  534. // $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
  535. // $item = $objectStorage->getItem($namespace, [
  536. // 'propertyName' => '*,field'
  537. // ]);
  538. }
  539. $fields = array_filter($this->_fields, function ($field) {
  540. return ($field['isActive']);
  541. });
  542. return array_map(function ($field) {
  543. $field['name'] = $field['fieldNamespace'];
  544. return $field;
  545. }, $fields);
  546. }
  547. public function _getField($fieldName) {
  548. if (!$fieldName) throw new Exception("Empty field name! '{$this->_namespace}'");
  549. foreach ($this->getFields() as $field) {
  550. if ($fieldName === $field['fieldNamespace']) return $field;
  551. }
  552. throw new Exception("Field '{$fieldName}' not found '{$this->_namespace}/{$fieldName}'");
  553. }
  554. public function getSqlPrimaryKeyField() { return $this->_primaryKey; }
  555. public function getSqlFieldName($fieldName) {
  556. $field = $this->_getField($fieldName);
  557. if ($field['isLocal']) return $field['fieldNamespace'];
  558. return $fieldName; // TODO: throw new Exception("Field is not local");
  559. }
  560. public function getTotal($params = []) {
  561. return $this->buildQuery($params)->getTotal();
  562. }
  563. public function getItems($params = []) {
  564. return $this->buildQuery($params)->getItems();
  565. }
  566. public function getItem($primaryKey, $params = []) {
  567. return $this->buildQuery($params)->getItem($primaryKey);
  568. }
  569. public static function buildInstance($idZasob, $conf = []) {
  570. static $_cache;
  571. if (!$_cache) $_cache = array();
  572. if (array_key_exists($idZasob, $_cache)) {
  573. return $_cache[$idZasob];
  574. }
  575. if (empty($conf)) throw new Exception("Brak danych konfiguracyjnych do obiektu ant nr {$idZasob}");
  576. DBG::log($conf, 'array', 'AntAclBase::buildInstance $conf');
  577. $acl = new AntAclBase($idZasob);
  578. $acl->_name = $conf['name'];
  579. $acl->_rootTableName = $conf['_rootTableName'];
  580. $acl->_db = $conf['idDatabase'];
  581. $acl->_namespace = $conf['namespace'];
  582. $acl->_rootNamespace = str_replace('__x3A__', '/', $conf['nsPrefix']);
  583. $acl->_fields = $conf['field']; // TODO: lazyLoading - use getFields() in all functions - TODO: use ACL::getObjectFields
  584. $acl->_primaryKey = (!empty($conf['primaryKey'])) ? $conf['primaryKey'] : 'ID'; // $conf['primaryKey'];
  585. $acl->_hasWriteGroupField = $conf['hasWriteGroupField'];
  586. $acl->_hasReadGroupField = $conf['hasReadGroupField'];
  587. $acl->_hasOwnerField = $conf['hasOwnerField'];
  588. $_cache[$idZasob] = $acl;
  589. return $_cache[$idZasob];
  590. }
  591. public function buildQuery($params = array()) {
  592. Lib::loadClass('AclQueryFeatures');
  593. return new AclQueryFeatures($this, $params);
  594. }
  595. public function getInstanceList() {
  596. $rootTableName = $this->_rootTableName;
  597. return array_map(function ($row) use ($rootTableName) {
  598. return $row['name'];
  599. }, SchemaFactory::loadDefaultObject('SystemObject')->getItems([
  600. 'propertyName' => 'name', // TODO: SystemObject fix propertyName
  601. 'f__rootTableName' => "={$rootTableName}",
  602. 'f__type' => "=AntAcl",
  603. 'f_isObjectActive' => "=1",
  604. ])
  605. );
  606. }
  607. public function getLocalFieldList() {
  608. return array_map(function ($field) {
  609. return $field['fieldNamespace'];
  610. }, array_filter($this->getFields(), function ($field) {
  611. return ($field['isLocal']);
  612. }));
  613. }
  614. public function isLocalField($fieldName) {
  615. return $this->_getField($fieldName)['isLocal'];
  616. }
  617. public function init($force = false) { }
  618. public function isInitialized($force = false) { return true; }
  619. public function addItem($itemTodo) {
  620. if (is_object($itemTodo)) {
  621. $itemTodo = (array)$itemTodo;
  622. } else if (!is_array($itemTodo)) {
  623. throw new HttpException('Item is not array', 400);
  624. }
  625. // from convertObjectFromUserInput - fixEmptyValueFromUser
  626. $item = array();
  627. $fields = $this->getFieldListByIdZasob();
  628. foreach ($fields as $kID => $vFieldName) {
  629. if (!$this->isAllowed($kID, 'C')) {
  630. continue;
  631. }
  632. if (isset($itemTodo[$vFieldName])) {
  633. $value = $itemTodo[$vFieldName];
  634. if (empty($value) && strlen($value) == 0) {// fix bug in input type date and value="0000-00-00"
  635. $value = $this->fixEmptyValueFromUser($kID);
  636. }
  637. $item[$vFieldName] = $value;
  638. }
  639. }
  640. {// add DefaultAclGroup if no create perms ('C')
  641. $defaultAclGroup = User::getDefaultAclGroup();
  642. if ($defaultAclGroup) {
  643. $permFields = array('A_ADM_COMPANY', 'A_CLASSIFIED');
  644. foreach ($permFields as $permFldName) {
  645. $permFldId = $this->getFieldIdByName($permFldName);
  646. if (0 == $permFldId || !$this->isAllowed($permFldId, 'C')) {
  647. $item[$permFldName] = $defaultAclGroup;
  648. }
  649. }
  650. }
  651. }
  652. DBG::log($item, 'array', "insert \$item");
  653. $idItem = DB::getPDO()->insert($this->getRootTableName(), array_merge($item, [
  654. 'A_RECORD_CREATE_DATE' => 'NOW()',
  655. 'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
  656. ]));
  657. if ($idItem) {
  658. DB::getPDO()->insert($this->getRootTableName() . '_HIST', array_merge($item, [
  659. 'ID_USERS2' => $idItem,
  660. 'A_RECORD_CREATE_DATE' => 'NOW()',
  661. 'A_RECORD_CREATE_AUTHOR' => User::getLogin(),
  662. ]));
  663. }
  664. return $idItem;
  665. }
  666. public function updateItem($itemPatch) {
  667. if (is_object($itemPatch)) {
  668. $itemPatch = (array)$itemPatch;
  669. } else if (!is_array($itemPatch)) {
  670. throw new HttpException('Item patch is not array', 400);
  671. }
  672. if (empty($itemPatch)) {
  673. DBG::log("Item patch is empty - after validation");
  674. // throw new Exception('Item patch is empty');
  675. return 0;// nothing to change
  676. }
  677. $primaryKeyField = $this->getPrimaryKeyField();
  678. if (empty($itemPatch[$primaryKeyField])) throw new HttpException("Item Primary Key not set!", 400);
  679. $primaryKey = $itemPatch[$primaryKeyField];
  680. $itemOld = (array)$this->getItem($primaryKey);
  681. if (!$itemOld) throw new HttpException("Item not exists!", 404);
  682. if (!$this->canWriteRecord($itemOld) && !$this->hasPermSuperWrite()) throw new HttpException("Brak dostępu do rekordu", 403);
  683. // $itemPatch from user input to $validPatch
  684. $validPatch = array();
  685. DBG::log($itemPatch, 'array', "Item patch - before validation");
  686. foreach ($this->getFieldListByIdZasob() as $kID => $fieldName) {
  687. if (!array_key_exists($fieldName, $itemPatch)) continue;
  688. if (!$this->isAllowed($kID, 'W', $itemOld)) continue;
  689. // default value for perms 'W' without 'R' is '*****'
  690. if (!$this->isAllowed($kID, 'R', $itemOld) && '*****' == $itemPatch[$fieldName]) continue;
  691. $value = $itemPatch[$fieldName];
  692. if (empty($itemPatch[$fieldName]) && strlen($itemPatch[$fieldName]) == 0) {// fix bug in input type date and value="0000-00-00"
  693. $value = $this->fixFieldEmptyValue($fieldName);
  694. }
  695. if ($value != $itemOld[$fieldName]) {
  696. $validPatch[$fieldName] = $value;
  697. }
  698. }
  699. DBG::log($validPatch, 'array', "Item patch - after validation");
  700. if (empty($validPatch)) {
  701. DBG::log("Item patch is empty - after validation");
  702. // throw new Exception('Item patch is empty');
  703. return 0;// nothing to change
  704. }
  705. DBG::log($validPatch, 'array', "TODO: EDIT valid item patch");
  706. $affected = DB::getPDO()->update($this->getRootTableName(), $primaryKeyField, $primaryKey, array_merge(
  707. $validPatch,
  708. [
  709. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  710. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  711. ]
  712. ));
  713. if ($affected) {
  714. $affected += $this->saveUpdateHist(array_merge(
  715. $validPatch,
  716. [
  717. 'ID_USERS2' => $primaryKey,
  718. 'A_RECORD_UPDATE_DATE' => 'NOW()',
  719. 'A_RECORD_UPDATE_AUTHOR' => User::getLogin(),
  720. ]
  721. ));
  722. }
  723. return $affected;
  724. }
  725. public function saveUpdateHist($histPatch) {
  726. try {
  727. $idHist = DB::getPDO()->insert($this->getRootTableName() . '_HIST', $histPatch);
  728. } catch (Exception $e) {
  729. DBG::log($e);
  730. }
  731. }
  732. public function hasWriteGroupField() { return $this->_hasWriteGroupField; }
  733. public function hasReadGroupField() { return $this->_hasReadGroupField; }
  734. public function hasOwnerField() { return $this->_hasOwnerField; }
  735. function getSpecialFilters() {
  736. $fltrs = array();
  737. $namespace = $this->getNamespace();
  738. $availableBackRefs = array_map(function($instance) {
  739. $exNs = explode('/', $instance['namespace']);
  740. $label = end($exNs);
  741. return [
  742. 'id' => $instance['idInstance'],
  743. 'namespace' => $instance['namespace'],
  744. 'label' => $label,
  745. ];
  746. }, ACL::getBackRefList($namespace));
  747. // [ 'id' => 41, 'namespace' => "default_db/TEST_PERMS/TestPermsAnt", 'label' => "TestPermsAnt" ],
  748. DBG::log($availableBackRefs, 'array', "\$availableBackRefs");
  749. $availableChildRefs = []; // TODO: ? show relation to child objects
  750. $availableChildRefs = array_map(function($instance) {
  751. $exNs = explode('/', $instance['namespace']);
  752. $label = end($exNs);
  753. return [
  754. 'id' => $instance['idInstance'],
  755. 'namespace' => $instance['namespace'],
  756. 'label' => $label,
  757. ];
  758. }, ACL::getRefList($namespace));
  759. DBG::log($availableChildRefs, 'array', "\$availableChildRefs");
  760. if (!empty($availableBackRefs) || !empty($availableChildRefs)) {
  761. $fltrs['Relations'] = (object)[
  762. 'type' => 'RELATIONS',
  763. 'icon' => 'glyphicon glyphicon-random',
  764. 'label' => 'Relacje',
  765. 'availableBackRefs' => $availableBackRefs,
  766. 'availableChildRefs' => $availableChildRefs,
  767. ];
  768. }
  769. return $fltrs;
  770. }
  771. function parseSpecialFilter($filter, $value) { // @return string | NULL
  772. if ('Ref_From_' === substr($filter, 0, strlen('Ref_From_'))) {
  773. return $this->parseSpecialFilterRefFrom(substr($filter, strlen('Ref_From_')), $value);
  774. }
  775. if ('Ref_To_' === substr($filter, 0, strlen('Ref_To_'))) {
  776. return $this->parseSpecialFilterRefTo(substr($filter, strlen('Ref_To_')), $value);
  777. }
  778. throw new Exception("Not Implemented special filter '{$filter}={$value}' ");
  779. }
  780. function parseSpecialFilterRefFrom($idInstance, $primaryKey) { // @return string | NULL
  781. $sqlPkField = $this->getSqlPrimaryKeyField();
  782. $parentNamespace = ACL::getInstanceNamespaceById($idInstance);
  783. $refTable = ACL::getRefTable($parentNamespace, Api_WfsNs::toTypeName($this->getNamespace()) );
  784. $sqlParentPk = DB::getPDO()->quote($primaryKey);
  785. return "
  786. t.{$sqlPkField} in (
  787. select `{$refAlias}`.REMOTE_PRIMARY_KEY
  788. from `{$refTable}` `{$refAlias}`
  789. where `{$refAlias}`.PRIMARY_KEY = {$sqlParentPk}
  790. )
  791. ";
  792. }
  793. function parseSpecialFilterRefTo($idInstance, $primaryKey) { // @return string | NULL
  794. $sqlPkField = $this->getSqlPrimaryKeyField();
  795. $childNamespace = ACL::getInstanceNamespaceById($idInstance);
  796. $refTable = ACL::getRefTable($this->getNamespace(), Api_WfsNs::toTypeName($childNamespace) );
  797. $sqlChildRefPk = DB::getPDO()->quote($primaryKey);
  798. return "
  799. t.{$sqlPkField} in (
  800. select refTable.PRIMARY_KEY
  801. from `{$refTable}` refTable
  802. where refTable.REMOTE_PRIMARY_KEY = {$sqlChildRefPk}
  803. )
  804. ";
  805. }
  806. function getRawLabel($posLimit = 100) {
  807. return substr( V::getValue( ACL::getAclLabel($this->_zasobID), $this->getName() ), 0, $posLimit );
  808. }
  809. function getOpis($posLimit = 1000) {
  810. return substr( V::getValue( ACL::getAclOpis($this->_zasobID), $this->getName() ), 0, $posLimit );
  811. }
  812. }