Merge pull request #15890 from civicrm/5.20
[civicrm-core.git] / Civi / API / SelectQuery.php
CommitLineData
e47bcddb
CW
1<?php
2/*
3 +--------------------------------------------------------------------+
41498ac5 4 | Copyright CiviCRM LLC. All rights reserved. |
e47bcddb 5 | |
41498ac5
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
e47bcddb
CW
9 +--------------------------------------------------------------------+
10 */
11namespace Civi\API;
34f3bbd9 12
ab039e22 13use Civi\API\Exception\UnauthorizedException;
e47bcddb
CW
14
15/**
16 * Query builder for civicrm_api_basic_get.
17 *
18 * Fetches an entity based on specified params for the "where" clause,
19 * return properties for the "select" clause,
20 * as well as limit and order.
21 *
22 * Automatically joins on custom fields to return or filter by them.
23 *
24 * Supports an additional sql fragment which the calling api can provide.
25 *
26 * @package Civi\API
27 */
8bcc0d86 28abstract class SelectQuery {
e47bcddb 29
6c051493
CW
30 const
31 MAX_JOINS = 4,
32 MAIN_TABLE_ALIAS = 'a';
5b46e216 33
e47bcddb
CW
34 /**
35 * @var string
36 */
37 protected $entity;
c64f69d9
CW
38 public $select = [];
39 public $where = [];
40 public $orderBy = [];
8bcc0d86
CW
41 public $limit;
42 public $offset;
e47bcddb
CW
43 /**
44 * @var array
45 */
c64f69d9 46 protected $selectFields = [];
e47bcddb
CW
47 /**
48 * @var bool
49 */
8bcc0d86 50 public $isFillUniqueFields = FALSE;
e47bcddb
CW
51 /**
52 * @var \CRM_Utils_SQL_Select
53 */
54 protected $query;
2cfe873c
CW
55 /**
56 * @var array
57 */
c64f69d9 58 protected $joins = [];
e47bcddb
CW
59 /**
60 * @var array
61 */
62 protected $apiFieldSpec;
63 /**
64 * @var array
65 */
66 protected $entityFieldNames;
b53bcc5d
CW
67 /**
68 * @var array
69 */
c64f69d9 70 protected $aclFields = [];
d343069c
CW
71 /**
72 * @var string|bool
73 */
8e8bf584 74 protected $checkPermissions;
8bcc0d86
CW
75
76 protected $apiVersion;
e47bcddb
CW
77
78 /**
8bcc0d86 79 * @param string $entity
8e8bf584 80 * @param bool $checkPermissions
e47bcddb 81 */
8e8bf584 82 public function __construct($entity, $checkPermissions) {
8bcc0d86
CW
83 $this->entity = $entity;
84 require_once 'api/v3/utils.php';
85 $baoName = _civicrm_api3_get_BAO($entity);
6c051493 86 $bao = new $baoName();
e47bcddb 87
6c051493 88 $this->entityFieldNames = _civicrm_api3_field_names(_civicrm_api3_build_fields_array($bao));
8bcc0d86 89 $this->apiFieldSpec = $this->getFields();
e47bcddb 90
6c051493 91 $this->query = \CRM_Utils_SQL_Select::from($bao->tableName() . ' ' . self::MAIN_TABLE_ALIAS);
b53bcc5d 92
6c051493 93 // Add ACLs first to avoid redundant subclauses
8e8bf584 94 $this->checkPermissions = $checkPermissions;
6c051493 95 $this->query->where($this->getAclClause(self::MAIN_TABLE_ALIAS, $baoName));
e47bcddb
CW
96 }
97
d343069c
CW
98 /**
99 * Build & execute the query and return results array
100 *
066c4638 101 * @return array|int
d343069c
CW
102 * @throws \API_Exception
103 * @throws \CRM_Core_Exception
104 * @throws \Exception
105 */
e47bcddb 106 public function run() {
8bcc0d86 107 $this->buildSelectFields();
e47bcddb 108
8bcc0d86 109 $this->buildWhereClause();
258c92c6 110 if (in_array('count_rows', $this->select)) {
8bcc0d86 111 $this->query->select("count(*) as c");
e47bcddb 112 }
8bcc0d86
CW
113 else {
114 foreach ($this->selectFields as $column => $alias) {
69aae315 115 $this->query->select("$column as `$alias`");
e47bcddb 116 }
8bcc0d86
CW
117 // Order by
118 $this->buildOrderBy();
e47bcddb
CW
119 }
120
530c3791 121 // Limit
8bcc0d86
CW
122 if (!empty($this->limit) || !empty($this->offset)) {
123 $this->query->limit($this->limit, $this->offset);
e47bcddb
CW
124 }
125
c64f69d9 126 $result_entities = [];
e47bcddb
CW
127 $result_dao = \CRM_Core_DAO::executeQuery($this->query->toSQL());
128
129 while ($result_dao->fetch()) {
258c92c6 130 if (in_array('count_rows', $this->select)) {
e47bcddb
CW
131 return (int) $result_dao->c;
132 }
c64f69d9 133 $result_entities[$result_dao->id] = [];
8bcc0d86 134 foreach ($this->selectFields as $column => $alias) {
69aae315
CW
135 $returnName = $alias;
136 $alias = str_replace('.', '_', $alias);
e47bcddb 137 if (property_exists($result_dao, $alias) && $result_dao->$alias != NULL) {
69aae315 138 $result_entities[$result_dao->id][$returnName] = $result_dao->$alias;
e47bcddb
CW
139 }
140 // Backward compatibility on fields names.
984f31ae
CW
141 if ($this->isFillUniqueFields && !empty($this->apiFieldSpec[$alias]['uniqueName'])) {
142 $result_entities[$result_dao->id][$this->apiFieldSpec[$alias]['uniqueName']] = $result_dao->$alias;
e47bcddb
CW
143 }
144 foreach ($this->apiFieldSpec as $returnName => $spec) {
145 if (empty($result_entities[$result_dao->id][$returnName]) && !empty($result_entities[$result_dao->id][$spec['name']])) {
146 $result_entities[$result_dao->id][$returnName] = $result_entities[$result_dao->id][$spec['name']];
147 }
148 }
149 };
150 }
e47bcddb
CW
151 return $result_entities;
152 }
153
154 /**
155 * @param \CRM_Utils_SQL_Select $sqlFragment
4b350175 156 * @return SelectQuery
e47bcddb
CW
157 */
158 public function merge($sqlFragment) {
159 $this->query->merge($sqlFragment);
160 return $this;
161 }
69aae315
CW
162
163 /**
164 * Joins onto an fk field
165 *
166 * Adds one or more joins to the query to make this field available for use in a clause.
167 *
d343069c
CW
168 * Enforces permissions at the api level and by appending the acl clause for that entity to the join.
169 *
69aae315 170 * @param $fkFieldName
2cfe873c
CW
171 * @param $side
172 *
69aae315
CW
173 * @return array|null
174 * Returns the table and field name for adding this field to a SELECT or WHERE clause
d343069c 175 * @throws \API_Exception
ab039e22 176 * @throws \Civi\API\Exception\UnauthorizedException
69aae315 177 */
8bcc0d86 178 protected function addFkField($fkFieldName, $side) {
69aae315
CW
179 $stack = explode('.', $fkFieldName);
180 if (count($stack) < 2) {
181 return NULL;
182 }
6c051493 183 $prev = self::MAIN_TABLE_ALIAS;
69aae315
CW
184 foreach ($stack as $depth => $fieldName) {
185 // Setup variables then skip the first level
186 if (!$depth) {
187 $fk = $fieldName;
188 // We only join on core fields
189 // @TODO: Custom contact ref fields could be supported too
190 if (!in_array($fk, $this->entityFieldNames)) {
191 return NULL;
192 }
193 $fkField = &$this->apiFieldSpec[$fk];
194 continue;
195 }
4f7a32d8 196 // More than 4 joins deep seems excessive - DOS attack?
5b46e216 197 if ($depth > self::MAX_JOINS) {
3924e596 198 throw new UnauthorizedException("Maximum number of joins exceeded in parameter $fkFieldName");
4f7a32d8 199 }
466fce54
CW
200 $subStack = array_slice($stack, 0, $depth);
201 $this->getJoinInfo($fkField, $subStack);
2cfe873c 202 if (!isset($fkField['FKApiName']) || !isset($fkField['FKClassName'])) {
ab039e22 203 // Join doesn't exist - might be another param with a dot in it for some reason, we'll just ignore it.
69aae315
CW
204 return NULL;
205 }
a762b380 206 // Ensure we have permission to access the other api
b53bcc5d 207 if (!$this->checkPermissionToJoin($fkField['FKApiName'], $subStack)) {
ab039e22 208 throw new UnauthorizedException("Authorization failed to join onto {$fkField['FKApiName']} api in parameter $fkFieldName");
a762b380 209 }
69aae315
CW
210 if (!isset($fkField['FKApiSpec'])) {
211 $fkField['FKApiSpec'] = \_civicrm_api_get_fields($fkField['FKApiName']);
212 }
213 $fieldInfo = \CRM_Utils_Array::value($fieldName, $fkField['FKApiSpec']);
214
9c846e15
CW
215 $keyColumn = \CRM_Utils_Array::value('FKKeyColumn', $fkField, 'id');
216 if (!$fieldInfo || !isset($fkField['FKApiSpec'][$keyColumn])) {
ab039e22 217 // Join doesn't exist - might be another param with a dot in it for some reason, we'll just ignore it.
69aae315
CW
218 return NULL;
219 }
220 $fkTable = \CRM_Core_DAO_AllCoreTables::getTableForClass($fkField['FKClassName']);
b53bcc5d 221 $tableAlias = implode('_to_', $subStack) . "_to_$fkTable";
69aae315 222
d343069c 223 // Add acl condition
2cfe873c 224 $joinCondition = array_merge(
c64f69d9 225 ["$prev.$fk = $tableAlias.$keyColumn"],
2cfe873c
CW
226 $this->getAclClause($tableAlias, \_civicrm_api3_get_BAO($fkField['FKApiName']), $subStack)
227 );
d343069c 228
9c846e15
CW
229 if (!empty($fkField['FKCondition'])) {
230 $joinCondition[] = str_replace($fkTable, $tableAlias, $fkField['FKCondition']);
231 }
232
2cfe873c 233 $this->join($side, $fkTable, $tableAlias, $joinCondition);
69aae315
CW
234
235 if (strpos($fieldName, 'custom_') === 0) {
2cfe873c 236 list($tableAlias, $fieldName) = $this->addCustomField($fieldInfo, $side, $tableAlias);
69aae315
CW
237 }
238
239 // Get ready to recurse to the next level
240 $fk = $fieldName;
241 $fkField = &$fkField['FKApiSpec'][$fieldName];
242 $prev = $tableAlias;
243 }
c64f69d9 244 return [$tableAlias, $fieldName];
69aae315
CW
245 }
246
466fce54 247 /**
9c846e15 248 * Get join info for dynamically-joined fields (e.g. "entity_id", "option_group")
466fce54
CW
249 *
250 * @param $fkField
251 * @param $stack
252 */
253 protected function getJoinInfo(&$fkField, $stack) {
254 if ($fkField['name'] == 'entity_id') {
255 $entityTableParam = substr(implode('.', $stack), 0, -2) . 'table';
256 $entityTable = \CRM_Utils_Array::value($entityTableParam, $this->where);
257 if ($entityTable && is_string($entityTable) && \CRM_Core_DAO_AllCoreTables::getClassForTable($entityTable)) {
258 $fkField['FKClassName'] = \CRM_Core_DAO_AllCoreTables::getClassForTable($entityTable);
259 $fkField['FKApiName'] = \CRM_Core_DAO_AllCoreTables::getBriefName($fkField['FKClassName']);
260 }
261 }
9c846e15
CW
262 if (!empty($fkField['pseudoconstant']['optionGroupName'])) {
263 $fkField['FKClassName'] = 'CRM_Core_DAO_OptionValue';
264 $fkField['FKApiName'] = 'OptionValue';
265 $fkField['FKKeyColumn'] = 'value';
266 $fkField['FKCondition'] = "civicrm_option_value.option_group_id = (SELECT id FROM civicrm_option_group WHERE name = '{$fkField['pseudoconstant']['optionGroupName']}')";
267 }
466fce54
CW
268 }
269
69aae315
CW
270 /**
271 * Joins onto a custom field
272 *
273 * Adds a join to the query to make this field available for use in a clause.
274 *
275 * @param array $customField
2cfe873c 276 * @param string $side
69aae315
CW
277 * @param string $baseTable
278 * @return array
279 * Returns the table and field name for adding this field to a SELECT or WHERE clause
280 */
8bcc0d86 281 protected function addCustomField($customField, $side, $baseTable = self::MAIN_TABLE_ALIAS) {
69aae315
CW
282 $tableName = $customField["table_name"];
283 $columnName = $customField["column_name"];
284 $tableAlias = "{$baseTable}_to_$tableName";
c64f69d9
CW
285 $this->join($side, $tableName, $tableAlias, ["`$tableAlias`.entity_id = `$baseTable`.id"]);
286 return [$tableAlias, $columnName];
69aae315
CW
287 }
288
289 /**
290 * Fetch a field from the getFields list
291 *
69aae315
CW
292 * @param string $fieldName
293 * @return array|null
294 */
8bcc0d86 295 abstract protected function getField($fieldName);
69aae315 296
48488ea3 297 /**
2fa03859
CW
298 * Perform input validation on params that use the join syntax
299 *
300 * Arguably this should be done at the api wrapper level, but doing it here provides a bit more consistency
301 * in that api permissions to perform the join are checked first.
48488ea3
CW
302 *
303 * @param $fieldName
304 * @param $value
305 * @throws \Exception
306 */
8bcc0d86 307 protected function validateNestedInput($fieldName, &$value) {
48488ea3
CW
308 $stack = explode('.', $fieldName);
309 $spec = $this->apiFieldSpec;
310 $fieldName = array_pop($stack);
311 foreach ($stack as $depth => $name) {
312 $entity = $spec[$name]['FKApiName'];
313 $spec = $spec[$name]['FKApiSpec'];
314 }
c64f69d9 315 $params = [$fieldName => $value];
2fa03859
CW
316 \_civicrm_api3_validate_fields($entity, 'get', $params, $spec);
317 $value = $params[$fieldName];
48488ea3
CW
318 }
319
a762b380
CW
320 /**
321 * Check permission to join onto another api entity
322 *
323 * @param string $entity
324 * @param array $fieldStack
325 * The stack of fields leading up to this join
326 * @return bool
327 */
8bcc0d86 328 protected function checkPermissionToJoin($entity, $fieldStack) {
d343069c 329 if (!$this->checkPermissions) {
a762b380
CW
330 return TRUE;
331 }
332 // Build an array of params that relate to the joined entity
c64f69d9 333 $params = [
a762b380 334 'version' => 3,
c64f69d9 335 'return' => [],
d343069c 336 'check_permissions' => $this->checkPermissions,
c64f69d9 337 ];
a762b380
CW
338 $prefix = implode('.', $fieldStack) . '.';
339 $len = strlen($prefix);
8bcc0d86 340 foreach ($this->select as $key => $ret) {
a762b380
CW
341 if (strpos($key, $prefix) === 0) {
342 $params['return'][substr($key, $len)] = $ret;
343 }
344 }
8bcc0d86 345 foreach ($this->where as $key => $param) {
a762b380
CW
346 if (strpos($key, $prefix) === 0) {
347 $params[substr($key, $len)] = $param;
348 }
349 }
350
351 return \Civi::service('civi_api_kernel')->runAuthorize($entity, 'get', $params);
352 }
353
188fd46b 354 /**
d343069c
CW
355 * Get acl clause for an entity
356 *
357 * @param string $tableAlias
6c051493 358 * @param string $baoName
b53bcc5d 359 * @param array $stack
2cfe873c 360 * @return array
188fd46b 361 */
c64f69d9 362 protected function getAclClause($tableAlias, $baoName, $stack = []) {
d343069c 363 if (!$this->checkPermissions) {
c64f69d9 364 return [];
d343069c 365 }
b53bcc5d
CW
366 // Prevent (most) redundant acl sub clauses if they have already been applied to the main entity.
367 // FIXME: Currently this only works 1 level deep, but tracking through multiple joins would increase complexity
368 // and just doing it for the first join takes care of most acl clause deduping.
369 if (count($stack) === 1 && in_array($stack[0], $this->aclFields)) {
c64f69d9 370 return [];
b53bcc5d 371 }
20e41014 372 $clauses = $baoName::getSelectWhereClause($tableAlias);
6c051493
CW
373 if (!$stack) {
374 // Track field clauses added to the main entity
375 $this->aclFields = array_keys($clauses);
b53bcc5d 376 }
2cfe873c 377 return array_filter($clauses);
188fd46b
CW
378 }
379
530c3791
CW
380 /**
381 * Orders the query by one or more fields
382 *
530c3791
CW
383 * @throws \API_Exception
384 * @throws \Civi\API\Exception\UnauthorizedException
385 */
8bcc0d86 386 protected function buildOrderBy() {
8bcc0d86 387 $sortParams = is_string($this->orderBy) ? explode(',', $this->orderBy) : (array) $this->orderBy;
4c6cc364
CW
388 foreach ($sortParams as $index => $item) {
389 $item = trim($item);
390 if ($item == '(1)') {
391 continue;
392 }
393 $words = preg_split("/[\s]+/", $item);
530c3791
CW
394 if ($words) {
395 // Direction defaults to ASC unless DESC is specified
396 $direction = strtoupper(\CRM_Utils_Array::value(1, $words, '')) == 'DESC' ? ' DESC' : '';
397 $field = $this->getField($words[0]);
398 if ($field) {
4c6cc364 399 $this->query->orderBy(self::MAIN_TABLE_ALIAS . '.' . $field['name'] . $direction, NULL, $index);
530c3791
CW
400 }
401 elseif (strpos($words[0], '.')) {
2cfe873c 402 $join = $this->addFkField($words[0], 'LEFT');
530c3791 403 if ($join) {
4c6cc364 404 $this->query->orderBy("`{$join[0]}`.`{$join[1]}`$direction", NULL, $index);
530c3791
CW
405 }
406 }
407 else {
408 throw new \API_Exception("Unknown field specified for sort. Cannot order by '$item'");
409 }
410 }
411 }
530c3791
CW
412 }
413
2cfe873c
CW
414 /**
415 * @param string $side
416 * @param string $tableName
417 * @param string $tableAlias
418 * @param array $conditions
419 */
420 public function join($side, $tableName, $tableAlias, $conditions) {
421 // INNER JOINs take precedence over LEFT JOINs
422 if ($side != 'LEFT' || !isset($this->joins[$tableAlias])) {
423 $this->joins[$tableAlias] = $side;
424 $this->query->join($tableAlias, "$side JOIN `$tableName` `$tableAlias` ON " . implode(' AND ', $conditions));
425 }
426 }
427
8bcc0d86
CW
428 /**
429 * Populate where clauses
430 *
431 * @throws \Civi\API\Exception\UnauthorizedException
432 * @throws \Exception
433 */
434 abstract protected function buildWhereClause();
435
436 /**
437 * Populate $this->selectFields
438 *
439 * @throws \Civi\API\Exception\UnauthorizedException
440 */
441 protected function buildSelectFields() {
442 $return_all_fields = (empty($this->select) || !is_array($this->select));
443 $return = $return_all_fields ? $this->entityFieldNames : $this->select;
444 if ($return_all_fields || in_array('custom', $this->select)) {
445 foreach (array_keys($this->apiFieldSpec) as $fieldName) {
446 if (strpos($fieldName, 'custom_') === 0) {
447 $return[] = $fieldName;
448 }
449 }
450 }
451
523c222f 452 // Always select the ID if the table has one.
453 if (array_key_exists('id', $this->apiFieldSpec)) {
454 $this->selectFields[self::MAIN_TABLE_ALIAS . ".id"] = "id";
455 }
8bcc0d86
CW
456
457 // core return fields
458 foreach ($return as $fieldName) {
459 $field = $this->getField($fieldName);
460 if ($field && in_array($field['name'], $this->entityFieldNames)) {
461 $this->selectFields[self::MAIN_TABLE_ALIAS . ".{$field['name']}"] = $field['name'];
462 }
463 elseif (strpos($fieldName, '.')) {
464 $fkField = $this->addFkField($fieldName, 'LEFT');
465 if ($fkField) {
466 $this->selectFields[implode('.', $fkField)] = $fieldName;
467 }
468 }
469 elseif ($field && strpos($fieldName, 'custom_') === 0) {
470 list($table_name, $column_name) = $this->addCustomField($field, 'LEFT');
471
472 if ($field['data_type'] != 'ContactReference') {
473 // 'ordinary' custom field. We will select the value as custom_XX.
474 $this->selectFields["$table_name.$column_name"] = $fieldName;
475 }
476 else {
477 // contact reference custom field. The ID will be stored in custom_XX_id.
478 // custom_XX will contain the sort name of the contact.
479 $this->query->join("c_$fieldName", "LEFT JOIN civicrm_contact c_$fieldName ON c_$fieldName.id = `$table_name`.`$column_name`");
480 $this->selectFields["$table_name.$column_name"] = $fieldName . "_id";
481 // We will call the contact table for the join c_XX.
482 $this->selectFields["c_$fieldName.sort_name"] = $fieldName;
483 }
484 }
485 }
486 }
487
488 /**
489 * Load entity fields
490 * @return array
491 */
492 abstract protected function getFields();
493
e47bcddb 494}