3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 |
9 +--------------------------------------------------------------------+
13 use Civi\API\Exception\UnauthorizedException
;
16 * Query builder for civicrm_api_basic_get.
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.
22 * Automatically joins on custom fields to return or filter by them.
24 * Supports an additional sql fragment which the calling api can provide.
28 abstract class SelectQuery
{
32 MAIN_TABLE_ALIAS
= 'a';
46 protected $selectFields = [];
50 public $isFillUniqueFields = FALSE;
52 * @var \CRM_Utils_SQL_Select
58 protected $joins = [];
62 protected $apiFieldSpec;
66 protected $entityFieldNames;
70 protected $aclFields = [];
74 protected $checkPermissions;
76 protected $apiVersion;
79 * @param string $entity
80 * @param bool $checkPermissions
82 public function __construct($entity, $checkPermissions) {
83 $this->entity
= $entity;
84 require_once 'api/v3/utils.php';
85 $baoName = _civicrm_api3_get_BAO($entity);
86 $bao = new $baoName();
88 $this->entityFieldNames
= _civicrm_api3_field_names(_civicrm_api3_build_fields_array($bao));
89 $this->apiFieldSpec
= $this->getFields();
91 $this->query
= \CRM_Utils_SQL_Select
::from($bao->tableName() . ' ' . self
::MAIN_TABLE_ALIAS
);
93 // Add ACLs first to avoid redundant subclauses
94 $this->checkPermissions
= $checkPermissions;
95 $this->query
->where($this->getAclClause(self
::MAIN_TABLE_ALIAS
, $baoName));
99 * Build & execute the query and return results array
102 * @throws \API_Exception
103 * @throws \CRM_Core_Exception
106 public function run() {
107 $this->buildSelectFields();
109 $this->buildWhereClause();
110 if (in_array('count_rows', $this->select
)) {
111 $this->query
->select("count(*) as c");
114 foreach ($this->selectFields
as $column => $alias) {
115 $this->query
->select("$column as `$alias`");
118 $this->buildOrderBy();
122 if (!empty($this->limit
) ||
!empty($this->offset
)) {
123 $this->query
->limit($this->limit
, $this->offset
);
126 $result_entities = [];
127 $result_dao = \CRM_Core_DAO
::executeQuery($this->query
->toSQL());
129 while ($result_dao->fetch()) {
130 if (in_array('count_rows', $this->select
)) {
131 return (int) $result_dao->c
;
133 $result_entities[$result_dao->id
] = [];
134 foreach ($this->selectFields
as $column => $alias) {
135 $returnName = $alias;
136 $alias = str_replace('.', '_', $alias);
137 if (property_exists($result_dao, $alias) && $result_dao->$alias != NULL) {
138 $result_entities[$result_dao->id
][$returnName] = $result_dao->$alias;
140 // Backward compatibility on fields names.
141 if ($this->isFillUniqueFields
&& !empty($this->apiFieldSpec
[$alias]['uniqueName'])) {
142 $result_entities[$result_dao->id
][$this->apiFieldSpec
[$alias]['uniqueName']] = $result_dao->$alias;
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']];
151 return $result_entities;
155 * @param \CRM_Utils_SQL_Select $sqlFragment
156 * @return SelectQuery
158 public function merge($sqlFragment) {
159 $this->query
->merge($sqlFragment);
164 * Joins onto an fk field
166 * Adds one or more joins to the query to make this field available for use in a clause.
168 * Enforces permissions at the api level and by appending the acl clause for that entity to the join.
170 * @param $fkFieldName
174 * Returns the table and field name for adding this field to a SELECT or WHERE clause
175 * @throws \API_Exception
176 * @throws \Civi\API\Exception\UnauthorizedException
178 protected function addFkField($fkFieldName, $side) {
179 $stack = explode('.', $fkFieldName);
180 if (count($stack) < 2) {
183 $prev = self
::MAIN_TABLE_ALIAS
;
184 foreach ($stack as $depth => $fieldName) {
185 // Setup variables then skip the first level
188 // We only join on core fields
189 // @TODO: Custom contact ref fields could be supported too
190 if (!in_array($fk, $this->entityFieldNames
)) {
193 $fkField = &$this->apiFieldSpec
[$fk];
196 // More than 4 joins deep seems excessive - DOS attack?
197 if ($depth > self
::MAX_JOINS
) {
198 throw new UnauthorizedException("Maximum number of joins exceeded in parameter $fkFieldName");
200 $subStack = array_slice($stack, 0, $depth);
201 $this->getJoinInfo($fkField, $subStack);
202 if (!isset($fkField['FKApiName']) ||
!isset($fkField['FKClassName'])) {
203 // Join doesn't exist - might be another param with a dot in it for some reason, we'll just ignore it.
206 // Ensure we have permission to access the other api
207 if (!$this->checkPermissionToJoin($fkField['FKApiName'], $subStack)) {
208 throw new UnauthorizedException("Authorization failed to join onto {$fkField['FKApiName']} api in parameter $fkFieldName");
210 if (!isset($fkField['FKApiSpec'])) {
211 $fkField['FKApiSpec'] = \
_civicrm_api_get_fields($fkField['FKApiName']);
213 $fieldInfo = \CRM_Utils_Array
::value($fieldName, $fkField['FKApiSpec']);
215 $keyColumn = \CRM_Utils_Array
::value('FKKeyColumn', $fkField, 'id');
216 if (!$fieldInfo ||
!isset($fkField['FKApiSpec'][$keyColumn])) {
217 // Join doesn't exist - might be another param with a dot in it for some reason, we'll just ignore it.
220 $fkTable = \CRM_Core_DAO_AllCoreTables
::getTableForClass($fkField['FKClassName']);
221 $tableAlias = implode('_to_', $subStack) . "_to_$fkTable";
224 $joinCondition = array_merge(
225 ["$prev.$fk = $tableAlias.$keyColumn"],
226 $this->getAclClause($tableAlias, \
_civicrm_api3_get_BAO($fkField['FKApiName']), $subStack)
229 if (!empty($fkField['FKCondition'])) {
230 $joinCondition[] = str_replace($fkTable, $tableAlias, $fkField['FKCondition']);
233 $this->join($side, $fkTable, $tableAlias, $joinCondition);
235 if (strpos($fieldName, 'custom_') === 0) {
236 list($tableAlias, $fieldName) = $this->addCustomField($fieldInfo, $side, $tableAlias);
239 // Get ready to recurse to the next level
241 $fkField = &$fkField['FKApiSpec'][$fieldName];
244 return [$tableAlias, $fieldName];
248 * Get join info for dynamically-joined fields (e.g. "entity_id", "option_group")
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']);
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']}')";
271 * Joins onto a custom field
273 * Adds a join to the query to make this field available for use in a clause.
275 * @param array $customField
276 * @param string $side
277 * @param string $baseTable
279 * Returns the table and field name for adding this field to a SELECT or WHERE clause
281 protected function addCustomField($customField, $side, $baseTable = self
::MAIN_TABLE_ALIAS
) {
282 $tableName = $customField["table_name"];
283 $columnName = $customField["column_name"];
284 $tableAlias = "{$baseTable}_to_$tableName";
285 $this->join($side, $tableName, $tableAlias, ["`$tableAlias`.entity_id = `$baseTable`.id"]);
286 return [$tableAlias, $columnName];
290 * Fetch a field from the getFields list
292 * @param string $fieldName
295 abstract protected function getField($fieldName);
298 * Perform input validation on params that use the join syntax
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.
307 protected function validateNestedInput($fieldName, &$value) {
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'];
315 $params = [$fieldName => $value];
316 \
_civicrm_api3_validate_fields($entity, 'get', $params, $spec);
317 $value = $params[$fieldName];
321 * Check permission to join onto another api entity
323 * @param string $entity
324 * @param array $fieldStack
325 * The stack of fields leading up to this join
328 protected function checkPermissionToJoin($entity, $fieldStack) {
329 if (!$this->checkPermissions
) {
332 // Build an array of params that relate to the joined entity
336 'check_permissions' => $this->checkPermissions
,
338 $prefix = implode('.', $fieldStack) . '.';
339 $len = strlen($prefix);
340 foreach ($this->select
as $key => $ret) {
341 if (strpos($key, $prefix) === 0) {
342 $params['return'][substr($key, $len)] = $ret;
345 foreach ($this->where
as $key => $param) {
346 if (strpos($key, $prefix) === 0) {
347 $params[substr($key, $len)] = $param;
351 return \Civi
::service('civi_api_kernel')->runAuthorize($entity, 'get', $params);
355 * Get acl clause for an entity
357 * @param string $tableAlias
358 * @param string $baoName
359 * @param array $stack
362 protected function getAclClause($tableAlias, $baoName, $stack = []) {
363 if (!$this->checkPermissions
) {
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
)) {
372 $clauses = $baoName::getSelectWhereClause($tableAlias);
374 // Track field clauses added to the main entity
375 $this->aclFields
= array_keys($clauses);
377 return array_filter($clauses);
381 * Orders the query by one or more fields
383 * @throws \API_Exception
384 * @throws \Civi\API\Exception\UnauthorizedException
386 protected function buildOrderBy() {
387 $sortParams = is_string($this->orderBy
) ?
explode(',', $this->orderBy
) : (array) $this->orderBy
;
388 foreach ($sortParams as $index => $item) {
390 if ($item == '(1)') {
393 $words = preg_split("/[\s]+/", $item);
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]);
399 $this->query
->orderBy(self
::MAIN_TABLE_ALIAS
. '.' . $field['name'] . $direction, NULL, $index);
401 elseif (strpos($words[0], '.')) {
402 $join = $this->addFkField($words[0], 'LEFT');
404 $this->query
->orderBy("`{$join[0]}`.`{$join[1]}`$direction", NULL, $index);
408 throw new \
API_Exception("Unknown field specified for sort. Cannot order by '$item'");
415 * @param string $side
416 * @param string $tableName
417 * @param string $tableAlias
418 * @param array $conditions
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));
429 * Populate where clauses
431 * @throws \Civi\API\Exception\UnauthorizedException
434 abstract protected function buildWhereClause();
437 * Populate $this->selectFields
439 * @throws \Civi\API\Exception\UnauthorizedException
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;
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";
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'];
463 elseif (strpos($fieldName, '.')) {
464 $fkField = $this->addFkField($fieldName, 'LEFT');
466 $this->selectFields
[implode('.', $fkField)] = $fieldName;
469 elseif ($field && strpos($fieldName, 'custom_') === 0) {
470 list($table_name, $column_name) = $this->addCustomField($field, 'LEFT');
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;
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;
492 abstract protected function getFields();