AntAclBase.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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->_zasobyInfoFetched = false;
  18. }
  19. public function getDB() { return $this->_db; }
  20. public function getName() { return $this->_name; }
  21. public function getNamespace() { return $this->_namespace; }
  22. public function getRootNamespace() { return $this->_rootNamespace; }
  23. public function getSourceName() { return 'default_db'; } // TODO: ?
  24. public function getRootTableName() { return $this->_rootTableName; }
  25. public function getPrimaryKeyField() { return $this->_primaryKey; }
  26. public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
  27. public function getVirtualFieldListByIdZasob() { return []; }
  28. public function _fetchInfoFromZasobyIfNeeded() {
  29. if (!$this->_zasobyInfoFetched) {
  30. $zasobyIds = array_filter(
  31. array_map(function ($field) {
  32. return (int)$field['idZasob'];
  33. }, $this->_fields),
  34. function ($id) { return $id > 0; }
  35. );
  36. if (!empty($zasobyIds)) {
  37. DBG::log("DBG sort fields - TODO: ids [".implode(",", $zasobyIds)."]");
  38. $zasobyInfo = DB::getPDO()->fetchAllByKey("
  39. select z.ID, z.DESC_PL, z.OPIS, z.SORT_PRIO
  40. from CRM_LISTA_ZASOBOW z
  41. where z.ID in(".implode(",", $zasobyIds).")
  42. ", 'ID');
  43. DBG::log($zasobyInfo, 'array', "DBG sort fields - zasobyInfo");
  44. $maxSortPrio = 0;
  45. array_map(function ($zInfo) use (&$maxSortPrio) {
  46. if ($zInfo['SORT_PRIO'] > 0 && $zInfo['SORT_PRIO'] > $maxSortPrio) {
  47. $maxSortPrio = $zInfo['SORT_PRIO'];
  48. }
  49. }, $zasobyInfo);
  50. foreach ($this->_fields as $idx => $field) {
  51. // $this->_fields[$idx]['name'] = $field['fieldNamespace']; // TODO: BUG query for non existing fields - check if isLocal is used
  52. if ($field['idZasob'] > 0 && array_key_exists($field['idZasob'], $zasobyInfo)) {
  53. $this->_fields[$idx]['sort_prio'] = $zasobyInfo[ $field['idZasob'] ]['SORT_PRIO'];
  54. if (!empty($zasobyInfo[ $field['idZasob'] ]['DESC_PL'])) $this->_fields[$idx]['label'] = $zasobyInfo[ $field['idZasob'] ]['DESC_PL'];
  55. if (!empty($zasobyInfo[ $field['idZasob'] ]['OPIS'])) $this->_fields[$idx]['opis'] = $zasobyInfo[ $field['idZasob'] ]['OPIS'];
  56. } else { // !$field['idZasob'] => generate sortPrio
  57. $this->_fields[$idx]['sort_prio'] = ++$maxSortPrio;
  58. }
  59. }
  60. }
  61. $this->_zasobyInfoFetched = true;
  62. }
  63. usort($this->_fields, array($this, '_sortFieldsCallback'));
  64. DBG::log($this->_fields, 'array', "DBG sort fields - sorted \$this->_fields");
  65. }
  66. public function _sortFieldsCallback($a, $b) {
  67. if ($a['name'] == 'ID') {
  68. return -1;
  69. }
  70. else if ($b['name'] == 'ID') {
  71. return 1;
  72. }
  73. else if ($a['sort_prio'] < $b['sort_prio']) {
  74. return -1;
  75. }
  76. else if ($a['sort_prio'] > $b['sort_prio']) {
  77. return 1;
  78. }
  79. else {
  80. return 0;
  81. }
  82. }
  83. public function getVisibleFieldListByIdZasob() {
  84. $this->_fetchInfoFromZasobyIfNeeded();
  85. $fields = $this->getRealFieldListByIdZasob();
  86. $pkField = $this->getPrimaryKeyField();
  87. $cols = array();
  88. foreach ($fields as $kFieldID => $fieldName) {
  89. if ($pkField === $fieldName) {
  90. $id = $kFieldID;
  91. break;
  92. }
  93. }
  94. $cols[$id] = $pkField; // 'ID'; // TODO: why rename primary key field to ID? check JS
  95. foreach ($fields as $kFieldID => $fieldName) {
  96. if ($pkField === $fieldName) continue;
  97. $cols[$kFieldID] = $fieldName;
  98. }
  99. return $cols;
  100. }
  101. public function getRealFieldListByIdZasob() {
  102. $cols = array();
  103. foreach ($this->getFields() as $field) {
  104. if (!$field['isActive']) continue;
  105. if (!$field['idZasob']) continue;
  106. $cols[ $field['idZasob'] ] = $field['fieldNamespace'];
  107. }
  108. return $cols;
  109. }
  110. public function getRealFieldList() {
  111. $pkField = $this->getPrimaryKeyField();
  112. $cols = array_merge([ $pkField ], array_filter($this->getLocalFieldList(), function ($fieldName) use ($pkField) {
  113. if ($pkField === $fieldName) return false;
  114. return true;
  115. }));
  116. return $cols;
  117. }
  118. public function getHistItems($id, $params = array()) {
  119. DBG::log($params, 'array', "getHistItems({$id}, \$params)");
  120. $sqlPkField = $this->getSqlPrimaryKeyField();
  121. $ret = array();
  122. $sql_tbl = $this->getRootTableName() . "_HIST";
  123. $sql_cols = array_map(function ($fieldName) {
  124. return "t.`{$fieldName}`";
  125. }, $this->getRealFieldList());
  126. $sql_cols = implode(", ", $sql_cols);
  127. $sql_where = "t.`ID_USERS2`='{$id}'";
  128. $idHist = V::get('ID', 0, $params, 'int');
  129. if ($idHist > 0) {
  130. $sql_where .= "\n and t.`ID`='{$idHist}'";
  131. }
  132. $paramNotEmptyFlds = V::get('notEmptyFlds', '', $params);
  133. if (!empty($paramNotEmptyFlds) && is_array($paramNotEmptyFlds)) {
  134. $sqlWhereOr = array();
  135. foreach ($paramNotEmptyFlds as $fldName) {
  136. if (array_key_exists($fldName, $this->_cols)) {
  137. $sqlWhereOr[] = "t.`{$fldName}`!='N/S;'";
  138. }
  139. }
  140. if (!empty($sqlWhereOr)) $sql_where .= "\n and (" . implode(" or ", $sqlWhereOr) . ")";
  141. }
  142. $histRows = DB::getPDO()->fetchAllByKey("
  143. select {$sql_cols}
  144. from {$sql_tbl} as t
  145. where {$sql_where}
  146. order by ID DESC
  147. ", 'ID');
  148. return array_map(function ($row) {
  149. $r = (object)$row;
  150. $r->_author = $r->A_RECORD_UPDATE_AUTHOR;
  151. $r->_created = $r->A_RECORD_UPDATE_DATE;
  152. if (!$r->_author || $r->_author == 'N/S;') {
  153. $r->_author = $r->A_RECORD_CREATE_AUTHOR;
  154. }
  155. if (!$r->_created || $r->_created == 'N/S;') {
  156. $r->_created = $r->A_RECORD_CREATE_DATE;
  157. }
  158. return $r;
  159. }, $histRows);
  160. }
  161. public function getFieldIdByName($fieldName) {
  162. if (!$fieldName) return null;
  163. $idZasob = null;
  164. foreach ($this->getFields() as $field) {
  165. if ($fieldName === $field['name']) {
  166. if ($field['idZasob']) $idZasob = $field['idZasob'];
  167. }
  168. }
  169. return $idZasob;
  170. }
  171. public function getFieldType($fieldName) { return null; }
  172. // try {
  173. // throw new Exception("TODO: AntAclBase::getFieldType({$fieldName})");
  174. // } catch (Exception $e) {
  175. // DBG::log($e);
  176. // }
  177. // $field = $this->_getField($fieldName);
  178. // return $field['xsdType'];
  179. // }
  180. public function getField($idField) {
  181. DBG::log($this->getFields(), 'array', "fields");
  182. foreach ($this->getFields() as $field) {
  183. if (!$field['isActive']) continue;
  184. if (!$field['idZasob']) continue;
  185. if ($idField == $field['idZasob']) {
  186. return $field;
  187. }
  188. }
  189. return null;
  190. }
  191. public function getXsdFieldType($fieldName) {
  192. $field = $this->_getField($fieldName);
  193. return $field['xsdType'];
  194. }
  195. public function getXsdMaxOccurs($fieldName) {
  196. $field = $this->_getField($fieldName);
  197. return $field['maxOccurs'];
  198. }
  199. public function getXsdMinOccurs($fieldName) {
  200. $field = $this->_getField($fieldName);
  201. return $field['minOccurs'];
  202. }
  203. public function getAttributesFromZasoby() {
  204. return [];// TODO: ...
  205. }
  206. public function getXsdFieldParam($fieldName, $paramKey) { // TODO: fetch from db
  207. return null;
  208. }
  209. // public function getXsdFieldParam($fieldName, $paramKey) { // TableAcl
  210. // return ($this->_schemaClass)
  211. // ? $this->_schemaClass->getFieldParam($fieldName, $paramKey)
  212. // : null
  213. // ;
  214. // }
  215. // public function getXsdFieldParam($fieldName, $paramKey) { // SimpleSchema
  216. // if (empty($this->_simpleSchema['root'][$fieldName])) return null;
  217. // if (empty($this->_simpleSchema['root'][$fieldName]['@@params'])) return null;
  218. // if (empty($this->_simpleSchema['root'][$fieldName]['@@params'][$paramKey])) return null;
  219. // return $this->_simpleSchema['root'][$fieldName]['@@params'][$paramKey];
  220. // }
  221. public function isGeomField($fieldName) {
  222. return ('the_geom' === $fieldName); // TODO: check by xsdType
  223. }
  224. public function isEnumerationField($fieldName) {
  225. return false; // TODO: ...
  226. }
  227. public function canWriteField($fieldName) {
  228. return false; // TODO: $this->getAclInfo($fieldName); @see canReadField
  229. }
  230. public function canCreateField($fieldName) {
  231. try {
  232. $fieldAclInfo = $this->getAclInfo($fieldName);
  233. DBG::log($fieldAclInfo, 'array', "AntAclBase: canReadField({$fieldName})...");
  234. return ($fieldAclInfo['PERM_C'] > 0);
  235. } catch (Exception $e) {
  236. DBG::log($e);
  237. return false;
  238. }
  239. return false;
  240. }
  241. public function canReadField($fieldName) {
  242. try {
  243. $fieldAclInfo = $this->getAclInfo($fieldName);
  244. DBG::log($fieldAclInfo, 'array', "AntAclBase: canReadField({$fieldName})...");
  245. return ($fieldAclInfo['PERM_R'] > 0 || $fieldAclInfo['PERM_V'] > 0 || $fieldAclInfo['PERM_O'] > 0);
  246. } catch (Exception $e) {
  247. DBG::log($e);
  248. return false;
  249. }
  250. return false;
  251. }
  252. public function canReadObjectField($fieldName, $object) {
  253. return true; // TODO: $this->getAclInfo($fieldName); @see canReadField
  254. }
  255. public function canWriteObjectField($fieldName, $record) {
  256. return false; // TODO: $this->getAclInfo($fieldName); @see canReadField
  257. }
  258. public function getAclInfo($fieldName = null) {
  259. static $_aclInfo = []; // [ fieldName => [ id => {idZasob}, perms => 'RWX...' ] // TODO: , sort_prio => {SORT_PRIO}, label => {CELL_LABEL} ]
  260. if (!array_key_exists($this->getID(), $_aclInfo)) {
  261. $_aclInfo[ $this->getID() ] = [];
  262. $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_... ]
  263. DBG::log($fieldsConfig, 'array', "AntAclBase: User::getAcl()->getPermsForTable(".$this->getID().");");
  264. // $this->initFieldsFromConfig($fieldsConfig);
  265. $permCols = [ 'PERM_R', 'PERM_W', 'PERM_X', 'PERM_C', 'PERM_S', 'PERM_O', 'PERM_V', 'PERM_E' ];
  266. foreach ($fieldsConfig as $row) {
  267. $nameField = $row['CELL_NAME'];
  268. $_aclInfo[ $this->getID() ][ $nameField ] = [
  269. 'idZasob' => $row['ID_CELL'],
  270. 'label' => $row['CELL_LABEL'],
  271. 'sort_prio' => $row['SORT_PRIO'],
  272. ];
  273. foreach ($permCols as $colPerm) $_aclInfo[ $this->getID() ][ $nameField ][ $colPerm ] = (int)$row[ $colPerm ];
  274. }
  275. }
  276. if ($fieldName && !array_key_exists($fieldName, $_aclInfo[ $this->getID() ])) {
  277. throw new Exception("Field not exists or missing access '{$fieldName}'");
  278. }
  279. return ($fieldName) ? $_aclInfo[ $this->getID() ][ $fieldName ] : $_aclInfo[ $this->getID() ];
  280. }
  281. public function getFields() { // TODO: conflict return structure with TableAcl
  282. if (empty($this->_fields)) {
  283. // TODO: fetch fields from DB
  284. // Lib::loadClass('SchemaFactory');
  285. // $objectStorage = SchemaFactory::loadDefaultObject('SystemObject');
  286. // $item = $objectStorage->getItem($namespace, [
  287. // 'propertyName' => '*,field'
  288. // ]);
  289. }
  290. $fields = array_filter($this->_fields, function ($field) {
  291. return ($field['isActive']);
  292. });
  293. return array_map(function ($field) {
  294. $field['name'] = $field['fieldNamespace'];
  295. return $field;
  296. }, $fields);
  297. }
  298. public function _getField($fieldName) {
  299. foreach ($this->getFields() as $field) {
  300. if ($fieldName === $field['fieldNamespace']) return $field;
  301. }
  302. throw new Exception("Field not found '{$this->_namespace}/{$fieldName}'");
  303. }
  304. public function getSqlPrimaryKeyField() { return $this->_primaryKey; }
  305. public function getTotal($params = []) {
  306. DBG::log($params, 'array', "AntAclBase::getTotal params");
  307. $idInstance = ACL::getInstanceId($this->_namespace);
  308. $instanceTable = ACL::getInstanceTable($this->_namespace);
  309. $sqlPrimaryKey = $this->getSqlPrimaryKeyField();
  310. return DB::getPDO()->fetchValue(" -- getTotal({$this->_namespace})
  311. select count(1)
  312. from `{$this->_rootTableName}` t
  313. join `{$instanceTable}` i on(i.pk = t.{$sqlPrimaryKey} and i.idInstance = {$idInstance})
  314. ");
  315. }
  316. public function getItems($params = []) {
  317. DBG::log($params, 'array', "AntAclBase::getItems params");
  318. // $sql->limit = V::get('limit', 10, $params, 'int');
  319. // $sql->offset = V::get('limitstart', 0, $params, 'int');
  320. $limit = V::get('limit', 0, $params, 'int');
  321. $limit = ($limit < 0) ? 0 : $limit;
  322. $offset = V::get('limitstart', 0, $params, 'int');
  323. $offset = ($offset < 0) ? 0 : $offset;
  324. $sqlLimit = ($limit > 0)
  325. ? "limit {$limit} offset {$offset}"
  326. : '';
  327. $idInstance = ACL::getInstanceId($this->_namespace);
  328. $instanceTable = ACL::getInstanceTable($this->_namespace);
  329. $sqlPrimaryKey = $this->getSqlPrimaryKeyField();
  330. {
  331. $filtrIsInstance = [$this->_namespace];
  332. $filtrIsNotInstance = [];
  333. if (!empty($params['f_is_instance'])) $filtrIsInstance = $params['f_is_instance'];
  334. if (!empty($params['f_is_not_instance'])) $filtrIsNotInstance = $params['f_is_not_instance'];
  335. }
  336. return ACL::query($this)
  337. ->isInstance($filtrIsInstance)
  338. ->isNotInstance($filtrIsNotInstance)
  339. ->select('*') // TODO: fields
  340. ->select(!empty($params['@instances']) ? '@instances' : '')
  341. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPrimaryKey} and i.idInstance = {$idInstance}" ])
  342. ->limit($limit)
  343. ->offset($offset)
  344. ->execute();
  345. }
  346. public function getItem($primaryKey, $params = []) {
  347. return $this->buildQuery($params)->getItem($primaryKey);
  348. }
  349. public static function buildInstance($idZasob, $conf = []) {
  350. static $_cache;
  351. if (!$_cache) $_cache = array();
  352. if (array_key_exists($idZasob, $_cache)) {
  353. return $_cache[$idZasob];
  354. }
  355. if (empty($conf)) throw new Exception("Brak danych konfiguracyjnych do obiektu ant nr {$idZasob}");
  356. DBG::log($conf, 'array', 'AntAclBase::buildInstance $conf');
  357. $acl = new AntAclBase($idZasob);
  358. $acl->_name = $conf['name'];
  359. $acl->_rootTableName = $conf['_rootTableName'];
  360. $acl->_db = $conf['idDatabase'];
  361. $acl->_namespace = $conf['namespace'];
  362. $acl->_rootNamespace = str_replace('__x3A__', '/', $conf['nsPrefix']);
  363. $acl->_fields = $conf['field']; // TODO: lazyLoading - use getFields() in all functions - TODO: use ACL::getObjectFields
  364. $acl->_primaryKey = (!empty($conf['primaryKey'])) ? $conf['primaryKey'] : 'ID'; // $conf['primaryKey'];
  365. $_cache[$idZasob] = $acl;
  366. return $_cache[$idZasob];
  367. }
  368. public function buildQuery($params = array()) {
  369. Lib::loadClass('AclQueryFeatures');
  370. return new AclQueryFeatures($this, $params, $legacyMode = false);
  371. }
  372. public function getInstanceList() {
  373. $rootTableName = $this->_rootTableName;
  374. return array_map(function ($row) use ($rootTableName) {
  375. return $row['name'];
  376. }, SchemaFactory::loadDefaultObject('SystemObject')->getItems([
  377. 'propertyName' => 'name', // TODO: SystemObject fix propertyName
  378. 'f__rootTableName' => "={$rootTableName}",
  379. 'f__type' => "=AntAcl",
  380. 'f_isObjectActive' => "=1",
  381. ])
  382. );
  383. }
  384. public function getLocalFieldList() {
  385. return array_map(function ($field) {
  386. return $field['fieldNamespace'];
  387. }, array_filter($this->getFields(), function ($field) {
  388. return ($field['isLocal']);
  389. }));
  390. }
  391. public function isLocalField($fieldName) {
  392. return $this->_getField($fieldName)['isLocal'];
  393. }
  394. public function init($force = false) { }
  395. public function isInitialized($force = false) { return true; }
  396. }