AclQueryFeatures.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  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: throw new Exception("Not Implemented special filter '".substr($k, 3)."'");
  313. }
  314. } else if ('ogc:Filter' === $k) {
  315. $this->_query->where($this->parseOgcFilter($v));
  316. } else if ('primaryKey' === $k) {
  317. $fieldName = $this->_acl->getPrimaryKeyField();
  318. $fieldType = $this->_acl->getXsdFieldType($fieldName);
  319. if (is_array($v)) {
  320. DBG::log([ $fieldName, $v, $fieldType ], 'array', "parseQueryValue :: primaryKey, value is array");
  321. $this->_query->where([ $fieldName, 'or', array_map(function ($pk) use ($fieldName) {
  322. return [ $fieldName, '=', $pk ];
  323. }, $v) ]);
  324. } else {
  325. list($comparisonSign, $value) = $this->parseQueryValue($fieldName, $v, $fieldType);
  326. DBG::log([ $fieldName, $comparisonSign, $value, $fieldType ], 'array', "parseQueryValue");
  327. $this->_query->where([$fieldName, $comparisonSign, $value]);
  328. }
  329. } else if ('__backRef' === $k) { // skip - parse below
  330. } else if ('__childRef' === $k) { // skip - parse below
  331. } else if ('limit' === $k) {
  332. } else if ('limitstart' === $k) {
  333. } else if ('order_by' === $k) {
  334. } else if ('order_dir' === $k) {
  335. } else if ('sortBy' === $k) {
  336. } else {
  337. throw new Exception("Not Implemented param '{$k}' = '{$v}'");
  338. }
  339. }
  340. // sf_Access: if 'SHOW' then show all rows, but data with ***
  341. if ('SHOW' !== V::get('sf_Access', '', $this->_params)) $this->_query->where($this->parseSpecialFilterAccess());
  342. if (array_key_exists('__backRef', $this->_params)) {
  343. $backRef = $this->_params['__backRef'];
  344. if (!is_array($backRef)) throw new Exception("Wrong back ref structure - expected array");
  345. if (empty($backRef['namespace'])) throw new Exception("Wrong back ref structure - missing namespace");
  346. if (empty($backRef['primaryKey'])) throw new Exception("Wrong back ref structure - missing primaryKey");
  347. if (empty($backRef['fieldName'])) throw new Exception("Wrong back ref structure - missing fieldName");
  348. // TODO: $this->_query->where([ '__backRef' ]); or $this->_query->join([ '__backRef' ]);
  349. $refAcl = ACL::getAclByNamespace($backRef['namespace']);
  350. if ($refAcl->getSourceName() !== $this->_acl->getSourceName()) throw new Exception("Not implemented join with different source");
  351. $refTable = ACL::getRefTable($refAcl->getNamespace(), $backRef['fieldName']);
  352. // TODO: 'in' operator? // $this->_query->where($pkField, 'in', "");
  353. $sqlPk = $this->getAclSqlPrimaryKeyField();
  354. $sqlBackRefPk = DB::getPDO()->quote($backRef['primaryKey']);
  355. $limit = V::get('limit', 10, $this->_params, 'int');
  356. $offset = V::get('limitstart', 0, $this->_params, 'int');
  357. DBG::log(['limit' => $limit, 'offset' => $offset], 'array', "DBG: limit with __backRef \$this->_params");
  358. $sqlLimit = "limit {$limit} offset {$offset}";
  359. // $this->_query->where("
  360. // t.{$sqlPk} in (
  361. // select refTable.REMOTE_PRIMARY_KEY
  362. // from `{$refTable}` refTable
  363. // where refTable.PRIMARY_KEY = {$sqlBackRefPk}
  364. // order by refTable.REMOTE_PRIMARY_KEY DESC -- TODO refTable.SORT_PRIO
  365. // -- {$sqlLimit} -- BUG MariaDB not support limit in subquery
  366. // )
  367. // ");
  368. // TODO: convert `where t.ID in ( ... )` into `join` and `order by`
  369. // join `CRM__#REF_TABLE__120_VIEW` refTable on (refTable.REMOTE_PRIMARY_KEY = t.ID and refTable.PRIMARY_KEY = '37' )
  370. DBG::log([
  371. 'ACL::getRefTable(...)' => [$refAcl->getNamespace(), $backRef['fieldName']],
  372. '$backRef' => $backRef,
  373. '$refTable' => $refTable
  374. ], 'array', "DBG: join \$join class(".get_class($join).")");
  375. $this->_query->join($refTable, 'refTable', [ 'rawJoin' => "t.{$sqlPk} = refTable.REMOTE_PRIMARY_KEY and refTable.PRIMARY_KEY = {$sqlBackRefPk}" ]);
  376. // moved to getItems: $this->_query->orderBy("refTable.REMOTE_PRIMARY_KEY DESC"); // TODO: order by refTable.SORT_PRIO
  377. }
  378. if (array_key_exists('__childRef', $this->_params)) {
  379. $childRef = $this->_params['__childRef'];
  380. if (!is_array($childRef)) throw new Exception("Wrong child ref structure - expected array");
  381. if (empty($childRef['namespace'])) throw new Exception("Wrong child ref structure - missing namespace");
  382. if (empty($childRef['primaryKey'])) throw new Exception("Wrong child ref structure - missing primaryKey");
  383. $refAcl = ACL::getAclByNamespace($childRef['namespace']);
  384. if ($refAcl->getSourceName() !== $this->_acl->getSourceName()) throw new Exception("Not implemented join with different source");
  385. $refTypeName = Api_WfsNs::typeName($childRef['namespace']);
  386. DBG::log("\$refTypeName({$refTypeName})");
  387. $refTable = ACL::getRefTable($this->_acl->getNamespace(), $refTypeName);
  388. // TODO: 'in' operator? // $this->_query->where($pkField, 'in', "");
  389. $sqlPk = $this->getAclSqlPrimaryKeyField();
  390. $sqlChildRefPk = DB::getPDO()->quote($childRef['primaryKey']);
  391. $this->_query->where("
  392. t.{$sqlPk} in (
  393. select refTable.PRIMARY_KEY
  394. from `{$refTable}` refTable
  395. where refTable.REMOTE_PRIMARY_KEY = {$sqlChildRefPk}
  396. )
  397. ");
  398. }
  399. DBG::log($this->_query, 'array', "TODO: optimize \$this->_query");
  400. $this->_USE_TEMPORARY_TABLE = false; // TODO: ...
  401. if ($this->_USE_TEMPORARY_TABLE) {
  402. $sortBy = ($this->hasParam('sortBy')) ? $this->getParam('sortBy') : null;
  403. if (!$sortBy) {
  404. $sortBy = $this->hasParam('order_by')
  405. ? ( $this->hasParam('order_dir')
  406. ? $this->getParam('order_by') . " " . $this->getParam('order_dir')
  407. : $this->getParam('order_by')
  408. )
  409. : '';
  410. }
  411. $TMP_TABLE_NAME = $this->_acl->getRootTableName() . "__#TEMPORARY";
  412. DBG::log("\$TMP_TABLE_NAME='{$TMP_TABLE_NAME}'");
  413. Lib::loadClass('AntAclBase');
  414. if ($this->_acl instanceof AntAclBase) {
  415. $baseSql = $this->_query->generateSql();
  416. DB::getPDO()->execSql("
  417. create temporary table `{$TMP_TABLE_NAME}`
  418. {$baseSql}
  419. ");
  420. DBG::log(DB::getPDO()->fetchValue("select count(*) as cnt from `{$TMP_TABLE_NAME}`"), 'array', "select count(*) cnt from '{$TMP_TABLE_NAME}'");
  421. $tmpAclFrom = clone($this->_acl);
  422. $tmpAclFrom->_rootTableName = $TMP_TABLE_NAME;
  423. // $tmpAclFrom = AntAclBase::buildInstance($this->_acl->getID(), [
  424. // 'name' => $this->_acl->getName(),
  425. // '_rootTableName' => $TMP_TABLE_NAME,
  426. // 'idDatabase' => $this->_acl->getDatabaseID(),
  427. // 'namespace' => $this->_acl->getNamespace(),
  428. // 'primaryKey' => $this->_acl->getPrimaryKeyField(),
  429. // 'field' => $this->_acl->getFields(),
  430. // ]);
  431. Lib::loadClass('AclQueryBuilder');
  432. $query = new AclQueryBuilder();
  433. $query->from($tmpAclFrom, $prefix = 't');
  434. DBG::log($query, 'array', "TODO: \$query by temporary table");
  435. // $this->_query = $query;
  436. // return $this->_query;
  437. }
  438. }
  439. return clone($this->_query);
  440. }
  441. public function getTotal() {
  442. $this->_beforeFetchData();
  443. if ($this->_legacyMode) return $this->_acl->getTotal($this->_params);
  444. if (null !== $this->_total) return $this->_total;
  445. $this->_total = $this->getQuery()->fetchTotal();
  446. return $this->_total;
  447. }
  448. public function hasParam($key) { return !empty($this->_params[$key]); }
  449. public function getParam($key) { return V::get($key, '', $this->_params); }
  450. public function getItems() {
  451. $this->_logToFile('getItems() ...');
  452. $this->_beforeFetchData();
  453. if ($this->_legacyMode) return $this->_acl->getItems($this->_params);// TODO: array_map( $r => (array)$r )
  454. // 'limit' => 10,
  455. // 'limitstart' => 0,
  456. // 'order_by' => 'ID',
  457. // 'order_dir' => 'desc',
  458. // TODO: sortBy from wfs query
  459. $sortBy = ($this->hasParam('sortBy')) ? $this->getParam('sortBy') : null;
  460. if (!$sortBy && array_key_exists('__backRef', $this->_params)) {
  461. $sortBy = "refTable.REMOTE_PRIMARY_KEY DESC"; // TODO: order by refTable.SORT_PRIO
  462. }
  463. if (!$sortBy) {
  464. $sortBy = $this->hasParam('order_by')
  465. ? ( $this->hasParam('order_dir')
  466. ? $this->getParam('order_by') . " " . $this->getParam('order_dir')
  467. : $this->getParam('order_by')
  468. )
  469. : '';
  470. }
  471. $limit = V::get('limit', 10, $this->_params, 'int');
  472. $offset = V::get('limitstart', 0, $this->_params, 'int');
  473. DBG::log(['params' => $this->_params, 'sortBy' => $sortBy, 'limit' => $limit, 'offset' => $offset], 'array', '$this->_params');
  474. $select = $this->prepareSelect();
  475. DBG::log($select, 'array', "\$select is(TableAcl)=(".($this->_acl instanceof TableAcl).")");
  476. // DBG::log($this->getQuery(), 'array', "\$select is(TableAcl)=(".($this->_acl instanceof TableAcl).") \$this->getQuery()");
  477. $items = $this->fetchRowsRefs(
  478. $this->getQuery()
  479. ->select(array_merge(['@primaryKey'], $select))
  480. ->limit($limit)
  481. ->offset($offset)
  482. ->orderBy($sortBy)
  483. ->fetchAll()
  484. );
  485. $this->_logToFile('getItems() fetched.');
  486. return $items;
  487. }
  488. function _beforeFetchData() {
  489. if (method_exists($this->_acl, 'onBeforeFetchData')) $this->_acl->onBeforeFetchData();
  490. }
  491. public function getItem($primaryKey) { // TODO: throw exception if not found?
  492. $this->_beforeFetchData();
  493. if ($this->_legacyMode) return (array)$this->_acl->getItem($primaryKey, $this->_params);
  494. $select = $this->prepareSelect();
  495. $pkField = $this->_acl->getPrimaryKeyField();
  496. return $this->fetchRowRefs(
  497. $this->getQuery()
  498. ->select($select)
  499. ->where([$pkField, '=', $primaryKey])
  500. ->fetchFirst()
  501. );
  502. }
  503. public function prepareSelect() { // TODO: replace with getSelectLocal
  504. // TODO: select from params: 'cols' => [ fieldName, ... ]
  505. // TODO: select from params: '@instances' => 1
  506. // TODO: if no fields set, then '*'
  507. // TODO: select must contain primaryKey
  508. return $this->getSelectLocal();
  509. }
  510. public function getSelectLocal() { // @returns [ $fieldName, ... ]
  511. // TODO: rawSelect!
  512. if (null !== $this->_selectLocalFields) return $this->_selectLocalFields;
  513. $this->_selectLocalFields = [];
  514. $todoFetchAllCols = false; // select t.*
  515. if (!empty($this->_params['cols'])) {
  516. if (in_array('*', $this->_params['cols'])) $todoFetchAllCols = true;
  517. $acl = $this->_acl;
  518. $this->_selectLocalFields = array_filter($this->_params['cols'], function ($fieldQuery) use ($acl) {
  519. if ('*' === $fieldQuery) return false;
  520. list($fieldName, $subFieldQuery) = explode('/', $fieldQuery, 2);
  521. if (!empty($subFieldQuery)) return false;
  522. return $acl->isLocalField($fieldName);
  523. });
  524. }
  525. if (!empty($this->_params['@instances'])) $this->_selectLocalFields[] = '@instances';
  526. if (empty($this->_selectLocalFields)) $todoFetchAllCols = true;
  527. if (1 === count($this->_selectLocalFields) && in_array('@instances', $this->_selectLocalFields)) $todoFetchAllCols = true;
  528. // if ($this->_acl instanceof TableAcl) {
  529. // $rawSelect = $this->_acl->getDataSource()->_getSqlCols();
  530. // DBG::log($rawSelect, 'string', "DBG raw select");
  531. // if ('*' !== $rawSelect && 't.*' !== $rawSelect) {
  532. // $this->_selectLocalFields['rawSelect'] = $rawSelect;
  533. // }
  534. // }
  535. if (!empty($this->_params['cols'])) DBG::log($this->_params['cols'], 'array', "\$this->_params[cols] (" . ($this->_acl ? $this->_acl->getNamespace() : 'unknown') . ")");
  536. if ($todoFetchAllCols) {
  537. // $this->_selectLocalFields[] = '*'; // TODO: select all $this->from local fields
  538. DBG::log($this->_acl->getLocalFieldList(), 'array', "\$this->_acl->getLocalFieldList()");
  539. foreach ($this->_acl->getLocalFieldList() as $localFieldName) {
  540. $this->_selectLocalFields[] = $localFieldName;
  541. }
  542. }
  543. $primaryKeyField = $this->getAclSqlPrimaryKeyField();
  544. if (!in_array($primaryKeyField, $this->_selectLocalFields)) {
  545. $this->_selectLocalFields[] = $primaryKeyField;
  546. }
  547. // TODO: always add A_ADM_COMPANY, A_CLASSIFIED, L_APPOITMENT_USER ?
  548. DBG::log($this->_selectLocalFields, 'array', '$this->_selectLocalFields');
  549. return $this->_selectLocalFields;
  550. }
  551. public function getSelectRemote() { // @returns [ $fieldName => [ $fieldName, ... ] ]
  552. if (null !== $this->_selectRemote) return $this->_selectRemote;
  553. $this->_selectRemote = [];
  554. if (!empty($this->_params['cols'])) {
  555. $cols = $this->_params['cols'];
  556. if (in_array('*', $cols)) {
  557. $this->_selectLocalFields[] = '*';
  558. $cols = array_filter($cols, function ($fieldQuery) { return '*' !== $fieldQuery; });
  559. }
  560. $acl = $this->_acl;
  561. $cols = array_filter($cols, function ($fieldQuery) use ($acl) {
  562. list($fieldName, $subFieldQuery) = explode('/', $fieldQuery, 2);
  563. // if (empty($subFieldQuery)) return false;
  564. return !$acl->isLocalField($fieldName);
  565. });
  566. foreach ($cols as $fieldQuery) { // group by fieldName
  567. list($fieldName, $subFieldQuery) = explode('/', $fieldQuery, 2);
  568. if (!array_key_exists($fieldName, $this->_selectRemote)) $this->_selectRemote[$fieldName] = [];
  569. if (!empty($subFieldQuery)) $this->_selectRemote[$fieldName][] = $subFieldQuery;
  570. }
  571. }
  572. return $this->_selectRemote;
  573. }
  574. public function fetchRowsRefs($rows) {
  575. $pkField = $this->_acl->getPrimaryKeyField();
  576. $namespace = $this->_acl->getNamespace();
  577. $this->_foundFeatures = array_merge($this->_foundFeatures, array_map(function ($row) use ($namespace, $pkField) {
  578. return "{$namespace}." . V::get($pkField, '', $row);
  579. }, $rows));
  580. DBG::log($this->_foundFeatures, 'array', "_foundFeatures");
  581. return array_map([ $this, 'fetchRowRefs' ], $rows);
  582. }
  583. public function fetchRowRefs($row) {
  584. try {
  585. return $this->_fetchRowRefs($row);
  586. } catch (Exception $e) {
  587. DBG::log($e);
  588. }
  589. return $row;
  590. }
  591. public function _fetchRowRefs($row) {
  592. if (!$row) return $row;
  593. $sqlPk = $this->getAclSqlPrimaryKeyField();
  594. $primaryKey = $row[$sqlPk];
  595. DBG::log($row, 'array', "DBG primaryKey '{$primaryKey}'");
  596. if (!$primaryKey) throw new Exception("Missing primaryKey");
  597. $defaultRefLimit = 10; // TODO: get from $this->_params and pass to nested buildQuery
  598. $refLimitPlus1 = $defaultRefLimit + 1;
  599. foreach ($this->getSelectRemote() as $fieldName => $cols) {
  600. DBG::log($cols, 'array', "add select remote '{$fieldName}' \$cols");
  601. $xsdType = $this->_acl->getXsdFieldType($fieldName);
  602. if ('ref:' === substr($xsdType, 0, 4) && empty($cols)) {
  603. DBG::log("add remote xlink's '{$fieldName}' \$items[{$primaryKey}] ...");
  604. $refTable = ACL::getRefTable($this->_acl->getNamespace(), $fieldName);
  605. if (!$refTable) DBG::log("BUG: Missing refTable in add remote xlink's '{$fieldName}' \$items[{$primaryKey}]");
  606. if ($refTable) {
  607. $xlinks = DB::getPDO()->fetchAll("
  608. select r.REMOTE_PRIMARY_KEY
  609. from `{$refTable}` r
  610. where r.PRIMARY_KEY = '{$primaryKey}'
  611. order by r.REMOTE_PRIMARY_KEY DESC -- TODO r.SORT_PRIO
  612. limit {$refLimitPlus1}
  613. ");
  614. DBG::log($xlinks, 'array', "add remote xlink's for '{$fieldName}' \$items[{$primaryKey}]");
  615. $row[$fieldName] = array_map(function ($refInfo) use ($fieldName) {
  616. $ns = Core_AclHelper::parseTypeName($fieldName);
  617. return [
  618. // '_ns' => $ns,
  619. 'xlink' => "{$ns['url']}#{$ns['name']}.{$refInfo['REMOTE_PRIMARY_KEY']}",
  620. ];
  621. }, $xlinks);
  622. if (count($xlinks) > $defaultRefLimit) DBG::log('TODO: xlink FETCH MORE DATA...');
  623. if (count($xlinks) > $defaultRefLimit) $row[$fieldName][] = [ 'p5:links' => [
  624. 'p5:next' => [
  625. '@typeName' => $fieldName,
  626. '@backRefNS' => $this->_acl->getNamespace(),
  627. '@backRefPK' => $primaryKey,
  628. '@startIndex' => $defaultRefLimit,
  629. '@maxFeatures' => $defaultRefLimit,
  630. '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}",
  631. ],
  632. ] ];
  633. DBG::log($row[$fieldName], 'array', "remote xlinks for \$items[{$primaryKey}][{$fieldName}]");
  634. }
  635. } else if ('ref:' === substr($xsdType, 0, 4) && !empty($cols)) {
  636. $refAcl = ACL::getAclByTypeName($fieldName);
  637. $refQuery = $refAcl->buildQuery([
  638. 'cols' => $cols,
  639. '__backRef' => [
  640. 'namespace' => $this->_acl->getNamespace(),
  641. 'primaryKey' => $primaryKey,
  642. 'fieldName' => $fieldName,
  643. ],
  644. 'limit' => $refLimitPlus1,
  645. 'skipFeaturesAsXlink' => $this->_foundFeatures
  646. // TODO: add $defaultRefLimit + 1
  647. ]);
  648. $totalRefs = $refQuery->getTotal();
  649. $items = $refQuery->getItems([ 'limit' => $defaultRefLimit ]);
  650. // TODO: if (count($items) > $defaultRefLimit) // TODO: add item for GUI - has more data + wfs link to fetch more (offset)
  651. DBG::log($items, 'array', "add remote items '{$fieldName}' \$items[{$primaryKey}][{$fieldName}] total({$totalRefs})");
  652. if ($totalRefs > $defaultRefLimit) {
  653. DBG::log('TODO: resolve recurse fetch more data link');
  654. array_pop($items); // remove last item
  655. $items[] = [ 'p5:links' => [
  656. 'p5:next' => [
  657. '@typeName' => $fieldName,
  658. '@backRefNS' => $this->_acl->getNamespace(),
  659. '@backRefPK' => $primaryKey,
  660. '@startIndex' => $defaultRefLimit,
  661. '@maxFeatures' => $defaultRefLimit,
  662. '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}",
  663. ],
  664. ] ];
  665. }
  666. $refNs = $refAcl->getNamespace();
  667. $refPk = $refAcl->getPrimaryKeyField();
  668. $this__hasFeatureId = [ $this, 'hasFeatureId' ];
  669. $this__addFeatureId = [ $this, 'addFeatureId' ];
  670. $row[$fieldName] = array_map(function ($item) use ($fieldName, $refNs, $refPk, $this__hasFeatureId, $this__addFeatureId) {
  671. if (1 === count($item) && !empty($item['p5:links'])) return $item;
  672. $pk = V::get($refPk, '', $item);
  673. $featureId = "{$refNs}.{$pk}";
  674. if (!$this__hasFeatureId($featureId)) {
  675. $this__addFeatureId($featureId);
  676. return $item;
  677. } else {
  678. $ns = Core_AclHelper::parseTypeName($fieldName);
  679. return [
  680. 'xlink' => "{$ns['url']}#{$ns['name']}.{$pk}",
  681. ];
  682. }
  683. }, $items);
  684. } else { // TODO: field is not ref
  685. DBG::log($items, 'array', "NotImplemented - add remote items for non ref field \$items[{$primaryKey}][{$fieldName}]?");
  686. }
  687. }
  688. return $row;
  689. }
  690. public function hasFeatureId($featureId) {
  691. return in_array($featureId, $this->_foundFeatures);
  692. }
  693. public function addFeatureId($featureId) {
  694. $this->_foundFeatures[] = $featureId;
  695. DBG::log($this->_foundFeatures, 'array', "addFeatureId({$featureId})");
  696. }
  697. public function getAclSqlPrimaryKeyField() {
  698. return ($this->_acl instanceof Core_AclBase)
  699. ? $this->_acl->getSqlPrimaryKeyField()
  700. : 'ID';
  701. }
  702. }