AclQueryFeatures.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. <?php
  2. Lib::loadClass('ACL');
  3. Lib::loadClass('SqlQueryWhereBuilder');
  4. Lib::loadClass('ParseOgcFilter');
  5. Lib::loadClass('TableAcl');
  6. // usage: (Acl class)::buildQuery($params): return new AclQueryFeatures($this, $params);
  7. // (view): $queryFeatures = $acl->buildQuery($params);
  8. // (view): $total = $queryFeatures->getTotal();
  9. // (view): $items = $queryFeatures->getItems();
  10. // example: @see TableAcl, TableAjax
  11. // Special Filter Access - btns visible only if user don't have super access perms. If has, then will always see all rows.
  12. class AclQueryFeatures {
  13. public $_params;
  14. public $_acl;
  15. public $_query;
  16. public $_total;
  17. public $_legacyMode;
  18. public $_selectLocalFields; // TODO: leave here or move to AclQueryBuilder? use join for perf?
  19. public $_selectRemote; // TODO: ...
  20. public function __construct($acl, $params, $legacyMode = false) {
  21. $this->_acl = $acl;
  22. $this->_params = $params;
  23. $this->_query = null;
  24. $this->_total = null;
  25. $this->_legacyMode = $legacyMode;
  26. // TODO: _legacyMode = ($from instanceof simple schema or another programmed objects)
  27. $this->_selectLocalFields = null;
  28. $this->_selectRemote = null;
  29. }
  30. public function parseQueryValue($fieldName, $searchQuery, $fieldType = 'xsd:string') {
  31. if ('!NULL' === $searchQuery) return ['is not null', null];
  32. if ('IS NOT NULL' === $searchQuery) return ['is not null', null];
  33. if ('NULL' === $searchQuery) return ['is null', null];
  34. if ('IS NULL' === $searchQuery) return ['is null', null];
  35. switch ($fieldType) {
  36. case 'gml:PolygonPropertyType':
  37. case 'gml:PointPropertyType':
  38. case 'gml:LineStringPropertyType':
  39. case 'gml:GeometryPropertyType': return $this->_parseGeomQuery($searchQuery);
  40. // $sqlFilter = $this->_sqlValueForGeomField($fldName, $v, 't');
  41. // if ('_CSV_NUM' == substr($fldName, -8)) { // if ($this->isCsvNumericField($fldName)) { // TODO: xsd type - p5:csv_num
  42. // $sqlFilter = $this->_sqlValueForCsvNumericField($fldName, $v, 't');
  43. // if ($sqlFilter) $sql_where_and[] = $sqlFilter;
  44. // continue;
  45. // }
  46. }
  47. switch (substr($searchQuery, 0, 1)) {
  48. case '=': return ['=', substr($searchQuery, 1)];
  49. case '>':
  50. switch (substr($searchQuery, 1, 1)) {
  51. case '=': return ['>=', substr($searchQuery, 2)];
  52. default: return ['>', substr($searchQuery, 1)];
  53. }
  54. case '<':
  55. switch (substr($searchQuery, 1, 1)) {
  56. case '=': return ['<=', substr($searchQuery, 2)];
  57. case '>': return ['!=', substr($searchQuery, 2)];
  58. default: return ['<', substr($searchQuery, 1)];
  59. }
  60. case '!':
  61. switch (substr($searchQuery, 1, 1)) {
  62. case '=': return ['!=', substr($searchQuery, 2)];
  63. default: return ['not like', substr($searchQuery, 1)];
  64. }
  65. default: {
  66. switch ($fieldType) {
  67. case 'xsd:number':
  68. case 'xsd:int':
  69. case 'xsd:integer': {
  70. if (false !== strpos($searchQuery, '%')) return ['like', $searchQuery];
  71. return ['=', $searchQuery];
  72. }
  73. default: {
  74. if (false !== strpos($searchQuery, '%')) return ['like', $searchQuery];
  75. $queryWhereBuilder = new SqlQueryWhereBuilder();
  76. return ['and'
  77. , array_map(function ($word) use ($fieldName) {
  78. return [$fieldName, 'like', "%{$word}%"];
  79. }, $queryWhereBuilder->splitQueryToWords($searchQuery)
  80. )
  81. ];
  82. }
  83. }
  84. return ['=', $searchQuery];
  85. }
  86. }
  87. }
  88. public function _parseGeomQuery($searchQuery) { // _sqlValueForGeomField($fldName, $fltrValue, $tblPrefix = 't')
  89. // example: BBOX:54.40993961633866,18.583889010112824,54.337945760687454,18.397121431987586
  90. DBG::log($searchQuery, 'string', "\$searchQuery");
  91. if ('BBOX:' == substr($searchQuery, 0, 5)) {
  92. $valParts = explode(',', substr($searchQuery, 5));
  93. if (4 !== count($valParts)) throw new Exception("Wrong BBOX query");
  94. $valParts = array_filter($valParts, 'is_numeric');
  95. if (4 !== count($valParts)) throw new Exception("Wrong BBOX query - expected 4 numeric values");
  96. $bounds = "POLYGON((
  97. {$valParts[3]} {$valParts[2]},
  98. {$valParts[3]} {$valParts[0]},
  99. {$valParts[1]} {$valParts[0]},
  100. {$valParts[1]} {$valParts[2]},
  101. {$valParts[3]} {$valParts[2]}
  102. ))";
  103. // for mysql 5.6 use ST_Contains() @see http://dev.mysql.com/doc/refman/5.6/en/spatial-relation-functions.html
  104. return [ 'Intersects', $bounds ];
  105. }
  106. else if ('GeometryType=' == substr($fltrValue, 0, 13)) {
  107. return [ 'GeometryType', substr($fltrValue, 13) ];
  108. }
  109. throw new Exception("Not implemented geometry query string"); // TODO:? return null;
  110. }
  111. public function _sqlValueForCsvNumericField($fldName, $fltrValue, $tblPrefix = 't') {
  112. $sqlFilter = false;
  113. if (is_numeric($fltrValue)) {
  114. $sqlFilter = "FIND_IN_SET('{$fltrValue}', `{$fldName}`)>0";
  115. } else if (false !== strpos($fltrValue, ' ')) {
  116. $sqlGlue = " or ";
  117. $fltrValues = $fltrValue;
  118. if ('&' == substr($fltrValues, 0, 1)) {
  119. $fltrValues = substr($fltrValues, 1);
  120. $sqlGlue = " and ";
  121. }
  122. $fltrValues = explode(' ', $fltrValues);
  123. $sqlNumericValues = array();
  124. foreach ($fltrValues as $fltrVal) {
  125. if (is_numeric($fltrVal)) {
  126. $sqlNumericValues[] = "FIND_IN_SET('{$fltrVal}', `{$fldName}`)>0";
  127. }
  128. }
  129. if (!empty($sqlNumericValues)) {
  130. $sqlFilter = "(" . implode($sqlGlue, $sqlNumericValues) . ")";
  131. }
  132. }
  133. return $sqlFilter;
  134. }
  135. public function parseSpecialFilterMsgs($type) {
  136. $rootTableName = $this->_acl->getRootTableName();
  137. DBG::log($rootTableName, 'string', "parse SpecialFilter Msgs({$type}), \$rootTableName");
  138. $sqlHasFltrMsgs = "
  139. select 1
  140. from `CRM_UI_MSGS` m
  141. where m.`uiTargetName`=CONCAT('{$rootTableName}.', t.`ID`)
  142. and m.`uiTargetType`='default_db_table_record'
  143. and m.`A_STATUS` not in('DELETED')
  144. limit 1
  145. ";
  146. switch ($type) {
  147. case 'HAS_MSGS': return " ({$sqlHasFltrMsgs})=1 ";
  148. case 'NO_MSGS': return " ({$sqlHasFltrMsgs}) is null ";
  149. case 'NEW_MSGS': {
  150. $sqlNewFltrMsgs = "
  151. select 1
  152. from `CRM_UI_MSGS` m
  153. where m.`uiTargetName`=CONCAT('{$rootTableName}.', t.`ID`)
  154. and m.`uiTargetType`='default_db_table_record'
  155. and m.`A_STATUS` in('WAITING')
  156. limit 1
  157. ";
  158. return " ({$sqlNewFltrMsgs})=1 ";
  159. }
  160. }
  161. return null;
  162. }
  163. public function parseSpecialFilterProblemy($type) {
  164. DBG::log($type, 'string', "parse SpecialFilter Problemy");
  165. switch ($type) {
  166. case 'PROBLEM': return ['A_PROBLEM', '!=', ''];
  167. case 'WARNING': return ['A_PROBLEM', '=', 'WARNING'];
  168. case 'NORMAL': return ['A_PROBLEM', '=', 'NORMAL'];
  169. }
  170. return null;
  171. }
  172. public function parseSpecialFilterStatus($type) {
  173. DBG::log($type, 'string', "parse SpecialFilter Status");
  174. switch ($type) {
  175. case 'WAITING': return ['A_STATUS', '=', 'WAITING'];
  176. case 'AKTYWNI': return ['A_STATUS', 'or', [ // `A_STATUS` in('NORMAL', 'WARNING') ";
  177. ['A_STATUS', '=', 'NORMAL'],
  178. ['A_STATUS', '=', 'WARNING'],
  179. ] ];
  180. }
  181. return null;
  182. }
  183. public function parseSpecialFilterSpotkania($type) {
  184. DBG::log($type, 'string', "parse SpecialFilter Spotkania");
  185. switch ($type) {
  186. case 'OLD': return ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_LESS_THAN_NOW'];
  187. // COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < UNIX_TIMESTAMP()
  188. // and t.`L_APPOITMENT_DATE` != ''
  189. // and t.`L_APPOITMENT_DATE` != '0000-00-00 00:00:00'
  190. case 'NOW': return ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_NOW_3600'];
  191. // COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < UNIX_TIMESTAMP()+3600
  192. // and COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) > UNIX_TIMESTAMP()-3600
  193. case 'TODAY': return ['L_APPOITMENT_DATE', 'and', [
  194. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_GREATER_THAN', mktime(0,0,0, date("m"), date("d"), date("Y"))],
  195. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_LESS_THAN', mktime(0,0,0, date("m"), date("d") + 1, date("Y"))],
  196. ] ];
  197. // $start = mktime(0,0,0, date("m"), date("d"), date("Y"));
  198. // $end = mktime(0,0,0, date("m"), date("d") + 1, date("Y"));
  199. // $sqlFltr = "
  200. // COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) > '{$start}'
  201. // and COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < '{$end}'
  202. // ";
  203. case 'TOMORROW': return ['L_APPOITMENT_DATE', 'and', [
  204. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_GREATER_THAN', mktime(0,0,0, date("m"), date("d") + 1, date("Y"))],
  205. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_LESS_THAN', mktime(0,0,0, date("m"), date("d") + 2, date("Y"))],
  206. ] ];
  207. case 'YESTERDAY': return ['L_APPOITMENT_DATE', 'and', [
  208. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_GREATER_THAN', mktime(0,0,0, date("m"), date("d") - 2, date("Y"))],
  209. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_LESS_THAN', mktime(0,0,0, date("m"), date("d") - 1, date("Y"))],
  210. ] ];
  211. case 'BRAK': return ['L_APPOITMENT_DATE', 'or', [
  212. ['L_APPOITMENT_DATE', '=', ''],
  213. ['L_APPOITMENT_DATE', '=', '0000-00-00 00:00:00'],
  214. ] ];
  215. }
  216. return null;
  217. }
  218. public function parseSpecialFilterAccess() {
  219. $userLogin = User::getLogin();
  220. $usrAclGroups = User::getLdapGroupsNames();
  221. DBG::log(['login'=>$userLogin, 'groups'=>$usrAclGroups, 'hasFieldWrite'=>$this->_acl->hasField('A_ADM_COMPANY'), 'hasFieldRead'=>$this->_acl->hasField('A_CLASSIFIED'), 'acl'=>$this->_acl], 'array', "parse SpecialFilter Access");
  222. $orWhere = [];
  223. if ($this->_acl->hasField('A_ADM_COMPANY')) {
  224. $orWhere[] = ['A_ADM_COMPANY', '=', ''];// TODO: allow empty for everyone?
  225. foreach ($usrAclGroups as $group) $orWhere[] = ['A_ADM_COMPANY', '=', $group];
  226. }
  227. if ($this->_acl->hasField('A_CLASSIFIED')) {
  228. $orWhere[] = ['A_CLASSIFIED', '=', ''];// TODO: allow empty for everyone?
  229. foreach ($usrAclGroups as $group) $orWhere[] = ['A_CLASSIFIED', '=', $group];
  230. }
  231. if (!empty($orWhere) && $this->_acl->hasField('L_APPOITMENT_USER')) {
  232. $orWhere[] = ['L_APPOITMENT_USER', '=', $userLogin];
  233. }
  234. return (!empty($orWhere)) ? [null, 'or', $orWhere] : null;
  235. }
  236. public function parseOgcFilter($ogcFilter) {
  237. $parser = new ParseOgcFilter();
  238. $parser->loadOgcFilter($ogcFilter);
  239. $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
  240. return $queryWhereBuilder->getQueryWhere('t'); // TODO: $this->_fromPrefix
  241. }
  242. public function getQuery() {
  243. if ($this->_query) return clone($this->_query);
  244. // $ds = $this->_acl->getDataSource(); // TODO: only for TableAcl // TODO: move _parseSqlWhere to this class
  245. $filtrIsInstance = []; // $filtrIsInstance = [ $this->_acl->getNamespace() ];
  246. $filtrIsNotInstance = [];
  247. if (!empty($this->_params['f_is_instance'])) $filtrIsInstance = $this->_params['f_is_instance'];
  248. if (!empty($this->_params['f_is_not_instance'])) $filtrIsNotInstance = $this->_params['f_is_not_instance'];
  249. $this->_query = ACL::query($this->_acl)
  250. ->isInstance($filtrIsInstance)
  251. ->isNotInstance($filtrIsNotInstance);
  252. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPrimaryKey} and i.idInstance = {$idInstance}" ])
  253. // $this->_query->where($ds->_parseSqlWhere($params))
  254. DBG::log($this->_params, 'array', "AclQueryFeatures::getQuery \$this->_params");
  255. foreach ($this->_params as $k => $v) {
  256. // DBG::log(['v'=>$v, 'is_numeric' => is_numeric($k), 'is_int' => is_int($k), 'is_array' => is_array($v)], 'array', "AclQueryFeatures::getQuery \$this->_params[{$k}]");
  257. if (is_int($k) && is_array($v)) {
  258. $this->_query->where($v); // TODO: check format [$fieldName, $comparisonSign, $value]
  259. } else if (is_int($k) && null === $v) { // skip NULL
  260. } else if ('f_is_instance' === $k) { // parsed before
  261. } else if ('f_is_not_instance' === $k) { // parsed before
  262. } else if ('@instances' === $k) { // skip - select
  263. } else if ('cols' === $k) { // skip - select
  264. } else if ('f_' === substr($k, 0, 2) && is_string($v) && strlen($k) > 3) {
  265. $fieldName = substr($k, 2);
  266. $fieldType = $this->_acl->getXsdFieldType($fieldName);
  267. list($comparisonSign, $value) = $this->parseQueryValue($fieldName, $v, $fieldType);
  268. DBG::log([ $fieldName, $comparisonSign, $value, $fieldType ], 'array', "parseQueryValue");
  269. $this->_query->where([$fieldName, $comparisonSign, $value]);
  270. } else if ('sf_' === substr($k, 0, 3) && is_string($v) && strlen($k) > 4) {
  271. switch (substr($k, 3)) {
  272. case 'Msgs': $this->_query->where($this->parseSpecialFilterMsgs($v)); break;
  273. case 'Problemy': $this->_query->where($this->parseSpecialFilterProblemy($v)); break;
  274. case 'Status': $this->_query->where($this->parseSpecialFilterStatus($v)); break;
  275. case 'Spotkania': $this->_query->where($this->parseSpecialFilterSpotkania($v)); break;
  276. case 'Access': break; // SKIP - used below
  277. default: throw new Exception("Not Implemented special filter '".substr($k, 3)."'");
  278. }
  279. } else if ('ogc:Filter' === $k) {
  280. $this->_query->where($this->parseOgcFilter($v));
  281. } else if ('primaryKey' === $k) {
  282. $fieldName = $this->_acl->getPrimaryKeyField();
  283. $fieldType = $this->_acl->getXsdFieldType($fieldName);
  284. list($comparisonSign, $value) = $this->parseQueryValue($fieldName, $v, $fieldType);
  285. DBG::log([ $fieldName, $comparisonSign, $value, $fieldType ], 'array', "parseQueryValue");
  286. $this->_query->where([$fieldName, $comparisonSign, $value]);
  287. } else if ('__backRef' === $k) { // skip - parse below
  288. } else if ('limit' === $k) {
  289. } else if ('limitstart' === $k) {
  290. } else if ('order_by' === $k) {
  291. } else if ('order_dir' === $k) {
  292. } else if ('sortBy' === $k) {
  293. } else {
  294. throw new Exception("Not Implemented param '{$k}' = '{$v}'");
  295. }
  296. }
  297. // sf_Access: if 'SHOW' then show all rows, but data with ***
  298. if ('SHOW' !== V::get('sf_Access', '', $this->_params)) $this->_query->where($this->parseSpecialFilterAccess());
  299. if (array_key_exists('__backRef', $this->_params)) {
  300. $backRef = $this->_params['__backRef'];
  301. if (!is_array($backRef)) throw new Exception("Wrong back ref structure - expected array");
  302. if (empty($backRef['namespace'])) throw new Exception("Wrong back ref structure - missing namespace");
  303. if (empty($backRef['primaryKey'])) throw new Exception("Wrong back ref structure - missing primaryKey");
  304. if (empty($backRef['fieldName'])) throw new Exception("Wrong back ref structure - missing fieldName");
  305. // TODO: $this->_query->where([ '__backRef' ]); or $this->_query->join([ '__backRef' ]);
  306. $refAcl = ACL::getAclByNamespace($backRef['namespace']);
  307. if ($refAcl->getSourceName() !== $this->_acl->getSourceName()) throw new Exception("Not implemented join with different source");
  308. $refTable = ACL::getRefTable($refAcl->getNamespace(), $backRef['fieldName']);
  309. // TODO: 'in' operator? // $this->_query->where($pkField, 'in', "");
  310. $sqlPk = $this->getAclSqlPrimaryKeyField();
  311. $sqlBackRefPk = DB::getPDO()->quote($backRef['primaryKey']);
  312. $this->_query->where("
  313. t.{$sqlPk} in (
  314. select refTable.REMOTE_PRIMARY_KEY
  315. from `{$refTable}` refTable
  316. where refTable.PRIMARY_KEY = {$sqlBackRefPk}
  317. )
  318. ");
  319. }
  320. return clone($this->_query);
  321. }
  322. public function getTotal() {
  323. if ($this->_legacyMode) return $this->_acl->getTotal($this->_params);
  324. if (null !== $this->_total) return $this->_total;
  325. $this->_total = $this->getQuery()->fetchTotal();
  326. return $this->_total;
  327. }
  328. public function hasParam($key) { return !empty($this->_params[$key]); }
  329. public function getParam($key) { return V::get($key, '', $this->_params); }
  330. public function getItems() {
  331. if ($this->_legacyMode) return $this->_acl->getItems($this->_params);// TODO: array_map( $r => (array)$r )
  332. // 'limit' => 10,
  333. // 'limitstart' => 0,
  334. // 'order_by' => 'ID',
  335. // 'order_dir' => 'desc',
  336. // TODO: sortBy from wfs query
  337. $sortBy = ($this->hasParam('sortBy')) ? $this->getParam('sortBy') : null;
  338. if (!$sortBy) {
  339. $sortBy = $this->hasParam('order_by')
  340. ? ( $this->hasParam('order_dir')
  341. ? $this->getParam('order_by') . " " . $this->getParam('order_dir')
  342. : $this->getParam('order_by')
  343. )
  344. : '';
  345. }
  346. $limit = V::get('limit', 10, $this->_params, 'int');
  347. $offset = V::get('limitstart', 0, $this->_params, 'int');
  348. DBG::log(['params' => $this->_params, 'sortBy' => $sortBy, 'limit' => $limit, 'offset' => $offset], 'array', '$this->_params');
  349. $select = $this->prepareSelect();
  350. DBG::log($select, 'array', "\$select is(TableAcl)=(".($this->_acl instanceof TableAcl).")");
  351. DBG::log($this->getQuery(), 'array', "\$select is(TableAcl)=(".($this->_acl instanceof TableAcl).") \$this->getQuery()");
  352. return $this->fetchRowsRefs(
  353. $this->getQuery()
  354. ->select($select)
  355. ->limit($limit)
  356. ->offset($offset)
  357. ->orderBy($sortBy)
  358. ->fetchAll()
  359. );
  360. }
  361. public function getItem($primaryKey) { // TODO: throw exception if not found?
  362. if ($this->_legacyMode) return (array)$this->_acl->getItem($primaryKey, $this->_params);
  363. $select = $this->prepareSelect();
  364. $pkField = $this->_acl->getPrimaryKeyField();
  365. return $this->fetchRowRefs(
  366. $this->getQuery()
  367. ->select($select)
  368. ->where([$pkField, '=', $primaryKey])
  369. ->fetchFirst()
  370. );
  371. }
  372. public function prepareSelect() { // TODO: replace with getSelectLocal
  373. // TODO: select from params: 'cols' => [ fieldName, ... ]
  374. // TODO: select from params: '@instances' => 1
  375. // TODO: if no fields set, then '*'
  376. // TODO: select must contain primaryKey
  377. return $this->getSelectLocal();
  378. }
  379. public function getSelectLocal() { // @returns [ $fieldName, ... ]
  380. // TODO: rawSelect!
  381. if (null !== $this->_selectLocalFields) return $this->_selectLocalFields;
  382. $this->_selectLocalFields = [];
  383. $todoFetchAllCols = false; // select t.*
  384. if (!empty($this->_params['cols'])) {
  385. if (in_array('*', $this->_params['cols'])) $todoFetchAllCols = true;
  386. $acl = $this->_acl;
  387. $this->_selectLocalFields = array_filter($this->_params['cols'], function ($fieldQuery) use ($acl) {
  388. if ('*' === $fieldQuery) return false;
  389. list($fieldName, $subFieldQuery) = explode('/', $fieldQuery, 2);
  390. if (!empty($subFieldQuery)) return false;
  391. return $acl->isLocalField($fieldName);
  392. });
  393. }
  394. if (!empty($this->_params['@instances'])) $this->_selectLocalFields[] = '@instances';
  395. if (empty($this->_selectLocalFields)) $todoFetchAllCols = true;
  396. if (1 === count($this->_selectLocalFields) && in_array('@instances', $this->_selectLocalFields)) $todoFetchAllCols = true;
  397. // if ($this->_acl instanceof TableAcl) {
  398. // $rawSelect = $this->_acl->getDataSource()->_getSqlCols();
  399. // DBG::log($rawSelect, 'string', "DBG raw select");
  400. // if ('*' !== $rawSelect && 't.*' !== $rawSelect) {
  401. // $this->_selectLocalFields['rawSelect'] = $rawSelect;
  402. // }
  403. // }
  404. if (!empty($this->_params['cols'])) DBG::log($this->_params['cols'], 'array', '$this->_params[cols]');
  405. if ($todoFetchAllCols) {
  406. // $this->_selectLocalFields[] = '*'; // TODO: select all $this->from local fields
  407. DBG::log($this->_acl->getLocalFieldList(), 'array', "\$this->_acl->getLocalFieldList()");
  408. foreach ($this->_acl->getLocalFieldList() as $localFieldName) {
  409. $this->_selectLocalFields[] = $localFieldName;
  410. }
  411. }
  412. $primaryKey = $this->getAclSqlPrimaryKeyField();
  413. if (!in_array($primaryKey, $this->_selectLocalFields)) {
  414. $this->_selectLocalFields[] = $primaryKey;
  415. }
  416. // TODO: always add A_ADM_COMPANY, A_CLASSIFIED, L_APPOITMENT_USER ?
  417. DBG::log($this->_selectLocalFields, 'array', '$this->_selectLocalFields');
  418. return $this->_selectLocalFields;
  419. }
  420. public function getSelectRemote() { // @returns [ $fieldName => [ $fieldName, ... ] ]
  421. if (null !== $this->_selectRemote) return $this->_selectRemote;
  422. $this->_selectRemote = [];
  423. if (!empty($this->_params['cols'])) {
  424. $cols = $this->_params['cols'];
  425. if (in_array('*', $cols)) {
  426. $this->_selectLocalFields[] = '*';
  427. $cols = array_filter($cols, function ($fieldQuery) { return '*' !== $fieldQuery; });
  428. }
  429. $acl = $this->_acl;
  430. $cols = array_filter($cols, function ($fieldQuery) use ($acl) {
  431. list($fieldName, $subFieldQuery) = explode('/', $fieldQuery, 2);
  432. // if (empty($subFieldQuery)) return false;
  433. return !$acl->isLocalField($fieldName);
  434. });
  435. foreach ($cols as $fieldQuery) { // group by fieldName
  436. list($fieldName, $subFieldQuery) = explode('/', $fieldQuery, 2);
  437. if (!array_key_exists($fieldName, $this->_selectRemote)) $this->_selectRemote[$fieldName] = [];
  438. if (!empty($subFieldQuery)) $this->_selectRemote[$fieldName][] = $subFieldQuery;
  439. }
  440. }
  441. return $this->_selectRemote;
  442. }
  443. public function fetchRowsRefs($rows) {
  444. return array_map([ $this, 'fetchRowRefs' ], $rows);
  445. // if (!empty($rows) && !empty($rows[0])) {
  446. // $rows[0]['default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK'] = [
  447. // [ 'xlink' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK.999' ],
  448. // [ 'xlink' => 'default_db__x3A__CRM_WSKAZNIK:CRM_WSKAZNIK.998' ],
  449. // ];
  450. // }
  451. return $rows;
  452. }
  453. public function fetchRowRefs($row) {
  454. if (!$row) return $row;
  455. $sqlPk = $this->getAclSqlPrimaryKeyField();
  456. $primaryKey = $row[$sqlPk];
  457. DBG::log($row, 'array', "DBG primaryKey '{$primaryKey}'");
  458. if (!$primaryKey) throw new Exception("Missing primaryKey");
  459. foreach ($this->getSelectRemote() as $fieldName => $cols) {
  460. DBG::log($cols, 'array', "add select remote '{$fieldName}' \$cols");
  461. $xsdType = $this->_acl->getXsdFieldType($fieldName);
  462. if ('ref:' === substr($xsdType, 0, 4) && empty($cols)) { // only xlink's
  463. DBG::log("add remote xlink's '{$fieldName}' \$items[{$primaryKey}] ...");
  464. $refTable = ACL::getRefTable($this->_acl->getNamespace(), $fieldName);
  465. if (!$refTable) DBG::log("BUG: Missing refTable in add remote xlink's '{$fieldName}' \$items[{$primaryKey}]");
  466. if ($refTable) {
  467. $xlinks = DB::getPDO()->fetchAll("
  468. select r.REMOTE_PRIMARY_KEY
  469. from `{$refTable}` r
  470. where r.PRIMARY_KEY = '{$primaryKey}'
  471. ");
  472. DBG::log($xlinks, 'array', "add remote xlink's for '{$fieldName}' \$items[{$primaryKey}]");
  473. $row[$fieldName] = array_map(function ($refInfo) use ($fieldName) {
  474. $ns = Core_AclHelper::parseTypeName($fieldName);
  475. return [
  476. // '_ns' => $ns,
  477. 'xlink' => "{$ns['url']}#{$ns['name']}.{$refInfo['REMOTE_PRIMARY_KEY']}",
  478. ];
  479. }, $xlinks);
  480. DBG::log($row[$fieldName], 'array', "remote xlinks for \$items[{$primaryKey}][{$fieldName}]");
  481. }
  482. } else if ('ref:' === substr($xsdType, 0, 4)) { // cols
  483. $items = ACL::getAclByTypeName($fieldName)->buildQuery([
  484. 'cols' => $cols,
  485. '__backRef' => [
  486. 'namespace' => $this->_acl->getNamespace(),
  487. 'primaryKey' => $primaryKey,
  488. 'fieldName' => $fieldName,
  489. ]
  490. ])->getItems();
  491. DBG::log($items, 'array', "add remote items '{$fieldName}' \$items");
  492. $row[$fieldName] = $items;
  493. } else { // TODO: field is not ref
  494. DBG::log($items, 'array', "NotImplemented - add remote items for non ref field \$items[{$primaryKey}][{$fieldName}]?");
  495. }
  496. }
  497. return $row;
  498. }
  499. public function getAclSqlPrimaryKeyField() {
  500. return ($this->_acl instanceof Core_AclBase)
  501. ? $this->_acl->getSqlPrimaryKeyField()
  502. : 'ID';
  503. }
  504. }