[REF] Remove setting on unused variables
[civicrm-core.git] / ext / search / Civi / Search / Admin.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 namespace Civi\Search;
13
14 use CRM_Search_ExtensionUtil as E;
15
16 /**
17 * Class Admin
18 * @package Civi\Search
19 */
20 class Admin {
21
22 /**
23 * @return array
24 */
25 public static function getAdminSettings():array {
26 $schema = self::getSchema();
27 $extensions = \CRM_Extension_System::singleton()->getMapper();
28 return [
29 'schema' => $schema,
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'),
37 ];
38 }
39
40 /**
41 * @return string[]
42 */
43 public static function getOperators():array {
44 return [
45 '=' => '=',
46 '!=' => '≠',
47 '>' => '>',
48 '<' => '<',
49 '>=' => '≥',
50 '<=' => '≤',
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'),
60 ];
61 }
62
63 /**
64 * @return string[]
65 */
66 public static function getStyles():array {
67 return [
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'),
74 ];
75 }
76
77 /**
78 * Fetch all entities the current user has permission to `get`
79 * @return array
80 */
81 public static function getSchema() {
82 $schema = [];
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')
87 ->setChain([
88 'get' => ['$name', 'getActions', ['where' => [['name', '=', 'get']]], ['params']],
89 ])->execute();
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
93 if ($entity['get']) {
94 // Add paths (but only RUD actions) with translated titles
95 foreach ($entity['paths'] as $action => $path) {
96 unset($entity['paths'][$action]);
97 switch ($action) {
98 case 'view':
99 $title = E::ts('View %1', [1 => $entity['title']]);
100 break;
101
102 case 'update':
103 $title = E::ts('Edit %1', [1 => $entity['title']]);
104 break;
105
106 case 'delete':
107 $title = E::ts('Delete %1', [1 => $entity['title']]);
108 break;
109
110 default:
111 continue 2;
112 }
113 $entity['paths'][] = [
114 'path' => $path,
115 'title' => $title,
116 'action' => $action,
117 ];
118 }
119 $entity['fields'] = (array) civicrm_api4($entity['name'], 'getFields', [
120 'select' => $getFields,
121 'where' => [['name', 'NOT IN', ['api_key', 'hash']]],
122 'orderBy' => ['label'],
123 ]);
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);
130 }
131 }
132 }
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]);
145 }
146 }
147 }
148 return array_values($schema);
149 }
150
151 /**
152 * @param array $allowedEntities
153 * @return array
154 */
155 public static function getJoins(array $allowedEntities) {
156 $joins = [];
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'],
165 'description' => '',
166 'entity' => 'Contact',
167 'conditions' => self::getJoinConditions('entity_id', $alias . '.id'),
168 'defaults' => self::getJoinDefaults($alias, $targetEntity),
169 'alias' => $alias,
170 'multi' => FALSE,
171 ];
172 // Join from Contact to Custom group (n-n)
173 $alias = 'Contact_' . $entity['name'] . '_entity_id';
174 $joins['Contact'][] = [
175 'label' => $entity['title_plural'],
176 'description' => '',
177 'entity' => $entity['name'],
178 'conditions' => self::getJoinConditions('id', $alias . '.entity_id'),
179 'defaults' => self::getJoinDefaults($alias, $entity),
180 'alias' => $alias,
181 'multi' => TRUE,
182 ];
183 }
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;
192 });
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()
204 ) {
205 continue;
206 }
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']) {
212 continue;
213 }
214 $targetEntity = $allowedEntities[$targetEntityName];
215 // Non-bridge joins directly between 2 entities
216 if (!$bridge) {
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),
225 'alias' => $alias,
226 'multi' => FALSE,
227 ];
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),
236 'alias' => $alias,
237 'multi' => TRUE,
238 ];
239 }
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;
245 if (!$baseEntity) {
246 continue;
247 }
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(
257 [$bridge],
258 self::getJoinConditions('id', $alias . '.' . $baseKey, NULL, NULL)
259 ),
260 'defaults' => self::getJoinDefaults($alias, $targetEntity, $entity),
261 'bridge' => $bridge,
262 'alias' => $alias,
263 'multi' => TRUE,
264 ];
265 if (!$symmetric) {
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(
272 [$bridge],
273 self::getJoinConditions($reference->getTargetKey(), $alias . '.' . $keyField['name'], $targetTable, $dynamicCol ? $alias . '.' . $dynamicCol : NULL)
274 ),
275 'defaults' => self::getJoinDefaults($alias, $baseEntity, $entity),
276 'bridge' => $bridge,
277 'alias' => $alias,
278 'multi' => TRUE,
279 ];
280 }
281 }
282 }
283 }
284 }
285 }
286 return $joins;
287 }
288
289 /**
290 * Boilerplate join clause
291 *
292 * @param string $nearCol
293 * @param string $farCol
294 * @param string $targetTable
295 * @param string|null $dynamicCol
296 * @return array[]
297 */
298 private static function getJoinConditions($nearCol, $farCol, $targetTable = NULL, $dynamicCol = NULL) {
299 $conditions = [
300 [
301 $nearCol,
302 '=',
303 $farCol,
304 ],
305 ];
306 if ($dynamicCol) {
307 $conditions[] = [
308 $dynamicCol,
309 '=',
310 "'$targetTable'",
311 ];
312 }
313 return $conditions;
314 }
315
316 /**
317 * @param $alias
318 * @param array ...$entities
319 * @return array
320 */
321 private static function getJoinDefaults($alias, ...$entities):array {
322 $conditions = [];
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'],
329 ])->first();
330 $value = isset($field['options'][0]) ? json_encode($field['options'][0]['name']) : '';
331 $conditions[] = [
332 $alias . '.' . $fieldName . ($value ? ':name' : ''),
333 '=',
334 $value,
335 ];
336 }
337 }
338 return $conditions;
339 }
340
341 }