AclQueryFeatures.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  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 $_dbgExecTime;
  21. public $_instanceID;
  22. public $_foundFeatures;
  23. public function __construct($acl, $params, $legacyMode = false) {
  24. $this->_acl = $acl;
  25. $this->_params = $params;
  26. $this->_query = null;
  27. $this->_total = null;
  28. $this->_legacyMode = $legacyMode;
  29. // TODO: _legacyMode = ($from instanceof simple schema or another programmed objects)
  30. $this->_selectLocalFields = null;
  31. $this->_selectRemote = null;
  32. $this->_foundFeatures = [];
  33. // 'skipFeaturesAsXlink' => $this->_foundFeatures
  34. if (array_key_exists('skipFeaturesAsXlink', $this->_params)) {
  35. $this->_foundFeatures = V::get('skipFeaturesAsXlink', [], $this->_params, 'array');
  36. unset($this->_params['skipFeaturesAsXlink']);
  37. }
  38. $DBG_LOG_TO_FILE = false; // TODO: read from ENV or REQUEST
  39. if ($DBG_LOG_TO_FILE) {
  40. Lib::loadClass('DebugExecutionTime');
  41. $this->_dbgExecTime = new DebugExecutionTime();
  42. $this->_dbgExecTime->setLogFile('/tmp/se-dbg-exec-time--AclQueryFeatures.csv', $format = 'csv'); // $format: 'csv', 'json'
  43. $this->_logToFile("from: '" . $this->_acl->getNamespace() . "'");
  44. }
  45. }
  46. public function _logToFile($msg) {
  47. if ($this->_dbgExecTime) {
  48. $idInstance = $this->_getInstanceID();
  49. $this->_dbgExecTime->logToFile("#{$idInstance}: {$msg}");
  50. }
  51. }
  52. public function _getInstanceID() {
  53. static $_INSTANCE_ID = 0;
  54. if (!$this->_instanceID) {
  55. $_INSTANCE_ID += 1;
  56. $this->_instanceID = $_INSTANCE_ID;
  57. }
  58. return $this->_instanceID;
  59. }
  60. public function parseQueryValue($fieldName, $searchQuery, $fieldType = 'xsd:string') {
  61. if ('!NULL' === $searchQuery) return ['is not null', null];
  62. if ('IS NOT NULL' === $searchQuery) return ['is not null', null];
  63. if ('NULL' === $searchQuery) return ['is null', null];
  64. if ('IS NULL' === $searchQuery) return ['is null', null];
  65. switch ($fieldType) {
  66. case 'gml:PolygonPropertyType':
  67. case 'gml:PointPropertyType':
  68. case 'gml:LineStringPropertyType':
  69. case 'gml:GeometryPropertyType': return $this->_parseGeomQuery($searchQuery);
  70. // $sqlFilter = $this->_sqlValueForGeomField($fldName, $v, 't');
  71. // if ('_CSV_NUM' == substr($fldName, -8)) { // if ($this->isCsvNumericField($fldName)) { // TODO: xsd type - p5:csv_num
  72. // $sqlFilter = $this->_sqlValueForCsvNumericField($fldName, $v, 't');
  73. // if ($sqlFilter) $sql_where_and[] = $sqlFilter;
  74. // continue;
  75. // }
  76. }
  77. switch (substr($searchQuery, 0, 1)) {
  78. case '=': return ['=', substr($searchQuery, 1)];
  79. case '>':
  80. switch (substr($searchQuery, 1, 1)) {
  81. case '=': return ['>=', substr($searchQuery, 2)];
  82. default: return ['>', substr($searchQuery, 1)];
  83. }
  84. case '<':
  85. switch (substr($searchQuery, 1, 1)) {
  86. case '=': return ['<=', substr($searchQuery, 2)];
  87. case '>': return ['!=', substr($searchQuery, 2)];
  88. default: return ['<', substr($searchQuery, 1)];
  89. }
  90. case '!':
  91. switch (substr($searchQuery, 1, 1)) {
  92. case '=': return ['!=', substr($searchQuery, 2)];
  93. default: return ['not like', substr($searchQuery, 1)];
  94. }
  95. default: {
  96. switch ($fieldType) {
  97. case 'xsd:long':
  98. case 'xsd:number':
  99. case 'xsd:int':
  100. case 'xsd:integer': {
  101. if (false !== strpos($searchQuery, '%')) return ['like', $searchQuery];
  102. return ['=', $searchQuery];
  103. }
  104. default: {
  105. if (false !== strpos($searchQuery, '%')) return ['like', $searchQuery];
  106. $queryWhereBuilder = new SqlQueryWhereBuilder();
  107. return ['and'
  108. , array_map(function ($word) use ($fieldName) {
  109. return [$fieldName, 'like', "%{$word}%"];
  110. }, $queryWhereBuilder->splitQueryToWords($searchQuery)
  111. )
  112. ];
  113. }
  114. }
  115. return ['=', $searchQuery];
  116. }
  117. }
  118. }
  119. public function _parseGeomQuery($searchQuery) { // _sqlValueForGeomField($fldName, $fltrValue, $tblPrefix = 't')
  120. // example: BBOX:54.40993961633866,18.583889010112824,54.337945760687454,18.397121431987586
  121. DBG::log($searchQuery, 'string', "\$searchQuery");
  122. if ('BBOX:' == substr($searchQuery, 0, 5)) {
  123. $valParts = explode(',', substr($searchQuery, 5));
  124. if (4 !== count($valParts)) throw new Exception("Wrong BBOX query");
  125. $valParts = array_filter($valParts, 'is_numeric');
  126. if (4 !== count($valParts)) throw new Exception("Wrong BBOX query - expected 4 numeric values");
  127. $bounds = "POLYGON((
  128. {$valParts[3]} {$valParts[2]},
  129. {$valParts[3]} {$valParts[0]},
  130. {$valParts[1]} {$valParts[0]},
  131. {$valParts[1]} {$valParts[2]},
  132. {$valParts[3]} {$valParts[2]}
  133. ))";
  134. // for mysql 5.6 use ST_Contains() @see http://dev.mysql.com/doc/refman/5.6/en/spatial-relation-functions.html
  135. return [ 'Intersects', $bounds ];
  136. }
  137. else if ('GeometryType=' == substr($fltrValue, 0, 13)) {
  138. return [ 'GeometryType', substr($fltrValue, 13) ];
  139. }
  140. throw new Exception("Not implemented geometry query string"); // TODO:? return null;
  141. }
  142. public function _sqlValueForCsvNumericField($fldName, $fltrValue, $tblPrefix = 't') {
  143. $sqlFilter = false;
  144. if (is_numeric($fltrValue)) {
  145. $sqlFilter = "FIND_IN_SET('{$fltrValue}', `{$fldName}`)>0";
  146. } else if (false !== strpos($fltrValue, ' ')) {
  147. $sqlGlue = " or ";
  148. $fltrValues = $fltrValue;
  149. if ('&' == substr($fltrValues, 0, 1)) {
  150. $fltrValues = substr($fltrValues, 1);
  151. $sqlGlue = " and ";
  152. }
  153. $fltrValues = explode(' ', $fltrValues);
  154. $sqlNumericValues = array();
  155. foreach ($fltrValues as $fltrVal) {
  156. if (is_numeric($fltrVal)) {
  157. $sqlNumericValues[] = "FIND_IN_SET('{$fltrVal}', `{$fldName}`)>0";
  158. }
  159. }
  160. if (!empty($sqlNumericValues)) {
  161. $sqlFilter = "(" . implode($sqlGlue, $sqlNumericValues) . ")";
  162. }
  163. }
  164. return $sqlFilter;
  165. }
  166. public function parseSpecialFilterMsgs($type) {
  167. $rootTableName = $this->_acl->getRootTableName();
  168. DBG::log($rootTableName, 'string', "parse SpecialFilter Msgs({$type}), \$rootTableName");
  169. $sqlHasFltrMsgs = "
  170. select 1
  171. from `CRM_UI_MSGS` m
  172. where m.`uiTargetName`=CONCAT('{$rootTableName}.', t.`ID`)
  173. and m.`uiTargetType`='default_db_table_record'
  174. and m.`A_STATUS` not in('DELETED')
  175. limit 1
  176. ";
  177. switch ($type) {
  178. case 'HAS_MSGS': return " ({$sqlHasFltrMsgs})=1 ";
  179. case 'NO_MSGS': return " ({$sqlHasFltrMsgs}) is null ";
  180. case 'NEW_MSGS': {
  181. $sqlNewFltrMsgs = "
  182. select 1
  183. from `CRM_UI_MSGS` m
  184. where m.`uiTargetName`=CONCAT('{$rootTableName}.', t.`ID`)
  185. and m.`uiTargetType`='default_db_table_record'
  186. and m.`A_STATUS` in('WAITING')
  187. limit 1
  188. ";
  189. return " ({$sqlNewFltrMsgs})=1 ";
  190. }
  191. }
  192. return null;
  193. }
  194. public function parseSpecialFilterProblemy($type) {
  195. DBG::log($type, 'string', "parse SpecialFilter Problemy");
  196. switch ($type) {
  197. case 'PROBLEM': return ['A_PROBLEM', '!=', ''];
  198. case 'WARNING': return ['A_PROBLEM', '=', 'WARNING'];
  199. case 'NORMAL': return ['A_PROBLEM', '=', 'NORMAL'];
  200. }
  201. return null;
  202. }
  203. public function parseSpecialFilterStatus($type) {
  204. DBG::log($type, 'string', "parse SpecialFilter Status");
  205. switch ($type) {
  206. case 'WAITING': return ['A_STATUS', '=', 'WAITING'];
  207. case 'AKTYWNI': return ['A_STATUS', 'or', [ // `A_STATUS` in('NORMAL', 'WARNING') ";
  208. ['A_STATUS', '=', 'NORMAL'],
  209. ['A_STATUS', '=', 'WARNING'],
  210. ] ];
  211. }
  212. return null;
  213. }
  214. public function parseSpecialFilterSpotkania($type) {
  215. DBG::log($type, 'string', "parse SpecialFilter Spotkania");
  216. switch ($type) {
  217. case 'OLD': return ['L_APPOITMENT_DATE', 'and', [
  218. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_LESS_THAN_NOW'],
  219. ] ];
  220. // COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < UNIX_TIMESTAMP()
  221. // and t.`L_APPOITMENT_DATE` != ''
  222. // and t.`L_APPOITMENT_DATE` != '0000-00-00 00:00:00'
  223. case 'NOW': return ['L_APPOITMENT_DATE', 'and', [
  224. [ 'L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_NOW_3600'],
  225. ] ];
  226. // COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < UNIX_TIMESTAMP()+3600
  227. // and COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) > UNIX_TIMESTAMP()-3600
  228. case 'TODAY': return ['L_APPOITMENT_DATE', 'and', [
  229. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_GREATER_THAN', mktime(0,0,0, date("m"), date("d"), date("Y"))],
  230. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_LESS_THAN', mktime(0,0,0, date("m"), date("d") + 1, date("Y"))],
  231. ] ];
  232. // $start = mktime(0,0,0, date("m"), date("d"), date("Y"));
  233. // $end = mktime(0,0,0, date("m"), date("d") + 1, date("Y"));
  234. // $sqlFltr = "
  235. // COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) > '{$start}'
  236. // and COALESCE(UNIX_TIMESTAMP(t.`L_APPOITMENT_DATE`), 0) < '{$end}'
  237. // ";
  238. case 'TOMORROW': return ['L_APPOITMENT_DATE', 'and', [
  239. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_GREATER_THAN', mktime(0,0,0, date("m"), date("d") + 1, date("Y"))],
  240. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_LESS_THAN', mktime(0,0,0, date("m"), date("d") + 2, date("Y"))],
  241. ] ];
  242. case 'YESTERDAY': return ['L_APPOITMENT_DATE', 'and', [
  243. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_GREATER_THAN', mktime(0,0,0, date("m"), date("d") - 2, date("Y"))],
  244. ['L_APPOITMENT_DATE', 'UNIX_TIMESTAMP_LESS_THAN', mktime(0,0,0, date("m"), date("d") - 1, date("Y"))],
  245. ] ];
  246. case 'BRAK': return ['L_APPOITMENT_DATE', 'or', [
  247. ['L_APPOITMENT_DATE', '=', ''],
  248. ['L_APPOITMENT_DATE', '=', '0000-00-00 00:00:00'],
  249. ] ];
  250. }
  251. return null;
  252. }
  253. public function parseSpecialFilterAccess() {
  254. $userLogin = User::getLogin();
  255. $usrAclGroups = User::getLdapGroupsNames();
  256. DBG::log(['ns'=>$this->_acl->getNamespace(), 'login'=>$userLogin, 'hasWriteField'=>$this->_acl->hasWriteGroupField(), 'hasReadField'=>$this->_acl->hasReadGroupField(), 'hasOwnerField'=>$this->_acl->hasOwnerField(), 'groups'=>$usrAclGroups], 'array', "parse SpecialFilter Access");
  257. $orWhere = [];
  258. if ($this->_acl->hasWriteGroupField()) {
  259. $orWhere[] = ['A_ADM_COMPANY', '=', ''];// TODO: allow empty for everyone?
  260. foreach ($usrAclGroups as $group) $orWhere[] = ['A_ADM_COMPANY', '=', $group];
  261. }
  262. if ($this->_acl->hasReadGroupField()) {
  263. $orWhere[] = ['A_CLASSIFIED', '=', ''];// TODO: allow empty for everyone?
  264. foreach ($usrAclGroups as $group) $orWhere[] = ['A_CLASSIFIED', '=', $group];
  265. }
  266. if (!empty($orWhere) && $this->_acl->hasOwnerField()) {
  267. $orWhere[] = ['L_APPOITMENT_USER', '=', $userLogin];
  268. }
  269. return (!empty($orWhere)) ? [null, 'or', $orWhere] : null;
  270. }
  271. public function parseOgcFilter($ogcFilter) {
  272. $parser = new ParseOgcFilter();
  273. $parser->loadOgcFilter($ogcFilter);
  274. $queryWhereBuilder = $parser->convertToSqlQueryWhereBuilder();
  275. return $queryWhereBuilder->getQueryWhere('t'); // TODO: $this->_fromPrefix
  276. }
  277. public function getQuery() {
  278. if ($this->_query) return clone($this->_query);
  279. // $ds = $this->_acl->getDataSource(); // TODO: only for TableAcl // TODO: move _parseSqlWhere to this class
  280. $filtrIsInstance = []; // $filtrIsInstance = [ $this->_acl->getNamespace() ];
  281. $filtrIsNotInstance = [];
  282. if (!empty($this->_params['f_is_instance'])) $filtrIsInstance = $this->_params['f_is_instance'];
  283. if (!empty($this->_params['f_is_not_instance'])) $filtrIsNotInstance = $this->_params['f_is_not_instance'];
  284. $this->_query = ACL::query($this->_acl)
  285. ->isInstance($filtrIsInstance)
  286. ->isNotInstance($filtrIsNotInstance);
  287. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPrimaryKey} and i.idInstance = {$idInstance}" ])
  288. // $this->_query->where($ds->_parseSqlWhere($params))
  289. DBG::log($this->_params, 'array', "AclQueryFeatures::getQuery \$this->_params");
  290. foreach ($this->_params as $k => $v) {
  291. // 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}]");
  292. if (is_int($k) && is_array($v)) {
  293. $this->_query->where($v); // TODO: check format [$fieldName, $comparisonSign, $value]
  294. } else if (is_int($k) && null === $v) { // skip NULL
  295. } else if ('f_is_instance' === $k) { // parsed before
  296. } else if ('f_is_not_instance' === $k) { // parsed before
  297. } else if ('@instances' === $k) { // skip - select
  298. } else if ('cols' === $k) { // skip - select
  299. } else if ('f_' === substr($k, 0, 2) && is_string($v) && strlen($k) > 3) {
  300. $fieldName = substr($k, 2);
  301. $fieldType = $this->_acl->getXsdFieldType($fieldName);
  302. list($comparisonSign, $value) = $this->parseQueryValue($fieldName, $v, $fieldType);
  303. DBG::log([ $fieldName, $comparisonSign, $value, $fieldType ], 'array', "parseQueryValue");
  304. $this->_query->where([$fieldName, $comparisonSign, $value]);
  305. } else if ('sf_' === substr($k, 0, 3) && is_string($v) && strlen($k) > 4) {
  306. switch (substr($k, 3)) {
  307. case 'Msgs': $this->_query->where($this->parseSpecialFilterMsgs($v)); break;
  308. case 'Problemy': $this->_query->where($this->parseSpecialFilterProblemy($v)); break;
  309. case 'Status': $this->_query->where($this->parseSpecialFilterStatus($v)); break;
  310. case 'Spotkania': $this->_query->where($this->parseSpecialFilterSpotkania($v)); break;
  311. case 'Access': break; // SKIP - used below
  312. default: {
  313. if (method_exists($this->_acl, 'parseSpecialFilter')) {
  314. $this->_query->where(
  315. $this->_acl->parseSpecialFilter(substr($k, 3), $v)
  316. );
  317. } else {
  318. throw new Exception("Not Implemented special filter '".substr($k, 3)."'");
  319. }
  320. }
  321. }
  322. } else if ('ogc:Filter' === $k) {
  323. $this->_query->where($this->parseOgcFilter($v));
  324. } else if ('primaryKey' === $k) {
  325. $fieldName = $this->_acl->getPrimaryKeyField();
  326. $fieldType = $this->_acl->getXsdFieldType($fieldName);
  327. if (is_array($v)) {
  328. DBG::log([ $fieldName, $v, $fieldType ], 'array', "parseQueryValue :: primaryKey, value is array");
  329. $this->_query->where([ $fieldName, 'or', array_map(function ($pk) use ($fieldName) {
  330. return [ $fieldName, '=', $pk ];
  331. }, $v) ]);
  332. } else {
  333. list($comparisonSign, $value) = $this->parseQueryValue($fieldName, $v, $fieldType);
  334. DBG::log([ $fieldName, $comparisonSign, $value, $fieldType ], 'array', "parseQueryValue");
  335. $this->_query->where([$fieldName, $comparisonSign, $value]);
  336. }
  337. } else if ('__backRef' === $k) { // skip - parse below
  338. } else if ('__childRef' === $k) { // skip - parse below
  339. } else if ('limit' === $k) {
  340. } else if ('limitstart' === $k) {
  341. } else if ('order_by' === $k) {
  342. } else if ('order_dir' === $k) {
  343. } else if ('sortBy' === $k) {
  344. } else {
  345. throw new Exception("Not Implemented param '{$k}' = '{$v}'");
  346. }
  347. }
  348. // sf_Access: if 'SHOW' then show all rows, but data with ***
  349. if ('SHOW' !== V::get('sf_Access', '', $this->_params)) $this->_query->where($this->parseSpecialFilterAccess());
  350. if (array_key_exists('__backRef', $this->_params)) {
  351. $backRef = $this->_params['__backRef'];
  352. if (!is_array($backRef)) throw new Exception("Wrong back ref structure - expected array");
  353. if (empty($backRef['namespace'])) throw new Exception("Wrong back ref structure - missing namespace");
  354. if (empty($backRef['primaryKey'])) throw new Exception("Wrong back ref structure - missing primaryKey");
  355. if (empty($backRef['fieldName'])) throw new Exception("Wrong back ref structure - missing fieldName");
  356. // TODO: $this->_query->where([ '__backRef' ]); or $this->_query->join([ '__backRef' ]);
  357. $refAcl = ACL::getAclByNamespace($backRef['namespace']);
  358. if ($refAcl->getSourceName() !== $this->_acl->getSourceName()) throw new Exception("Not implemented join with different source");
  359. $refTable = ACL::getRefTable($refAcl->getNamespace(), $backRef['fieldName']);
  360. // TODO: 'in' operator? // $this->_query->where($pkField, 'in', "");
  361. $sqlPk = $this->getAclSqlPrimaryKeyField();
  362. $sqlBackRefPk = DB::getPDO()->quote($backRef['primaryKey']);
  363. $limit = V::get('limit', 10, $this->_params, 'int');
  364. $offset = V::get('limitstart', 0, $this->_params, 'int');
  365. DBG::log(['limit' => $limit, 'offset' => $offset], 'array', "DBG: limit with __backRef \$this->_params");
  366. $sqlLimit = "limit {$limit} offset {$offset}";
  367. // $this->_query->where("
  368. // t.{$sqlPk} in (
  369. // select refTable.REMOTE_PRIMARY_KEY
  370. // from `{$refTable}` refTable
  371. // where refTable.PRIMARY_KEY = {$sqlBackRefPk}
  372. // order by refTable.REMOTE_PRIMARY_KEY DESC -- TODO refTable.SORT_PRIO
  373. // -- {$sqlLimit} -- BUG MariaDB not support limit in subquery
  374. // )
  375. // ");
  376. // TODO: convert `where t.ID in ( ... )` into `join` and `order by`
  377. // join `CRM__#REF_TABLE__120_VIEW` refTable on (refTable.REMOTE_PRIMARY_KEY = t.ID and refTable.PRIMARY_KEY = '37' )
  378. DBG::log([
  379. 'ACL::getRefTable(...)' => [$refAcl->getNamespace(), $backRef['fieldName']],
  380. '$backRef' => $backRef,
  381. '$refTable' => $refTable
  382. ], 'array', "DBG: join \$join class(".get_class($join).")");
  383. $this->_query->join($refTable, 'refTable', [ 'rawJoin' => "t.{$sqlPk} = refTable.REMOTE_PRIMARY_KEY and refTable.PRIMARY_KEY = {$sqlBackRefPk}" ]);
  384. // moved to getItems: $this->_query->orderBy("refTable.REMOTE_PRIMARY_KEY DESC"); // TODO: order by refTable.SORT_PRIO
  385. }
  386. if (array_key_exists('__childRef', $this->_params)) {
  387. $childRef = $this->_params['__childRef'];
  388. if (!is_array($childRef)) throw new Exception("Wrong child ref structure - expected array");
  389. if (empty($childRef['namespace'])) throw new Exception("Wrong child ref structure - missing namespace");
  390. if (empty($childRef['primaryKey'])) throw new Exception("Wrong child ref structure - missing primaryKey");
  391. $refAcl = ACL::getAclByNamespace($childRef['namespace']);
  392. if ($refAcl->getSourceName() !== $this->_acl->getSourceName()) throw new Exception("Not implemented join with different source");
  393. $refTypeName = Api_WfsNs::typeName($childRef['namespace']);
  394. DBG::log("\$refTypeName({$refTypeName})");
  395. $refTable = ACL::getRefTable($this->_acl->getNamespace(), $refTypeName);
  396. // TODO: 'in' operator? // $this->_query->where($pkField, 'in', "");
  397. $sqlPk = $this->getAclSqlPrimaryKeyField();
  398. $sqlChildRefPk = DB::getPDO()->quote($childRef['primaryKey']);
  399. $this->_query->where("
  400. t.{$sqlPk} in (
  401. select refTable.PRIMARY_KEY
  402. from `{$refTable}` refTable
  403. where refTable.REMOTE_PRIMARY_KEY = {$sqlChildRefPk}
  404. )
  405. ");
  406. }
  407. DBG::log($this->_query, 'array', "TODO: optimize \$this->_query");
  408. $this->_USE_TEMPORARY_TABLE = false; // TODO: ...
  409. if ($this->_USE_TEMPORARY_TABLE) {
  410. $sortBy = ($this->hasParam('sortBy')) ? $this->getParam('sortBy') : null;
  411. if (!$sortBy) {
  412. $sortBy = $this->hasParam('order_by')
  413. ? ( $this->hasParam('order_dir')
  414. ? $this->getParam('order_by') . " " . $this->getParam('order_dir')
  415. : $this->getParam('order_by')
  416. )
  417. : '';
  418. }
  419. $TMP_TABLE_NAME = $this->_acl->getRootTableName() . "__#TEMPORARY";
  420. DBG::log("\$TMP_TABLE_NAME='{$TMP_TABLE_NAME}'");
  421. Lib::loadClass('AntAclBase');
  422. if ($this->_acl instanceof AntAclBase) {
  423. $baseSql = $this->_query->generateSql();
  424. DB::getPDO()->execSql("
  425. create temporary table `{$TMP_TABLE_NAME}`
  426. {$baseSql}
  427. ");
  428. DBG::log(DB::getPDO()->fetchValue("select count(*) as cnt from `{$TMP_TABLE_NAME}`"), 'array', "select count(*) cnt from '{$TMP_TABLE_NAME}'");
  429. $tmpAclFrom = clone($this->_acl);
  430. $tmpAclFrom->_rootTableName = $TMP_TABLE_NAME;
  431. // $tmpAclFrom = AntAclBase::buildInstance($this->_acl->getID(), [
  432. // 'name' => $this->_acl->getName(),
  433. // '_rootTableName' => $TMP_TABLE_NAME,
  434. // 'idDatabase' => $this->_acl->getDatabaseID(),
  435. // 'namespace' => $this->_acl->getNamespace(),
  436. // 'primaryKey' => $this->_acl->getPrimaryKeyField(),
  437. // 'field' => $this->_acl->getFields(),
  438. // ]);
  439. Lib::loadClass('AclQueryBuilder');
  440. $query = new AclQueryBuilder();
  441. $query->from($tmpAclFrom, $prefix = 't');
  442. DBG::log($query, 'array', "TODO: \$query by temporary table");
  443. // $this->_query = $query;
  444. // return $this->_query;
  445. }
  446. }
  447. return clone($this->_query);
  448. }
  449. public function getTotal() {
  450. $this->_beforeFetchData();
  451. if ($this->_legacyMode) return $this->_acl->getTotal($this->_params);
  452. if (null !== $this->_total) return $this->_total;
  453. $this->_total = $this->getQuery()->fetchTotal();
  454. return $this->_total;
  455. }
  456. public function hasParam($key) { return !empty($this->_params[$key]); }
  457. public function getParam($key) { return V::get($key, '', $this->_params); }
  458. public function getItems() {
  459. $this->_logToFile('getItems() ...');
  460. $this->_beforeFetchData();
  461. if ($this->_legacyMode) return $this->_acl->getItems($this->_params);// TODO: array_map( $r => (array)$r )
  462. // 'limit' => 10,
  463. // 'limitstart' => 0,
  464. // 'order_by' => 'ID',
  465. // 'order_dir' => 'desc',
  466. // TODO: sortBy from wfs query
  467. $sortBy = ($this->hasParam('sortBy')) ? $this->getParam('sortBy') : null;
  468. if (!$sortBy && array_key_exists('__backRef', $this->_params)) {
  469. $sortBy = "refTable.REMOTE_PRIMARY_KEY DESC"; // TODO: order by refTable.SORT_PRIO
  470. }
  471. if (!$sortBy) {
  472. $sortBy = $this->hasParam('order_by')
  473. ? ( $this->hasParam('order_dir')
  474. ? $this->getParam('order_by') . " " . $this->getParam('order_dir')
  475. : $this->getParam('order_by')
  476. )
  477. : '';
  478. }
  479. $limit = V::get('limit', 10, $this->_params, 'int');
  480. $offset = V::get('limitstart', 0, $this->_params, 'int');
  481. DBG::log(['params' => $this->_params, 'sortBy' => $sortBy, 'limit' => $limit, 'offset' => $offset], 'array', '$this->_params');
  482. $select = $this->prepareSelect();
  483. DBG::log($select, 'array', "\$select is(TableAcl)=(".($this->_acl instanceof TableAcl).")");
  484. // DBG::log($this->getQuery(), 'array', "\$select is(TableAcl)=(".($this->_acl instanceof TableAcl).") \$this->getQuery()");
  485. $items = $this->fetchRowsRefs(
  486. $this->getQuery()
  487. ->select(array_merge(['@primaryKey'], $select))
  488. ->limit($limit)
  489. ->offset($offset)
  490. ->orderBy($sortBy)
  491. ->fetchAll()
  492. );
  493. $this->_logToFile('getItems() fetched.');
  494. return $items;
  495. }
  496. function _beforeFetchData() {
  497. if (method_exists($this->_acl, 'onBeforeFetchData')) $this->_acl->onBeforeFetchData();
  498. }
  499. public function getItem($primaryKey) { // TODO: throw exception if not found?
  500. $this->_beforeFetchData();
  501. if ($this->_legacyMode) return (array)$this->_acl->getItem($primaryKey, $this->_params);
  502. $select = $this->prepareSelect();
  503. $pkField = $this->_acl->getPrimaryKeyField();
  504. return $this->fetchRowRefs(
  505. $this->getQuery()
  506. ->select($select)
  507. ->where([$pkField, '=', $primaryKey])
  508. ->fetchFirst()
  509. );
  510. }
  511. public function prepareSelect() { // TODO: replace with getSelectLocal
  512. // TODO: select from params: 'cols' => [ fieldName, ... ]
  513. // TODO: select from params: '@instances' => 1
  514. // TODO: if no fields set, then '*'
  515. // TODO: select must contain primaryKey
  516. return $this->getSelectLocal();
  517. }
  518. public function getSelectLocal() { // @returns [ $fieldName, ... ]
  519. // TODO: rawSelect!
  520. if (null !== $this->_selectLocalFields) return $this->_selectLocalFields;
  521. $this->_selectLocalFields = [];
  522. $todoFetchAllCols = false; // select t.*
  523. if (!empty($this->_params['cols'])) {
  524. if (in_array('*', $this->_params['cols'])) $todoFetchAllCols = true;
  525. $acl = $this->_acl;
  526. $this->_selectLocalFields = array_filter($this->_params['cols'], function ($fieldQuery) use ($acl) {
  527. if ('*' === $fieldQuery) return false;
  528. list($fieldName, $subFieldQuery) = explode('/', $fieldQuery, 2);
  529. if (!empty($subFieldQuery)) return false;
  530. return $acl->isLocalField($fieldName);
  531. });
  532. }
  533. if (!empty($this->_params['@instances'])) $this->_selectLocalFields[] = '@instances';
  534. if (empty($this->_selectLocalFields)) $todoFetchAllCols = true;
  535. if (1 === count($this->_selectLocalFields) && in_array('@instances', $this->_selectLocalFields)) $todoFetchAllCols = true;
  536. // if ($this->_acl instanceof TableAcl) {
  537. // $rawSelect = $this->_acl->getDataSource()->_getSqlCols();
  538. // DBG::log($rawSelect, 'string', "DBG raw select");
  539. // if ('*' !== $rawSelect && 't.*' !== $rawSelect) {
  540. // $this->_selectLocalFields['rawSelect'] = $rawSelect;
  541. // }
  542. // }
  543. if (!empty($this->_params['cols'])) DBG::log($this->_params['cols'], 'array', "\$this->_params[cols] (" . ($this->_acl ? $this->_acl->getNamespace() : 'unknown') . ")");
  544. if ($todoFetchAllCols) {
  545. // $this->_selectLocalFields[] = '*'; // TODO: select all $this->from local fields
  546. DBG::log($this->_acl->getLocalFieldList(), 'array', "\$this->_acl->getLocalFieldList()");
  547. foreach ($this->_acl->getLocalFieldList() as $localFieldName) {
  548. $this->_selectLocalFields[] = $localFieldName;
  549. }
  550. }
  551. $primaryKeyField = $this->getAclSqlPrimaryKeyField();
  552. if (!in_array($primaryKeyField, $this->_selectLocalFields)) {
  553. $this->_selectLocalFields[] = $primaryKeyField;
  554. }
  555. // TODO: always add A_ADM_COMPANY, A_CLASSIFIED, L_APPOITMENT_USER ?
  556. DBG::log($this->_selectLocalFields, 'array', '$this->_selectLocalFields');
  557. return $this->_selectLocalFields;
  558. }
  559. public function getSelectRemote() { // @returns [ $fieldName => [ $fieldName, ... ] ]
  560. if (null !== $this->_selectRemote) return $this->_selectRemote;
  561. $this->_selectRemote = [];
  562. if (!empty($this->_params['cols'])) {
  563. $cols = $this->_params['cols'];
  564. if (in_array('*', $cols)) {
  565. $this->_selectLocalFields[] = '*';
  566. $cols = array_filter($cols, function ($fieldQuery) { return '*' !== $fieldQuery; });
  567. }
  568. $acl = $this->_acl;
  569. $cols = array_filter($cols, function ($fieldQuery) use ($acl) {
  570. list($fieldName, $subFieldQuery) = explode('/', $fieldQuery, 2);
  571. // if (empty($subFieldQuery)) return false;
  572. return !$acl->isLocalField($fieldName);
  573. });
  574. foreach ($cols as $fieldQuery) { // group by fieldName
  575. list($fieldName, $subFieldQuery) = explode('/', $fieldQuery, 2);
  576. if (!array_key_exists($fieldName, $this->_selectRemote)) $this->_selectRemote[$fieldName] = [];
  577. if (!empty($subFieldQuery)) $this->_selectRemote[$fieldName][] = $subFieldQuery;
  578. }
  579. }
  580. return $this->_selectRemote;
  581. }
  582. public function fetchRowsRefs($rows) {
  583. $pkField = $this->_acl->getPrimaryKeyField();
  584. $namespace = $this->_acl->getNamespace();
  585. $this->_foundFeatures = array_merge($this->_foundFeatures, array_map(function ($row) use ($namespace, $pkField) {
  586. return "{$namespace}." . V::get($pkField, '', $row);
  587. }, $rows));
  588. DBG::log($this->_foundFeatures, 'array', "_foundFeatures");
  589. return array_map([ $this, 'fetchRowRefs' ], $rows);
  590. }
  591. public function fetchRowRefs($row) {
  592. try {
  593. return $this->_fetchRowRefs($row);
  594. } catch (Exception $e) {
  595. DBG::log($e);
  596. }
  597. return $row;
  598. }
  599. public function _fetchRowRefs($row) {
  600. if (!$row) return $row;
  601. $sqlPk = $this->getAclSqlPrimaryKeyField();
  602. $primaryKey = $row[$sqlPk];
  603. DBG::log($row, 'array', "DBG primaryKey '{$primaryKey}'");
  604. if (!$primaryKey) throw new Exception("Missing primaryKey");
  605. $defaultRefLimit = 10; // TODO: get from $this->_params and pass to nested buildQuery
  606. $refLimitPlus1 = $defaultRefLimit + 1;
  607. foreach ($this->getSelectRemote() as $fieldName => $cols) {
  608. DBG::log($cols, 'array', "add select remote '{$fieldName}' \$cols");
  609. $xsdType = $this->_acl->getXsdFieldType($fieldName);
  610. if ('ref:' === substr($xsdType, 0, 4) && empty($cols)) {
  611. DBG::log("add remote xlink's '{$fieldName}' \$items[{$primaryKey}] ...");
  612. $refTable = ACL::getRefTable($this->_acl->getNamespace(), $fieldName);
  613. if (!$refTable) DBG::log("BUG: Missing refTable in add remote xlink's '{$fieldName}' \$items[{$primaryKey}]");
  614. if ($refTable) {
  615. $xlinks = DB::getPDO()->fetchAll("
  616. select r.REMOTE_PRIMARY_KEY
  617. from `{$refTable}` r
  618. where r.PRIMARY_KEY = '{$primaryKey}'
  619. order by r.REMOTE_PRIMARY_KEY DESC -- TODO r.SORT_PRIO
  620. limit {$refLimitPlus1}
  621. ");
  622. DBG::log($xlinks, 'array', "add remote xlink's for '{$fieldName}' \$items[{$primaryKey}]");
  623. $row[$fieldName] = array_map(function ($refInfo) use ($fieldName) {
  624. $ns = Core_AclHelper::parseTypeName($fieldName);
  625. return [
  626. // '_ns' => $ns,
  627. 'xlink' => "{$ns['url']}#{$ns['name']}.{$refInfo['REMOTE_PRIMARY_KEY']}",
  628. ];
  629. }, $xlinks);
  630. if (count($xlinks) > $defaultRefLimit) DBG::log('TODO: xlink FETCH MORE DATA...');
  631. if (count($xlinks) > $defaultRefLimit) $row[$fieldName][] = [ 'p5:links' => [
  632. 'p5:next' => [
  633. '@typeName' => $fieldName,
  634. '@backRefNS' => $this->_acl->getNamespace(),
  635. '@backRefPK' => $primaryKey,
  636. '@startIndex' => $defaultRefLimit,
  637. '@maxFeatures' => $defaultRefLimit,
  638. 'value' => Request::getScriptUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$fieldName}&REQUEST=GetFeature&backRefNS=".$this->_acl->getNamespace()."&backRefPK={$primaryKey}&backRefField={$fieldName}&maxFeatures={$defaultRefLimit}&startIndex={$defaultRefLimit}",
  639. ],
  640. ] ];
  641. DBG::log($row[$fieldName], 'array', "remote xlinks for \$items[{$primaryKey}][{$fieldName}]");
  642. }
  643. } else if ('ref:' === substr($xsdType, 0, 4) && !empty($cols)) {
  644. $refAcl = ACL::getAclByTypeName($fieldName);
  645. $refQuery = $refAcl->buildQuery([
  646. 'cols' => $cols,
  647. '__backRef' => [
  648. 'namespace' => $this->_acl->getNamespace(),
  649. 'primaryKey' => $primaryKey,
  650. 'fieldName' => $fieldName,
  651. ],
  652. 'limit' => $refLimitPlus1,
  653. 'skipFeaturesAsXlink' => $this->_foundFeatures
  654. // TODO: add $defaultRefLimit + 1
  655. ]);
  656. $totalRefs = $refQuery->getTotal();
  657. $items = $refQuery->getItems([ 'limit' => $defaultRefLimit ]);
  658. // TODO: if (count($items) > $defaultRefLimit) // TODO: add item for GUI - has more data + wfs link to fetch more (offset)
  659. DBG::log($items, 'array', "add remote items '{$fieldName}' \$items[{$primaryKey}][{$fieldName}] total({$totalRefs})");
  660. if ($totalRefs > $defaultRefLimit) {
  661. DBG::log('TODO: resolve recurse fetch more data link');
  662. array_pop($items); // remove last item
  663. $items[] = [ 'p5:links' => [
  664. 'p5:next' => [
  665. '@typeName' => $fieldName,
  666. '@backRefNS' => $this->_acl->getNamespace(),
  667. '@backRefPK' => $primaryKey,
  668. '@startIndex' => $defaultRefLimit,
  669. '@maxFeatures' => $defaultRefLimit,
  670. 'value' => Request::getScriptUri() . "?SERVICE=WFS&VERSION=1.0.0&TYPENAME={$fieldName}&REQUEST=GetFeature&backRefNS=".$this->_acl->getNamespace()."&backRefPK={$primaryKey}&backRefField={$fieldName}&maxFeatures={$defaultRefLimit}&startIndex={$defaultRefLimit}",
  671. ],
  672. ] ];
  673. }
  674. $refNs = $refAcl->getNamespace();
  675. $refPk = $refAcl->getPrimaryKeyField();
  676. $this__hasFeatureId = [ $this, 'hasFeatureId' ];
  677. $this__addFeatureId = [ $this, 'addFeatureId' ];
  678. $row[$fieldName] = array_map(function ($item) use ($fieldName, $refNs, $refPk, $this__hasFeatureId, $this__addFeatureId) {
  679. if (1 === count($item) && !empty($item['p5:links'])) return $item;
  680. $pk = V::get($refPk, '', $item);
  681. $featureId = "{$refNs}.{$pk}";
  682. if (!$this__hasFeatureId($featureId)) {
  683. $this__addFeatureId($featureId);
  684. return $item;
  685. } else {
  686. $ns = Core_AclHelper::parseTypeName($fieldName);
  687. return [
  688. 'xlink' => "{$ns['url']}#{$ns['name']}.{$pk}",
  689. ];
  690. }
  691. }, $items);
  692. } else { // TODO: field is not ref
  693. DBG::log($items, 'array', "NotImplemented - add remote items for non ref field \$items[{$primaryKey}][{$fieldName}]?");
  694. }
  695. }
  696. return $row;
  697. }
  698. public function hasFeatureId($featureId) {
  699. return in_array($featureId, $this->_foundFeatures);
  700. }
  701. public function addFeatureId($featureId) {
  702. $this->_foundFeatures[] = $featureId;
  703. DBG::log($this->_foundFeatures, 'array', "addFeatureId({$featureId})");
  704. }
  705. public function getAclSqlPrimaryKeyField() {
  706. return ($this->_acl instanceof Core_AclBase)
  707. ? $this->_acl->getSqlPrimaryKeyField()
  708. : 'ID';
  709. }
  710. }