AclQueryBuilder.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. <?php
  2. Lib::loadClass('P5');
  3. Lib::loadClass('Core_AclBase');
  4. Lib::loadClass('AntAclBase');
  5. Lib::loadClass('ACL');
  6. class AclQueryBuilder {
  7. public $select;
  8. public $from;
  9. public $where;
  10. /* where: array of [ $fieldName, $comparisonSign, $value ]
  11. * $fieldName - field name, TODO: xpath, null for groups (or, and)
  12. * $comparisonSign - @see where() to check allowed (implemented) signs or function names
  13. * $value - string or another $where if group (or, and)
  14. * where examples: [ $fieldName, $comparisonSign, $value ]
  15. [ 'ID', '=', '1' ] // where ID = '1'
  16. [ 'LABEL', 'like', '%abc%' ] // where LABEL like '%abc%'
  17. [ null, 'or', [] $values ] // where ( $values[0] or $values[1] or ... ) // or where $values[0] when 1 === count($values)
  18. [ null, 'and', [] $values ] // where ( $values[0] and $values[1] and ... ) // or where $values[0] when 1 === count($values)
  19. */
  20. public $orderBy;
  21. public $groupBy;
  22. public $limit;
  23. public $offset;
  24. public $_fromPrefix;
  25. public $_joinPrefix;
  26. public $_joinParams;
  27. public $isInstances;
  28. public $isNotInstances;
  29. public function __construct() {
  30. $this->select = [];
  31. $this->from = null; // (ACL | tableName)
  32. $this->where = [];
  33. $this->orderBy = null;
  34. $this->groupBy = null;
  35. $this->limit = null;
  36. $this->offset = null;
  37. $this->_fromPrefix = 't'; // prefix for this->from - default 't'
  38. $this->_joinPrefix = []; // prefix => from (Acl | tableName)
  39. $this->_joinParams = []; // prefx => params
  40. $this->isInstances = [];
  41. $this->isNotInstances = [];
  42. }
  43. public function from($from, $prefix = 't') {
  44. DBG::log([
  45. 'from instanceof Core_AclBase' => ($from instanceof Core_AclBase),
  46. 'from instanceof AntAclBase' => ($from instanceof AntAclBase),
  47. 'from instanceof TableAcl' => ($from instanceof TableAcl),
  48. ], 'array', "\$from class(".get_class($from).")");
  49. if ($this->from) throw new Exception("Duplicate FROM");
  50. $this->from = $from;
  51. $this->_fromPrefix = $prefix;
  52. return $this;
  53. }
  54. public function select($propertyName) { // TODO: ogc:propertyName, *, xpath, @instances, etc...
  55. if (empty($propertyName)) return $this; // SKIP empty values, null's, etc.
  56. DBG::log($propertyName, 'array', "AclQueryBuilder->select");
  57. if (is_array($propertyName) && !empty($propertyName['rawSelect'])) {
  58. $this->select['__rawSelect__'] = $propertyName['rawSelect'];
  59. return $this;
  60. }
  61. if (!in_array($propertyName, $this->select)) $this->select[] = $propertyName; // TODO: split by property source
  62. return $this;
  63. }
  64. public function where($where) {
  65. if (is_string($where)) return $this->whereRaw($where);
  66. list($fieldName, $comparisonSign, $value) = $where;
  67. if (!in_array($comparisonSign, [ // validation
  68. '=', '<', '>', '<=', '>=', '<>', '!='
  69. , 'like', 'not like'
  70. , 'is not null', 'is null'
  71. , 'Intersects', 'GeometryType'
  72. , 'or' // $value = [ comparisons for $fieldName ... or null ]
  73. , 'and' // $value = [ comparisons for $fieldName ... or null ]
  74. ])) {
  75. throw new Exception("Not implemented comparisonSign '{$comparisonSign}'");
  76. }
  77. $this->where[] = [$fieldName, $comparisonSign, $value];
  78. return $this;
  79. }
  80. public function _generateWhereMain($where) { // @returns string
  81. if (is_string($where)) return $where; // whereRaw
  82. list($fieldName, $comparisonSign, $value) = $where;
  83. $sqlFieldName = $fieldName; // TODO: getSqlFieldName // TODO: get sql field name with table prefix from join list to replace "{$this->_fromPrefix}.{$sqlFieldName}" below
  84. switch ($comparisonSign) {
  85. case 'is not null': return "{$this->_fromPrefix}.{$sqlFieldName} is not null";
  86. case 'is null': return "{$this->_fromPrefix}.{$sqlFieldName} is null";
  87. case 'Intersects': return "Intersects(GeomFromText('{$value}'), {$this->_fromPrefix}.`{$sqlFieldName}`)=1";
  88. case 'GeometryType': return "GeometryType({$this->_fromPrefix}.`{$sqlFieldName}`)='{$value}'";
  89. case 'or': return $this->_generateWhereBlock($where);
  90. case 'and': return $this->_generateWhereBlock($where);
  91. case 'UNIX_TIMESTAMP_LESS_THAN_NOW': return "
  92. COALESCE(UNIX_TIMESTAMP({$this->_fromPrefix}.`{$sqlFieldName}`), 0) < UNIX_TIMESTAMP()
  93. and {$this->_fromPrefix}.`{$sqlFieldName}` != ''
  94. and {$this->_fromPrefix}.`{$sqlFieldName}` != '0000-00-00 00:00:00'
  95. ";
  96. case 'UNIX_TIMESTAMP_NOW_3600': return "
  97. COALESCE(UNIX_TIMESTAMP({$this->_fromPrefix}.`{$sqlFieldName}`), 0) < UNIX_TIMESTAMP()+3600
  98. and COALESCE(UNIX_TIMESTAMP({$this->_fromPrefix}.`{$sqlFieldName}`), 0) > UNIX_TIMESTAMP()-3600
  99. ";
  100. case 'UNIX_TIMESTAMP_GREATER_THAN': return " COALESCE(UNIX_TIMESTAMP({$this->_fromPrefix}.`{$sqlFieldName}`), 0) > '{$value}' ";
  101. case 'UNIX_TIMESTAMP_LESS_THAN': return " COALESCE(UNIX_TIMESTAMP({$this->_fromPrefix}.`{$sqlFieldName}`), 0) < '{$value}' ";
  102. default: return "{$this->_fromPrefix}.{$sqlFieldName} {$comparisonSign} " . DB::getPDO()->quote($value);
  103. }
  104. return null;
  105. }
  106. public function _generateWhereBlock($where) { // @returns string
  107. list($fieldName, $sqlGlue, $list) = $where;
  108. $sqlList = array_filter(
  109. array_map([$this, '_generateWhereMain'], $list),
  110. 'is_string'
  111. );
  112. if (1 === count($sqlList)) return $sqlList[0];
  113. else return "( " . implode(" {$sqlGlue} ", $sqlList) . " )";
  114. }
  115. public function whereIsNotNull($fieldName) {
  116. $this->where[] = "{$this->_fromPrefix}.{$fieldName} is not null";
  117. return $this;
  118. }
  119. public function whereRaw($rawWhere) { // add where without validation
  120. if (!$rawWhere) return $this;
  121. $this->where[] = $rawWhere;
  122. return $this;
  123. }
  124. // public function whereFunction($column, $operator = null, $value = null) {
  125. public function whereFunction($fieldName, $comparisonSign = null, $value = null) {
  126. throw new Exception("whereFunction not supported");
  127. $this->where[] = '';
  128. return $this;
  129. }
  130. public function join($join, $prefix, $params) {
  131. if (array_key_exists($prefix, $this->_joinPrefix)) throw new Exception("Prefix already used!");
  132. $this->_joinPrefix[$prefix] = $join;
  133. $this->_joinParams[$prefix] = $params;
  134. return $this;
  135. }
  136. public function orderBy($orderBy) { // TODO: ogc: order by ...
  137. if (null !== $this->orderBy) throw new Exception("OrderBy already set!");
  138. $this->orderBy = [];
  139. if (!$orderBy) return $this;
  140. // ID A,COL_X D,COL_Y A,...
  141. $sortByEx = array_map('trim', explode(',', $orderBy));
  142. $sortByEx = array_filter($sortByEx, function ($part) { return !empty($part); });
  143. foreach ($sortByEx as $sortPart) {
  144. $sortPartEx = explode(' ', $sortPart);
  145. if (count($sortPartEx) > 2) throw new Exception("SortBy parse error #" . __LINE__);
  146. $fieldName = trim($sortPartEx[0]);
  147. if (!$this->isFieldAllowedToOrderBy($fieldName)) throw new Exception("SortBy parse error for field '{$fieldName}' #" . __LINE__);
  148. $colSortDir = 'ASC';
  149. if (count($sortPartEx) == 2) {
  150. if ('A' == strtoupper($sortPartEx[1]) || 'ASC' == strtoupper($sortPartEx[1])) {
  151. } else if ('D' == strtoupper($sortPartEx[1]) || 'DESC' == strtoupper($sortPartEx[1])) {
  152. $colSortDir = 'DESC';
  153. } else throw new Exception("SortBy parse error - unknown sort order '{$sortPartEx[1]}' #" . __LINE__);
  154. }
  155. $this->orderBy[] = [$fieldName, $colSortDir];
  156. }
  157. return $this;
  158. }
  159. public function isFieldAllowedToOrderBy($fieldName) {
  160. return true;
  161. }
  162. public function generateOrderBySql() {
  163. if (empty($this->orderBy)) return '';
  164. $sortByList = [];
  165. foreach ($this->orderBy as $orderBy) {
  166. $sortByList[] = "t.`{$orderBy[0]}` {$orderBy[1]}";
  167. }
  168. return (!empty($sortByList))
  169. ? "order by " . implode(", ", $sortByList)
  170. : '';
  171. }
  172. public function limit($limit) {
  173. $this->limit = (int)$limit;
  174. return $this;
  175. }
  176. public function offset($offset) {
  177. $this->offset = (int)$offset;
  178. return $this;
  179. }
  180. public function isInstance($instances) {
  181. $this->isInstances = (is_array($instances)) ? $instances : [ $instances ];
  182. return $this;
  183. }
  184. public function isNotInstance($instances) {
  185. $this->isNotInstances = (is_array($instances)) ? $instances : [ $instances ];
  186. return $this;
  187. }
  188. public function _parseJoinParams($params) {
  189. if (array_key_exists('rawJoin', $params)) return $params['rawJoin'];
  190. throw new Exception("Not implemented JOIN params '".json_encode($params)."'");
  191. }
  192. public function _getTableName($source) {
  193. if (is_scalar($source)) return $source;
  194. if ($source instanceof Core_AclBase) return $source->getRootTableName();
  195. throw new Exception("Not implemented FROM type '".get_class($source)."'");
  196. }
  197. public function execute() {
  198. return $this->fetchAll();
  199. }
  200. public function fetchAll() {
  201. $sql = $this->generateSql();
  202. DBG::log((array)$this, 'array', "AclQueryBuilder::fetchAll");
  203. return DB::getPDO()->fetchAll($sql);
  204. }
  205. public function fetchValue() {
  206. $sql = $this->generateSql();
  207. DBG::log((array)$this, 'array', "AclQueryBuilder::fetchValue");
  208. return DB::getPDO()->fetchValue($sql);
  209. }
  210. public function generateSql() {
  211. if (!$this->from) throw new Exception("Missing FROM");
  212. $tableName = $this->_getTableName($this->from);
  213. if (!$tableName) throw new Exception("Missing FROM table name");
  214. $sqlPk = 'ID';
  215. if ($this->from instanceof Core_AclBase) $sqlPk = $this->from->getSqlPrimaryKeyField();
  216. $sqlJoin = [];
  217. DBG::log($this, 'array', '$this');
  218. foreach ($this->isInstances as $k => $ns) {
  219. $idInstance = ACL::getInstanceId($ns);
  220. $instanceTable = ACL::getInstanceTable($ns);
  221. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  222. $prefix = "is_inst_{$k}";
  223. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  224. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  225. // and {$prefix}.idInstance = {$idInstance}
  226. // )";
  227. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} in (
  228. select {$prefix}.pk
  229. from `{$instanceTable}` {$prefix}
  230. where {$prefix}.idInstance = {$idInstance}
  231. )";
  232. DBG::log("{$this->_fromPrefix}.{$sqlPk} in (
  233. select {$prefix}.pk
  234. from `{$instanceTable}` {$prefix}
  235. where {$prefix}.idInstance = {$idInstance}
  236. )", 'string', "\$this->where[] =");
  237. }
  238. foreach ($this->isNotInstances as $k => $ns) {
  239. $idInstance = ACL::getInstanceId($ns);
  240. $instanceTable = ACL::getInstanceTable($ns);
  241. // ->join($instanceTable, 'i', [ 'rawJoin' => "i.pk = t.{$sqlPk} and i.idInstance = {$idInstance}" ])
  242. $prefix = "is_inst_{$k}";
  243. // $sqlJoin[] = " inner join `{$joinName}` {$prefix} on (
  244. // {$prefix}.pk = {$this->_fromPrefix}.{$sqlPk}
  245. // and {$prefix}.idInstance = {$idInstance}
  246. // )";
  247. $this->where[] = "{$this->_fromPrefix}.{$sqlPk} not in (
  248. select {$prefix}.pk
  249. from `{$instanceTable}` {$prefix}
  250. where {$prefix}.idInstance = {$idInstance}
  251. )";
  252. }
  253. // join `{$instanceTable}` i on(i.pk = t.{$sqlPk} and i.idInstance = {$idInstance})
  254. foreach ($this->_joinPrefix as $prefix => $join) {
  255. $joinName = $this->_getTableName($join);
  256. $sqlJoin[] = " join `{$joinName}` {$prefix} on(" . $this->_parseJoinParams($this->_joinParams[$prefix]) . ")";
  257. }
  258. $sqlJoin = (!empty($sqlJoin)) ? implode("\n\t", $sqlJoin) : "";
  259. DBG::log($this->where, 'array', "generateSql \$this->where");
  260. $sqlWhere = array_filter(
  261. array_map([$this, '_generateWhereMain'], $this->where),
  262. 'is_string'
  263. );
  264. $sqlWhere = (!empty($sqlWhere)) ? "where " . implode("\n\t and ", $sqlWhere) : '';
  265. $limit = ($this->limit < 0) ? 0 : $this->limit;
  266. $offset = ($this->offset < 0) ? 0 : $this->offset;
  267. $sqlLimit = ($limit > 0) ? "limit {$limit} offset {$offset}" : '';
  268. $sqlSelect = [];
  269. if (!empty($this->select['__rawSelect__'])) {
  270. $sqlSelect[] = $this->select['__rawSelect__'];
  271. } else {
  272. $sqlSelect[] = "{$this->_fromPrefix}.{$sqlPk}";
  273. if (in_array('*', $this->select)) $sqlSelect[] = "{$this->_fromPrefix}.*";
  274. }
  275. if (in_array('@instances', $this->select)) {
  276. if (!($this->from instanceof Core_AclBase)) throw new Exception("select @instances allowed only for Acl object");
  277. $instanceTable = ACL::getInstanceTable($this->from->getNamespace());
  278. $sqlSelect[] = "
  279. (
  280. select GROUP_CONCAT(inst_conf.namespace)
  281. from `{$instanceTable}` inst_tbl
  282. join `CRM_INSTANCE_CONFIG` inst_conf on (inst_conf.id = inst_tbl.idInstance)
  283. where inst_tbl.pk = {$this->_fromPrefix}.{$sqlPk}
  284. ) as `@instances`
  285. ";
  286. }
  287. $sqlOrderBy = $this->generateOrderBySql();
  288. $sqlSelect = (!empty($sqlSelect)) ? implode(", ", $sqlSelect) : "{$this->_fromPrefix}.*";
  289. return "
  290. select {$sqlSelect}
  291. from `{$tableName}` {$this->_fromPrefix}
  292. {$sqlJoin}
  293. {$sqlWhere}
  294. {$sqlOrderBy}
  295. {$sqlLimit}
  296. ";
  297. }
  298. }