AclSimpleSchemaBase.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. <?php
  2. Lib::loadClass('Api_WfsNs');
  3. Lib::loadClass('Api_WfsException');
  4. Lib::loadClass('User');
  5. Lib::loadClass('Core_AclHelper');
  6. Lib::loadClass('Core_AclBase');
  7. // TODO: need PermProfile - array of perm profile list or just 'R,W,X,C,S', etc.
  8. class Core_AclSimpleSchemaBase extends Core_AclBase {
  9. /** simpleSchema - php structure:
  10. $simpleSchema = [
  11. 'root' => [
  12. '@namespace' => 'default_db/ZALICZKA/Zaliczka',
  13. '@primaryKey' => 'ID',
  14. 'ID' => 'xsd:integer', // short syntax - define only simpleType
  15. 'KWOTA' => [ // long syntax - define type with another params like restrictions
  16. '@type' => 'xsd:decimal'
  17. ],
  18. 'worker' => 'ref:Worker' // short syntax - define only type = ref
  19. 'pozycja' => [ // long syntax - define ref with maxOccurs, TODO: use more xsd attributes
  20. '@ref' => 'ZaliczkaPozycja',
  21. '@maxOccurs' => 'unbounded'
  22. ]
  23. ],
  24. 'Worker' => [
  25. '@namespace' => 'default_objects/AccessOwner',
  26. ...
  27. ],
  28. 'ZaliczkaPozycja' => [
  29. '@namespace' => 'default_db/ZALICZKA_POZYCJA/ZaliczkaPozycja',
  30. ...
  31. ]
  32. 'YT_LINK' => [ '@type' => 'p5:typeSpecialSimpleLink',
  33. '@label' => "Youtube link",
  34. '@@params' => [// $acl->getXsdFieldParam($col, 'format');
  35. 'format' => '<a href="https://www.youtube.com/watch?v={LINK}" target="_blank"></a>',
  36. 'aliasMap' => [
  37. 'LINK' => 'LINK'
  38. ]
  39. ]
  40. ],
  41. ]
  42. */
  43. public $_simpleSchema = array();
  44. public $_xsdTypes = null;// set by parseXsdTypes()
  45. public $_name = '';
  46. public $_namespace = '';
  47. public $_primaryKey = '';
  48. public $_rootTableName = '';
  49. public $_sourceNamespace = '';
  50. public $_xmlnsMap = [];
  51. public function __construct($simpleSchema = null) {
  52. if ($simpleSchema) $this->_simpleSchema = $simpleSchema;
  53. if (!$this->_simpleSchema) throw new Exception("Missing simpleSchema");
  54. if (empty($this->_simpleSchema['root'])) throw new Exception("Wrong simpleSchema syntax");
  55. if (empty($this->_simpleSchema['root']['@namespace'])) throw new Exception("Missing @namespace in simpleSchema");
  56. $this->_namespace = $this->_simpleSchema['root']['@namespace'];
  57. $ns = explode('/', $this->_namespace);
  58. $this->_name = end($ns);
  59. if (empty($this->_rootTableName)) {
  60. if (count($ns) < 3) throw new Exception("Wrong @namespace syntax in simpleSchema ns({$this->_simpleSchema['root']['@namespace']})");
  61. $this->_rootTableName = $ns[1];
  62. }
  63. {
  64. $this->_sourceNamespace = explode('/', $this->_namespace);
  65. array_pop($this->_sourceNamespace);// remove name
  66. $this->_sourceNamespace = implode('__x3A__', $this->_sourceNamespace);
  67. }
  68. if (empty($this->_simpleSchema['root']['@primaryKey'])) $this->_simpleSchema['root']['@primaryKey'] = 'ID';// TODO: throw new Exception("Missing @primaryKey in simpleSchema '{$this->_name}'");
  69. $this->_primaryKey = $this->_simpleSchema['root']['@primaryKey'];// TODO: check if field exists
  70. {// validate and fix _simpleSchema:
  71. // - convert field scalar to [ '@type' => ... ]
  72. // - check required @namespace attribute
  73. foreach ($this->_simpleSchema as $keySchema => $schema) {
  74. foreach ($schema as $fieldName => $params) {
  75. if ('@' == substr($fieldName, 0, 1)) continue;// skip params
  76. if (is_scalar($params)) {
  77. $this->_simpleSchema[ $keySchema ][ $fieldName ] = [ '@type' => $params ];
  78. } else if (!is_array($params)) {
  79. throw new Exception("Parse error - simpleSchema field type");
  80. }
  81. }
  82. if (empty($schema['@namespace'])) throw new Exception("Missing @namespace in schema for '{$keySchema}'");
  83. $ns = explode('/', $schema['@namespace']);
  84. $name = end($ns);
  85. if (count($ns) < 2) throw new Exception("Wrong @namespace syntax in schema for '{$keySchema}'");
  86. }
  87. }
  88. // $this->parseXsdTypes();// parse xsdTypes
  89. $this->_xsdTypes = array();
  90. {
  91. $generatedIdZasob = 10000; // fake zasob id
  92. foreach ($this->_simpleSchema['root'] as $key => $value) {
  93. if ('@' == substr($key, 0, 1)) continue;// skip attributes
  94. if (is_array($value)) {
  95. $fieldName = $key;
  96. $field = [ 'name' => $fieldName, 'perms' => '', 'idZasob' => $generatedIdZasob ];
  97. if (!empty($value['@label'])) $field['label'] = $value['@label'];
  98. if (!empty($value['@type'])) $field['xsdType'] = "{$value['@type']}";
  99. else if (!empty($value['@ref'])) {
  100. $field['xsdType'] = (false !== strpos($value['@ref'], '/'))
  101. ? "ref_uri:{$value['@ref']}"
  102. : "ref:{$value['@ref']}";
  103. }
  104. else throw new Exception("StorageAcl - field type not defined '{$key}'");
  105. if (!empty($value['@maxOccurs'])) $field['maxOccurs'] = $value['@maxOccurs'];
  106. $this->_xsdTypes[$fieldName] = $field;
  107. } else if (is_scalar($value)) {// short syntax: $fieldName => $xsdType
  108. $fieldName = $key;
  109. $field = [ 'name' => $fieldName, 'perms' => '', 'idZasob' => $generatedIdZasob ];
  110. $field['xsdType'] = $value;
  111. $this->_xsdTypes[$fieldName] = $field;
  112. } else {
  113. throw new Exception("StorageAcl - TODO: Unimplemented value type in simpleSchema: " . json_encode($value));
  114. }
  115. $generatedIdZasob++;
  116. }
  117. }
  118. // TODO: fix 'ref:*' types - use Core_AclHelper::parseNamespaceUrl($namespace)
  119. }
  120. public function getPDO() {
  121. return DB::getPDO( ($this->_idDatabase) ? $this->_idDatabase : '' );
  122. }
  123. public function __toString() {
  124. $out = "xsd @prefix(default_db__x3A__{$this->_rootTableName})" . "\n";
  125. $aliasRefUri = array();
  126. foreach ($this->_simpleSchema as $objectName => $schema) {
  127. if ('root' == $objectName) $objectName = $this->_name;
  128. $out .= "\t" . "{$objectName}";
  129. $out .= " @namespace({$schema['@namespace']})";
  130. $out .= "\n";
  131. foreach ($schema as $fieldName => $field) {
  132. if ('@' == substr($fieldName, 0, 1)) continue;// skip tags
  133. $out .= "\t\t" . "{$fieldName}";
  134. if (!empty($field['@type'])) {
  135. $out .= " @type({$field['@type']})";
  136. if (!empty($field['@alias'])) $out .= " @alias({$field['@alias']})";
  137. } else if (!empty($field['@ref'])) {
  138. $out .= " @ref({$field['@ref']})";
  139. if (false !== strpos($field['@ref'], '/')) $aliasRefUri[ $fieldName ] = $field['@ref'];
  140. } else {
  141. $out .= " @BUG('missing @type or @ref')";
  142. }
  143. // TODO: maxOccurs, nillable, etc.
  144. $out .= "\n";
  145. }
  146. foreach ($aliasRefUri as $fieldName => $nsUri) {
  147. $out .= "\t" . "{$objectName} @ref({$nsUri})" . "\n";
  148. // TODO: maxOccurs, nillable, etc.
  149. }
  150. }
  151. return $out;
  152. }
  153. public function hasSimpleSchema() { return true; }
  154. public function getSimpleSchema() { return $this->_simpleSchema; }
  155. public function getSimpleSchemaTree() {
  156. $tree = array();
  157. $tree['@namespace'] = $this->getNamespace();
  158. foreach ($this->getFieldsWithXsdTypes() as $fieldName => $field) {
  159. $tree[$fieldName] = $field;
  160. if (is_array($field) && 'ref_uri:' == substr($field['xsdType'], 0, 8)) {
  161. $tree[$fieldName] = $this->_getSimpleSchemaTreeRec(substr($field['xsdType'], 8), $this->getNamespace());
  162. }
  163. }
  164. return $tree;
  165. }
  166. public function _getSimpleSchemaTreeRec($ref, $namespacePath = '', $loopCount = 0) {
  167. if (++$loopCount > 100) die("Recurse limit in getSimpleSchemaTree for schema({$this->_namespace})");
  168. // echo "<p>DBG: F._getSimpleSchemaTreeRec({$ref}) \$namespacePath[$namespacePath]</p>";
  169. $tree = array();
  170. if (!empty($this->_simpleSchema[$ref])) {
  171. $tree = array();
  172. foreach ($this->_simpleSchema[$ref] as $fieldName => $field) {
  173. // echo "<p>DBG: F._getSimpleSchemaTreeRec({$ref}) \$namespacePath[$namespacePath] - 1/'{$fieldName}'</p>";
  174. $tree[$fieldName] = $field;
  175. if (is_array($field) && 'ref_uri:' == substr($field['xsdType'], 0, 8)) {
  176. $nsField = substr($field['xsdType'], 8);
  177. if (in_array($nsField, explode(',', $namespacePath))) {
  178. $tree[$fieldName]['@recurse_namespace'] = true;
  179. continue;
  180. }
  181. $tree[$fieldName] = $this->_getSimpleSchemaTreeRec($nsField, "{$namespacePath},{$nsField}", $loopCount);
  182. }
  183. }
  184. } else {
  185. $acl = Core_AclHelper::getAclByNamespace($ref);
  186. $tree['@namespace'] = $acl->getNamespace();
  187. foreach ($acl->getFieldsWithXsdTypes() as $fieldName => $field) {
  188. // echo "<p>DBG: F._getSimpleSchemaTreeRec({$ref}) \$namespacePath[$namespacePath] - 2/'{$fieldName}'</p>";
  189. $tree[$fieldName] = $field;
  190. if (is_array($field) && 'ref_uri:' == substr($field['xsdType'], 0, 8)) {
  191. $nsField = substr($field['xsdType'], 8);
  192. if (in_array($nsField, explode(',', $namespacePath))) {
  193. $tree[$fieldName]['@recurse_namespace'] = true;
  194. continue;
  195. }
  196. $tree[$fieldName] = $this->_getSimpleSchemaTreeRec($nsField, "{$namespacePath},{$nsField}", $loopCount);
  197. }
  198. }
  199. }
  200. // echo'<pre>F._getSimpleSchemaTreeRec('.$ref.') tree';print_r($tree);echo'</pre>';
  201. return $tree;
  202. }
  203. public function getName() { return $this->_name; }
  204. public function getRootTableName() { return $this->_rootTableName; }
  205. public function getXsdTypes() { // @returns [ fieldName => xsdType, ... ]
  206. return array_map(function ($field) {
  207. return $field['xsdType'];
  208. }, $this->_xsdTypes);
  209. }
  210. public function getFieldsWithXsdTypes() { return $this->_xsdTypes; } // @returns [ fieldName => [ 'xsdType' => , ... ], ... ]
  211. public function getNamespace() { return $this->_namespace; }
  212. public function getSourceName() { return $this->_sourceNamespace; }
  213. public function init($force = false) {}
  214. public function isInitialized() { return true; }
  215. public function getFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
  216. public function getVisibleFieldListByIdZasob() { return $this->getRealFieldListByIdZasob(); }
  217. public function getVirtualFieldListByIdZasob() { return array(); }
  218. public function getRealFieldListByIdZasob($force = false) {
  219. $cols = array();
  220. foreach ($this->getFields() as $idField => $field) {
  221. $cols[$idField] = $field['name'];
  222. }
  223. return $cols;
  224. }
  225. public function getFields() {// @returns array - $this->_fields
  226. $fieldsById = array();
  227. foreach ($this->getFieldsWithXsdTypes() as $fieldName => $field) {
  228. $field['name'] = $fieldName;
  229. $field['label'] = V::get('label', $fieldName, $field);
  230. if ('p5:www_link' == $field['xsdType']) $field['simpleType'] = 'p5:www_link';
  231. $fieldsById[ $field['idZasob'] ] = $field;
  232. }
  233. return $fieldsById;
  234. }
  235. public function getFieldType($fieldName) {
  236. foreach ($this->getFields() as $field) {
  237. if ($fieldName == $field['name']) return $field;
  238. }
  239. return null;
  240. }
  241. // TODO: replace legacy functions: isAllowed, hasFieldPerm, getFieldIdByName
  242. public function canCreateField($fieldName) { return false; }// TODO: perms from Procesy
  243. public function canReadField($fieldName) { return true; }// TODO: perms from Procesy
  244. public function canReadObjectField($fieldName, $record) { return true; }// TODO: perms from Procesy
  245. public function canWriteField($fieldName) { return false; }// TODO: perms from Procesy
  246. public function canWriteObjectField($fieldName, $record) { return false; }// TODO: perms from Procesy
  247. public function getTotal($params = array()) { throw new Exception("Unimplemented - TODO: " . get_class($this) . "::" . __FUNCTION__); }// TODO: use ParseOgcQuery
  248. public function getItem($primaryKey, $params = []) { throw new Exception("Unimplemented - TODO: " . get_class($this) . "::" . __FUNCTION__); }
  249. public function getItems($params = array()) { throw new Exception("Unimplemented - TODO: " . get_class($this) . "::" . __FUNCTION__); }// TODO: use ParseOgcQuery
  250. public function itemsFetchRefs(&$items) { throw new Exception("Unimplemented - TODO: " . get_class($this) . "::" . __FUNCTION__); }// TODO: , $fieldName = ''
  251. public function fetchItemFieldRefs($primaryKey, $fieldName) {
  252. $refTable = ACL::getRefTable($this->getNamespace(), $fieldName);
  253. $sqlPk = DB::getPDO()->quote($primaryKey, PDO::PARAM_STR);
  254. return array_map(
  255. function ($row) {
  256. return [
  257. 'xlink' => "{$row['REMOTE_TYPENAME']}.{$row['REMOTE_PRIMARY_KEY']}" // TODO:
  258. ];
  259. }
  260. , DB::getPDO()->fetchAll("
  261. select r.REMOTE_PRIMARY_KEY, r.REMOTE_TYPENAME
  262. from `{$refTable}` r
  263. where r.PRIMARY_KEY = {$sqlPk}
  264. and r.A_STATUS != 'DELETED'
  265. ")
  266. );
  267. }
  268. public function addItem($itemTodo) { throw new Exception("Unimplemented - TODO: " . get_class($this) . "::" . __FUNCTION__); }
  269. public function updateItem($itemPatch) { throw new Exception("Unimplemented - TODO: " . get_class($this) . "::" . __FUNCTION__); }
  270. public function getGeomFieldType($fieldName) { return null; }
  271. public function getPrimaryKeyField() { return $this->_primaryKey; }
  272. public function getSqlPrimaryKeyField() {
  273. return (!empty($this->_simpleSchema['root'][$this->_primaryKey]['@alias']))
  274. ? $this->_simpleSchema['root'][$this->_primaryKey]['@alias']
  275. : $this->_primaryKey;
  276. }
  277. public function getSqlFieldName($fieldName) {
  278. if (empty($this->_simpleSchema['root'][$fieldName])) throw new Exception("Missing field in schema '{$fieldName}'");
  279. return (!empty($this->_simpleSchema['root'][$fieldName]['@alias']))
  280. ? $this->_simpleSchema['root'][$fieldName]['@alias']
  281. : $fieldName;
  282. }
  283. public function getID() { return $this->_zasobID; }
  284. public function getAttributesFromZasoby() { return array(); }
  285. public function isEnumerationField($fieldName) { return false; }
  286. public function getEnumerations($fieldName) { return null; }
  287. public function getXsdFieldType($fieldName) {
  288. $xsdTypes = $this->getXsdTypes();
  289. if (empty($xsdTypes[$fieldName])) throw new Exception("Field '{$fieldName}' not exists");
  290. return $xsdTypes[$fieldName];
  291. }
  292. public function isGeomField($fieldName) {
  293. if ('File' == $fieldName) return false;
  294. if ('AccessGroupRead' == $fieldName) return false;
  295. if ('AccessGroupWrite' == $fieldName) return false;
  296. if ('AccessOwner' == $fieldName) return false;
  297. // if ('NestedObjectTest' == $fieldName) return false;
  298. // return $this->parentAcl->isGeomField($fieldName);
  299. }
  300. public function generateSqlSelectFromRootTable($prefix = 't') {
  301. $sqlSelect = [];
  302. foreach ($this->_simpleSchema['root'] as $key => $field) {
  303. if ('@' == substr($key, 0, 1)) continue;// skip attr
  304. if (!empty($field['@ref'])) continue;// skip ref
  305. if (empty($field['@type'])) continue;// skip wrong simpleType structure - BUG
  306. if ('xsd:' != substr($field['@type'], 0, 4)) continue;// skip non xsd types - eg. p5:typeSpecialSimpleLink
  307. $sqlKey = $this->getPDO()->identifierQuote($key);
  308. if (!empty($field['@aliasSql'])) {
  309. $sqlSelect[] = "{$field['@aliasSql']} as {$sqlKey}";
  310. } else {
  311. $sqlField = $this->getPDO()->identifierQuote( (!empty($field['@alias'])) ? $field['@alias'] : $key );
  312. $sqlSelect[] = "{$prefix}.{$sqlField} as {$sqlKey}";
  313. }
  314. }
  315. return implode("\n, ", $sqlSelect);
  316. }
  317. public function getXsdFieldParam($fieldName, $paramKey) {
  318. if (empty($this->_simpleSchema['root'][$fieldName])) return null;
  319. if (empty($this->_simpleSchema['root'][$fieldName]['@@params'])) return null;
  320. if (empty($this->_simpleSchema['root'][$fieldName]['@@params'][$paramKey])) return null;
  321. return $this->_simpleSchema['root'][$fieldName]['@@params'][$paramKey];
  322. }
  323. public function addP5Types(&$item) {
  324. DBG::_('DBG_ACL', '>1', "\$item", $item, __CLASS__, __FUNCTION__, __LINE__);
  325. $sqlSelect = [];
  326. foreach ($this->_simpleSchema['root'] as $key => $field) {
  327. if ('@' == substr($key, 0, 1)) continue;// skip attr
  328. if (empty($field['@type'])) continue;// skip ref
  329. if ('p5:' != substr($field['@type'], 0, 3)) continue;// skip non p5 types
  330. $fieldName = $key;
  331. $item[$fieldName] = '';
  332. switch ($field['@type']) {
  333. case 'p5:typeSpecialSimpleLink': {
  334. // '@@params' => [// $acl->getXsdFieldParam($col, 'format');
  335. // 'format' => '<a href="https://www.youtube.com/watch?v={LINK}" target="_blank"></a>',
  336. // 'aliasMap' => [
  337. // 'LINK' => 'LINK'
  338. // ]
  339. // ]
  340. $link = $this->getXsdFieldParam($fieldName, 'format');
  341. // $.each(_fieldProps._tsSimpleLink.aliasMap, function(i, v) {
  342. // //console.log('simpleLink aliasMap columnName:', columnName, 'i:', i, 'v:', v, 'props['+v+']', props[v], 'val', val, 'typeof val', typeof val);
  343. // if (undefined !== row[v]) {
  344. // valLink = valLink.replace(new RegExp('\{' + i + '\}', 'g'), row[v]);
  345. // }
  346. // });
  347. foreach ($this->getXsdFieldParam($fieldName, 'aliasMap') as $itemFieldName => $alias) {
  348. DBG::_('DBG_ACL', '>1', "aliasMap({$itemFieldName} => {$alias})", $item[$itemFieldName], __CLASS__, __FUNCTION__, __LINE__);
  349. if($itemFieldName=='LINK_PROBLEMS')
  350. $link = str_replace("{{$alias}}", $item[$itemFieldName], str_replace($link,'"','test') ); // bledy z cudzyslowami w <a href=\"mailto:?
  351. else
  352. $link = str_replace("{{$alias}}", $item[$itemFieldName], $link );
  353. }
  354. $item[$fieldName] = $link;
  355. } break;
  356. }
  357. }
  358. }
  359. public function getParamCols($params = []) {
  360. $filterCols = [];
  361. $cols = V::get('cols', [], $params);// wfs:propertyName
  362. if (empty($cols)) {// set default filter cols
  363. foreach ($this->_simpleSchema['root'] as $fieldName => $field) {
  364. if ('@' == substr($fieldName, 0, 1)) continue;
  365. if ('unbounded' == V::get('maxOccurs', '', $field)) continue;// TODO:?: default load only single value fields (skip maxOccurs="unbounded")?
  366. if (!empty($field['@type'])) {
  367. if ('xsd:' === substr($field['@type'], 0, 4)) $filterCols[$fieldName] = true;
  368. else if ('p5:' === substr($field['@type'], 0, 3)) $filterCols[$fieldName] = true;
  369. } else if (!empty($field['@ref'])) {
  370. $filterCols[$fieldName] = [];
  371. } else throw new Exception("Schema error for field '{$fieldName}' ns({$this->_namespace})");
  372. }
  373. } else {
  374. foreach ($cols as $fieldXPath) {
  375. if ('@' == substr($fieldXPath, 0, 1)) {// attr
  376. if ('@instance' === $fieldXPath) {
  377. $filterCols['@instance'] = true;
  378. } else {
  379. throw new Exception("Not implemented attribute name '{$fieldXPath}' in '{$this->_namespace}'");
  380. }
  381. } else if (false === strpos($fieldXPath, '/')) {// not xpath - field name
  382. if (!array_key_exists($fieldXPath, $this->_simpleSchema['root'])) throw new Exception("Field name '{$fieldXPath}' not exists in '{$this->_namespace}'");
  383. $field = $this->_simpleSchema['root'][$fieldXPath];
  384. if (!empty($field['@type'])) {
  385. $filterCols[$fieldXPath] = true;
  386. } else if (!empty($field['@ref'])) {
  387. $filterCols[$fieldXPath] = [];
  388. }
  389. } else {// is xpath
  390. list($fieldName, $subXPath) = explode('/', $fieldXPath, 2);// split only by first '/'
  391. $filterCols[$fieldXPath][$fieldName] = $subXPath;
  392. }
  393. }
  394. }
  395. return $filterCols;
  396. }
  397. public function buildFromSqlRow($row, $params = []) {
  398. $object = [];
  399. $filterCols = $this->getParamCols($params);
  400. // $object['_raw'] = $row;
  401. if (in_array('@instance', $filterCols)) {
  402. $object['@instance'] = '';
  403. // TODO: fetch instance names - InstanceConfig::???
  404. // $instanceTable = Core_AclHelper::getInstanceTable($this->getRootTableName());
  405. // $sqlPkFieldName = $this->getSqlPrimaryKeyField();
  406. // if (empty($row[$sqlPkFieldName])) throw new Exception("Missing primary key in ({$this->_namespace})");
  407. // $sqlPk = DB::getPDO()->quote($row[$sqlPkFieldName], PDO::PARAM_STR);
  408. // $object['@instance'] = DB::getPDO()->fetchValue("
  409. // select i.INSTANCE_NAME
  410. // from `{$instanceTable}` i
  411. // where i.PRIMARY_KEY = {$sqlPk}
  412. // ");// TODO: where i.`INSTANCE_TYPE` = 'instance' -- (i.`INSTANCE_TYPE` != 'derived')
  413. }
  414. foreach ($this->_simpleSchema['root'] as $fieldName => $field) {
  415. if ('@' == substr($fieldName, 0, 1)) continue;
  416. if (!array_key_exists($fieldName, $filterCols)) continue;// only filter cols
  417. if (!empty($field['@type'])) {
  418. // UI::alert('warning', "TODO: field({$fieldName}) type({$field['@type']})");
  419. if ('xsd:' === substr($field['@type'], 0, 4)) {
  420. $sqlFieldName = (!empty($field['@alias'])) ? $field['@alias'] : $fieldName;
  421. $object[$fieldName] = V::get($sqlFieldName, '', $row);
  422. } else if ('p5:enum' === $field['@type']) {
  423. $sqlFieldName = (!empty($field['@alias'])) ? $field['@alias'] : $fieldName;
  424. $object[$fieldName] = V::get($sqlFieldName, '', $row);
  425. } else if ('p5:' === substr($field['@type'], 0, 3)) {
  426. $object[$fieldName] = "TODO: generate value for type {$field['@type']} - field '{$fieldName}' ns({$this->_namespace})";// TODO: single field method like addP5Types
  427. } else throw new Exception("Not Implemented type for field '{$fieldName}' ns({$this->_namespace})");
  428. } else if (!empty($field['@ref'])) {
  429. // $object[$fieldName] = $this->fetchItemFieldRefs($primaryKey, $fieldName);
  430. $refTable = ACL::getRefTable($this->getNamespace(), $fieldName);
  431. $primaryKey = $row['ID'];// TODO: get primary key
  432. $sqlPk = DB::getPDO()->quote($primaryKey, PDO::PARAM_STR);
  433. $remoteIds = array_map(
  434. function ($row) {
  435. return $row['REMOTE_PRIMARY_KEY'];
  436. }
  437. , DB::getPDO()->fetchAll("
  438. select r.REMOTE_PRIMARY_KEY, r.REMOTE_TYPENAME
  439. from `{$refTable}` r
  440. where r.PRIMARY_KEY = {$sqlPk}
  441. and r.A_STATUS != 'DELETED'
  442. ")
  443. );
  444. $object[$fieldName] = (!empty($remoteIds))
  445. ? array_values(ACL::getAclByNamespace($field['@ref'])->getItems(['@primaryKey' => $remoteIds]))
  446. : [];
  447. } else throw new Exception("Schema error for field '{$fieldName}' ns({$this->_namespace})");
  448. }
  449. return $object;
  450. }
  451. public function getChildHistTable($childName) {
  452. if (empty($childName)) throw new Exception("Missing childName ('{$this->_namespace}')");
  453. if (!array_key_exists($childName, $this->_simpleSchema['root'])) throw new Exception("Field '{$childName}' not found in shema for '{$this->_namespace}'");
  454. if ('@' == substr($childName, 0, 1)) throw new Exception("Child hist table for attribute '{$childName}' not supported ('{$this->_namespace}')");
  455. // TODO: allow child for '@instance'
  456. $childSchema = $this->_simpleSchema['root'][$childName];
  457. return Core_AclHelper::getChildHistTable($this->getRootTableName(), $childName, $childSchema);
  458. }
  459. public function getEnumValues($childName) {
  460. $childSchema = $this->_simpleSchema['root'][$childName];
  461. DBG::log([
  462. 'msg' => 'dbg acl',
  463. 'sql field name' => $this->getSqlFieldName($childName),
  464. 'xsdType' => $this->getXsdFieldType($childName),
  465. 'childSchema' => $childSchema,
  466. ]);
  467. if ('p5:enum' == $this->getXsdFieldType($childName)) {
  468. if (!empty($this->_simpleSchema['root'][$childName]['@aliasFieldValues'])) {
  469. $aliasConf = $this->_simpleSchema['root'][$childName]['@aliasFieldValues'];
  470. $acl = Core_AclHelper::getAclByNamespace($aliasConf['namespace']);
  471. $sqlFldName = DB::getPDO()->quote($acl->getSqlFieldName($aliasConf['childName']), PDO::PARAM_STR);
  472. $sqlTblName = DB::getPDO()->quote($acl->getRootTableName(), PDO::PARAM_STR);
  473. $sqlDbName = DB::getPDO()->quote(DB::getPDO()->getDatabaseName(), PDO::PARAM_STR);
  474. } else {
  475. $sqlFldName = DB::getPDO()->quote($this->getSqlFieldName($childName), PDO::PARAM_STR);
  476. $sqlTblName = DB::getPDO()->quote($this->getRootTableName(), PDO::PARAM_STR);
  477. $sqlDbName = DB::getPDO()->quote(DB::getPDO()->getDatabaseName(), PDO::PARAM_STR);
  478. }
  479. $optionsEnum = DB::getPDO()->fetchValue("
  480. select COLUMN_TYPE
  481. from information_schema.COLUMNS c
  482. where c.COLUMN_NAME = {$sqlFldName}
  483. and c.TABLE_SCHEMA = {$sqlDbName}
  484. and c.TABLE_NAME = {$sqlTblName}
  485. ");
  486. if (!empty($optionsEnum)) {
  487. $optionsEnum = substr($optionsEnum, strlen('enum'));
  488. $optionsEnum = trim($optionsEnum, "()'");
  489. DBG::log(['msg' => '$optionsEnum', '$optionsEnum' => $optionsEnum]);
  490. return explode("','", $optionsEnum);
  491. }
  492. DBG::log(['msg' => 'Error empty options from enum field', '$optionsEnum' => $optionsEnum]);
  493. return null;
  494. }
  495. return null;
  496. }
  497. }