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 +--------------------------------------------------------------------+
12 namespace Civi\Search
;
14 use CRM_Search_ExtensionUtil
as E
;
18 * @package Civi\Search
25 public static function getAdminSettings():array {
26 $schema = self
::getSchema();
27 $extensions = \CRM_Extension_System
::singleton()->getMapper();
30 'joins' => self
::getJoins(array_column($schema, NULL, 'name')),
31 'operators' => \CRM_Utils_Array
::makeNonAssociative(self
::getOperators()),
32 'functions' => \CRM_Api4_Page_Api4Explorer
::getSqlFunctions(),
33 'displayTypes' => Display
::getDisplayTypes(['id', 'name', 'label', 'description', 'icon']),
34 'styles' => \CRM_Utils_Array
::makeNonAssociative(self
::getStyles()),
35 'afformEnabled' => $extensions->isActiveModule('afform'),
36 'afformAdminEnabled' => $extensions->isActiveModule('afform_admin'),
43 public static function getOperators():array {
51 'CONTAINS' => E
::ts('Contains'),
52 'IN' => E
::ts('Is One Of'),
53 'NOT IN' => E
::ts('Not One Of'),
54 'LIKE' => E
::ts('Is Like'),
55 'NOT LIKE' => E
::ts('Not Like'),
56 'BETWEEN' => E
::ts('Is Between'),
57 'NOT BETWEEN' => E
::ts('Not Between'),
58 'IS EMPTY' => E
::ts('Is Empty'),
59 'IS NOT EMPTY' => E
::ts('Not Empty'),
66 public static function getStyles():array {
68 'default' => E
::ts('Default'),
69 'primary' => E
::ts('Primary'),
70 'success' => E
::ts('Success'),
71 'info' => E
::ts('Info'),
72 'warning' => E
::ts('Warning'),
73 'danger' => E
::ts('Danger'),
78 * Fetch all entities the current user has permission to `get`
81 public static function getSchema() {
83 $entities = \Civi\Api4\Entity
::get()
84 ->addSelect('name', 'title', 'type', 'title_plural', 'description', 'label_field', 'icon', 'paths', 'dao', 'bridge', 'ui_join_filters')
85 ->addWhere('searchable', '=', TRUE)
86 ->addOrderBy('title_plural')
88 'get' => ['$name', 'getActions', ['where' => [['name', '=', 'get']]], ['params']],
90 foreach ($entities as $entity) {
91 // Skip if entity doesn't have a 'get' action or the user doesn't have permission to use get
93 // Add paths (but only RUD actions) with translated titles
94 foreach ($entity['paths'] as $action => $path) {
95 unset($entity['paths'][$action]);
96 if (in_array($action, ['view', 'update', 'delete'], TRUE)) {
97 $entity['paths'][] = [
103 $getFields = civicrm_api4($entity['name'], 'getFields', [
104 'select' => ['name', 'title', 'label', 'description', 'options', 'input_type', 'input_attrs', 'data_type', 'serialize', 'entity', 'fk_entity', 'readonly'],
105 'where' => [['name', 'NOT IN', ['api_key', 'hash']]],
106 'orderBy' => ['label'],
108 foreach ($getFields as $field) {
109 $field['fieldName'] = $field['name'];
110 $entity['fields'][] = $field;
112 $params = $entity['get'][0];
113 // Entity must support at least these params or it is too weird for search kit
114 if (!array_diff(['select', 'where', 'orderBy', 'limit', 'offset'], array_keys($params))) {
115 \CRM_Utils_Array
::remove($params, 'checkPermissions', 'debug', 'chain', 'language', 'select', 'where', 'orderBy', 'limit', 'offset');
116 unset($entity['get']);
117 $schema[$entity['name']] = ['params' => array_keys($params)] +
array_filter($entity);
121 // Add in FK fields for implicit joins
122 // For example, add a `campaign_id.title` field to the Contribution entity
123 foreach ($schema as &$entity) {
124 if (in_array('DAOEntity', $entity['type'], TRUE) && !in_array('EntityBridge', $entity['type'], TRUE)) {
125 foreach (array_reverse($entity['fields'], TRUE) as $index => $field) {
126 if (!empty($field['fk_entity']) && !$field['options'] && !empty($schema[$field['fk_entity']]['label_field'])) {
127 $isCustom = strpos($field['name'], '.');
128 // Custom fields: append "Contact ID" to original field label
130 $entity['fields'][$index]['label'] .= ' ' . E
::ts('Contact ID');
132 // DAO fields: use title instead of label since it represents the id (title usually ends in ID but label does not)
134 $entity['fields'][$index]['label'] = $field['title'];
136 // Add the label field from the other entity to this entity's list of fields
137 $newField = \CRM_Utils_Array
::findAll($schema[$field['fk_entity']]['fields'], ['name' => $schema[$field['fk_entity']]['label_field']])[0];
138 $newField['name'] = $field['name'] . '.' . $schema[$field['fk_entity']]['label_field'];
139 $newField['label'] = $field['label'] . ' ' . $newField['label'];
140 array_splice($entity['fields'], $index, 0, [$newField]);
145 return array_values($schema);
149 * @param array $allowedEntities
152 public static function getJoins(array $allowedEntities) {
154 foreach ($allowedEntities as $entity) {
155 // Multi-record custom field groups (to-date only the contact entity supports these)
156 if (in_array('CustomValue', $entity['type'])) {
157 $targetEntity = $allowedEntities['Contact'];
158 // Join from Custom group to Contact (n-1)
159 $alias = $entity['name'] . '_Contact_entity_id';
160 $joins[$entity['name']][] = [
161 'label' => $entity['title'] . ' ' . $targetEntity['title'],
163 'entity' => 'Contact',
164 'conditions' => self
::getJoinConditions('entity_id', $alias . '.id'),
165 'defaults' => self
::getJoinDefaults($alias, $targetEntity),
169 // Join from Contact to Custom group (n-n)
170 $alias = 'Contact_' . $entity['name'] . '_entity_id';
171 $joins['Contact'][] = [
172 'label' => $entity['title_plural'],
174 'entity' => $entity['name'],
175 'conditions' => self
::getJoinConditions('id', $alias . '.entity_id'),
176 'defaults' => self
::getJoinDefaults($alias, $entity),
181 // Non-custom DAO entities
182 elseif (!empty($entity['dao'])) {
183 /* @var \CRM_Core_DAO $daoClass */
184 $daoClass = $entity['dao'];
185 $references = $daoClass::getReferenceColumns();
186 // Only the first bridge reference gets processed, so if it's dynamic we want to be sure it's first in the list
187 usort($references, function($reference) {
188 return is_a($reference, 'CRM_Core_Reference_Dynamic') ?
-1 : 1;
190 $fields = array_column($entity['fields'], NULL, 'name');
191 $bridge = in_array('EntityBridge', $entity['type']) ?
$entity['name'] : NULL;
192 foreach ($references as $reference) {
193 $keyField = $fields[$reference->getReferenceKey()] ??
NULL;
194 // Exclude any joins that are better represented by pseudoconstants
195 if (is_a($reference, 'CRM_Core_Reference_OptionValue')
196 ||
!$keyField ||
!empty($keyField['options'])
197 // Limit bridge joins to just the first
198 ||
$bridge && array_search($keyField['name'], $entity['bridge']) !== 0
199 // Sanity check - table should match
200 ||
$daoClass::getTableName() !== $reference->getReferenceTable()
204 // Dynamic references use a column like "entity_table" (for normal joins this value will be null)
205 $dynamicCol = $reference->getTypeColumn();
206 // For dynamic references getTargetEntities will return multiple targets; for normal joins this loop will only run once
207 foreach ($reference->getTargetEntities() as $targetTable => $targetEntityName) {
208 if (!isset($allowedEntities[$targetEntityName]) ||
$targetEntityName === $entity['name']) {
211 $targetEntity = $allowedEntities[$targetEntityName];
212 // Non-bridge joins directly between 2 entities
214 // Add the straight 1-1 join
215 $alias = $entity['name'] . '_' . $targetEntityName . '_' . $keyField['name'];
216 $joins[$entity['name']][] = [
217 'label' => $entity['title'] . ' ' . $targetEntity['title'],
218 'description' => $dynamicCol ?
'' : $keyField['label'],
219 'entity' => $targetEntityName,
220 'conditions' => self
::getJoinConditions($keyField['name'], $alias . '.' . $reference->getTargetKey(), $targetTable, $dynamicCol),
221 'defaults' => self
::getJoinDefaults($alias, $targetEntity),
225 // Flip the conditions & add the reverse (1-n) join
226 $alias = $targetEntityName . '_' . $entity['name'] . '_' . $keyField['name'];
227 $joins[$targetEntityName][] = [
228 'label' => $targetEntity['title'] . ' ' . $entity['title_plural'],
229 'description' => $dynamicCol ?
'' : $keyField['label'],
230 'entity' => $entity['name'],
231 'conditions' => self
::getJoinConditions($reference->getTargetKey(), $alias . '.' . $keyField['name'], $targetTable, $dynamicCol ?
$alias . '.' . $dynamicCol : NULL),
232 'defaults' => self
::getJoinDefaults($alias, $entity),
237 // Bridge joins (sanity check - bridge must specify exactly 2 FK fields)
238 elseif (count($entity['bridge']) === 2) {
239 // Get the other entity being linked through this bridge
240 $baseKey = array_search($reference->getReferenceKey(), $entity['bridge']) ?
$entity['bridge'][0] : $entity['bridge'][1];
241 $baseEntity = $allowedEntities[$fields[$baseKey]['fk_entity']] ??
NULL;
245 // Add joins for the two entities that connect through this bridge (n-n)
246 $symmetric = $baseEntity['name'] === $targetEntityName;
247 $targetsTitle = $symmetric ?
$allowedEntities[$bridge]['title_plural'] : $targetEntity['title_plural'];
248 $alias = $baseEntity['name'] . "_{$bridge}_" . $targetEntityName;
249 $joins[$baseEntity['name']][] = [
250 'label' => $baseEntity['title'] . ' ' . $targetsTitle,
251 'description' => E
::ts('Multiple %1 per %2', [1 => $targetsTitle, 2 => $baseEntity['title']]),
252 'entity' => $targetEntityName,
253 'conditions' => array_merge(
255 self
::getJoinConditions('id', $alias . '.' . $baseKey, NULL, NULL)
257 'defaults' => self
::getJoinDefaults($alias, $targetEntity, $entity),
263 $alias = $targetEntityName . "_{$bridge}_" . $baseEntity['name'];
264 $joins[$targetEntityName][] = [
265 'label' => $targetEntity['title'] . ' ' . $baseEntity['title_plural'],
266 'description' => E
::ts('Multiple %1 per %2', [1 => $baseEntity['title_plural'], 2 => $targetEntity['title']]),
267 'entity' => $baseEntity['name'],
268 'conditions' => array_merge(
270 self
::getJoinConditions($reference->getTargetKey(), $alias . '.' . $keyField['name'], $targetTable, $dynamicCol ?
$alias . '.' . $dynamicCol : NULL)
272 'defaults' => self
::getJoinDefaults($alias, $baseEntity, $entity),
287 * Boilerplate join clause
289 * @param string $nearCol
290 * @param string $farCol
291 * @param string $targetTable
292 * @param string|null $dynamicCol
295 private static function getJoinConditions($nearCol, $farCol, $targetTable = NULL, $dynamicCol = NULL) {
315 * @param array ...$entities
318 private static function getJoinDefaults($alias, ...$entities):array {
320 foreach ($entities as $entity) {
321 foreach ($entity['ui_join_filters'] ??
[] as $fieldName) {
322 $field = civicrm_api4($entity['name'], 'getFields', [
323 'select' => ['options'],
324 'where' => [['name', '=', $fieldName]],
325 'loadOptions' => ['name'],
327 $value = isset($field['options'][0]) ?
json_encode($field['options'][0]['name']) : '';
329 $alias . '.' . $fieldName . ($value ?
':name' : ''),