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 $getFields = ['name', 'title', 'label', 'description', 'options', 'input_type', 'input_attrs', 'data_type', 'serialize', 'entity', 'fk_entity'];
91 foreach ($entities as $entity) {
92 // Skip if entity doesn't have a 'get' action or the user doesn't have permission to use get
94 // Add paths (but only RUD actions) with translated titles
95 foreach ($entity['paths'] as $action => $path) {
96 unset($entity['paths'][$action]);
99 $title = E
::ts('View %1', [1 => $entity['title']]);
103 $title = E
::ts('Edit %1', [1 => $entity['title']]);
107 $title = E
::ts('Delete %1', [1 => $entity['title']]);
113 $entity['paths'][] = [
119 $entity['fields'] = (array) civicrm_api4($entity['name'], 'getFields', [
120 'select' => $getFields,
121 'where' => [['name', 'NOT IN', ['api_key', 'hash']]],
122 'orderBy' => ['label'],
124 $params = $entity['get'][0];
125 // Entity must support at least these params or it is too weird for search kit
126 if (!array_diff(['select', 'where', 'orderBy', 'limit', 'offset'], array_keys($params))) {
127 \CRM_Utils_Array
::remove($params, 'checkPermissions', 'debug', 'chain', 'language', 'select', 'where', 'orderBy', 'limit', 'offset');
128 unset($entity['get']);
129 $schema[$entity['name']] = ['params' => array_keys($params)] +
array_filter($entity);
133 // Add in FK fields for implicit joins
134 // For example, add a `campaign.title` field to the Contribution entity
135 foreach ($schema as &$entity) {
136 foreach (array_reverse($entity['fields'], TRUE) as $index => $field) {
137 if (!empty($field['fk_entity']) && !$field['options'] && !empty($schema[$field['fk_entity']]['label_field'])) {
138 // The original field will get title instead of label since it represents the id (title usually ends in ID but label does not)
139 $entity['fields'][$index]['label'] = $field['title'];
140 // Add the label field from the other entity to this entity's list of fields
141 $newField = \CRM_Utils_Array
::findAll($schema[$field['fk_entity']]['fields'], ['name' => $schema[$field['fk_entity']]['label_field']])[0];
142 $newField['name'] = str_replace('_id', '', $field['name']) . '.' . $schema[$field['fk_entity']]['label_field'];
143 $newField['label'] = $field['label'] . ' ' . $newField['label'];
144 array_splice($entity['fields'], $index, 0, [$newField]);
148 return array_values($schema);
152 * @param array $allowedEntities
155 public static function getJoins(array $allowedEntities) {
157 foreach ($allowedEntities as $entity) {
158 // Multi-record custom field groups (to-date only the contact entity supports these)
159 if (in_array('CustomValue', $entity['type'])) {
160 $targetEntity = $allowedEntities['Contact'];
161 // Join from Custom group to Contact (n-1)
162 $alias = $entity['name'] . '_Contact_entity_id';
163 $joins[$entity['name']][] = [
164 'label' => $entity['title'] . ' ' . $targetEntity['title'],
166 'entity' => 'Contact',
167 'conditions' => self
::getJoinConditions('entity_id', $alias . '.id'),
168 'defaults' => self
::getJoinDefaults($alias, $targetEntity),
172 // Join from Contact to Custom group (n-n)
173 $alias = 'Contact_' . $entity['name'] . '_entity_id';
174 $joins['Contact'][] = [
175 'label' => $entity['title_plural'],
177 'entity' => $entity['name'],
178 'conditions' => self
::getJoinConditions('id', $alias . '.entity_id'),
179 'defaults' => self
::getJoinDefaults($alias, $entity),
184 // Non-custom DAO entities
185 elseif (!empty($entity['dao'])) {
186 /* @var \CRM_Core_DAO $daoClass */
187 $daoClass = $entity['dao'];
188 $references = $daoClass::getReferenceColumns();
189 // Only the first bridge reference gets processed, so if it's dynamic we want to be sure it's first in the list
190 usort($references, function($reference) {
191 return is_a($reference, 'CRM_Core_Reference_Dynamic') ?
-1 : 1;
193 $fields = array_column($entity['fields'], NULL, 'name');
194 $bridge = in_array('EntityBridge', $entity['type']) ?
$entity['name'] : NULL;
195 foreach ($references as $reference) {
196 $keyField = $fields[$reference->getReferenceKey()] ??
NULL;
197 // Exclude any joins that are better represented by pseudoconstants
198 if (is_a($reference, 'CRM_Core_Reference_OptionValue')
199 ||
!$keyField ||
!empty($keyField['options'])
200 // Limit bridge joins to just the first
201 ||
$bridge && array_search($keyField['name'], $entity['bridge']) !== 0
202 // Sanity check - table should match
203 ||
$daoClass::getTableName() !== $reference->getReferenceTable()
207 // Dynamic references use a column like "entity_table" (for normal joins this value will be null)
208 $dynamicCol = $reference->getTypeColumn();
209 // For dynamic references getTargetEntities will return multiple targets; for normal joins this loop will only run once
210 foreach ($reference->getTargetEntities() as $targetTable => $targetEntityName) {
211 if (!isset($allowedEntities[$targetEntityName]) ||
$targetEntityName === $entity['name']) {
214 $targetEntity = $allowedEntities[$targetEntityName];
215 // Non-bridge joins directly between 2 entities
217 // Add the straight 1-1 join
218 $alias = $entity['name'] . '_' . $targetEntityName . '_' . $keyField['name'];
219 $joins[$entity['name']][] = [
220 'label' => $entity['title'] . ' ' . $targetEntity['title'],
221 'description' => $dynamicCol ?
'' : $keyField['label'],
222 'entity' => $targetEntityName,
223 'conditions' => self
::getJoinConditions($keyField['name'], $alias . '.' . $reference->getTargetKey(), $targetTable, $dynamicCol),
224 'defaults' => self
::getJoinDefaults($alias, $targetEntity),
228 // Flip the conditions & add the reverse (1-n) join
229 $alias = $targetEntityName . '_' . $entity['name'] . '_' . $keyField['name'];
230 $joins[$targetEntityName][] = [
231 'label' => $targetEntity['title'] . ' ' . $entity['title_plural'],
232 'description' => $dynamicCol ?
'' : $keyField['label'],
233 'entity' => $entity['name'],
234 'conditions' => self
::getJoinConditions($reference->getTargetKey(), $alias . '.' . $keyField['name'], $targetTable, $dynamicCol ?
$alias . '.' . $dynamicCol : NULL),
235 'defaults' => self
::getJoinDefaults($alias, $entity),
240 // Bridge joins (sanity check - bridge must specify exactly 2 FK fields)
241 elseif (count($entity['bridge']) === 2) {
242 // Get the other entity being linked through this bridge
243 $baseKey = array_search($reference->getReferenceKey(), $entity['bridge']) ?
$entity['bridge'][0] : $entity['bridge'][1];
244 $baseEntity = $allowedEntities[$fields[$baseKey]['fk_entity']] ??
NULL;
248 // Add joins for the two entities that connect through this bridge (n-n)
249 $symmetric = $baseEntity['name'] === $targetEntityName;
250 $targetsTitle = $symmetric ?
$allowedEntities[$bridge]['title_plural'] : $targetEntity['title_plural'];
251 $alias = $baseEntity['name'] . "_{$bridge}_" . $targetEntityName;
252 $joins[$baseEntity['name']][] = [
253 'label' => $baseEntity['title'] . ' ' . $targetsTitle,
254 'description' => E
::ts('Multiple %1 per %2', [1 => $targetsTitle, 2 => $baseEntity['title']]),
255 'entity' => $targetEntityName,
256 'conditions' => array_merge(
258 self
::getJoinConditions('id', $alias . '.' . $baseKey, NULL, NULL)
260 'defaults' => self
::getJoinDefaults($alias, $targetEntity, $entity),
266 $alias = $targetEntityName . "_{$bridge}_" . $baseEntity['name'];
267 $joins[$targetEntityName][] = [
268 'label' => $targetEntity['title'] . ' ' . $baseEntity['title_plural'],
269 'description' => E
::ts('Multiple %1 per %2', [1 => $baseEntity['title_plural'], 2 => $targetEntity['title']]),
270 'entity' => $baseEntity['name'],
271 'conditions' => array_merge(
273 self
::getJoinConditions($reference->getTargetKey(), $alias . '.' . $keyField['name'], $targetTable, $dynamicCol ?
$alias . '.' . $dynamicCol : NULL)
275 'defaults' => self
::getJoinDefaults($alias, $baseEntity, $entity),
290 * Boilerplate join clause
292 * @param string $nearCol
293 * @param string $farCol
294 * @param string $targetTable
295 * @param string|null $dynamicCol
298 private static function getJoinConditions($nearCol, $farCol, $targetTable = NULL, $dynamicCol = NULL) {
318 * @param array ...$entities
321 private static function getJoinDefaults($alias, ...$entities):array {
323 foreach ($entities as $entity) {
324 foreach ($entity['ui_join_filters'] ??
[] as $fieldName) {
325 $field = civicrm_api4($entity['name'], 'getFields', [
326 'select' => ['options'],
327 'where' => [['name', '=', $fieldName]],
328 'loadOptions' => ['name'],
330 $value = isset($field['options'][0]) ?
json_encode($field['options'][0]['name']) : '';
332 $alias . '.' . $fieldName . ($value ?
':name' : ''),