Merge pull request #20199 from kartik1000/altering_recaptcha_form
[civicrm-core.git] / ext / search_kit / 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 foreach ($entities as $entity) {
91 // Skip if entity doesn't have a 'get' action or the user doesn't have permission to use get
92 if ($entity['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'][] = [
98 'path' => $path,
99 'action' => $action,
100 ];
101 }
102 }
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'],
107 ]);
108 foreach ($getFields as $field) {
109 $field['fieldName'] = $field['name'];
110 $entity['fields'][] = $field;
111 }
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);
118 }
119 }
120 }
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($field['serialize']) && !empty($schema[$field['fk_entity']]['label_field'])) {
127 $isCustom = strpos($field['name'], '.');
128 // Custom fields: append "Contact ID" to original field label
129 if ($isCustom) {
130 $entity['fields'][$index]['label'] .= ' ' . E::ts('Contact ID');
131 }
132 // DAO fields: use title instead of label since it represents the id (title usually ends in ID but label does not)
133 else {
134 $entity['fields'][$index]['label'] = $field['title'];
135 }
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]);
141 }
142 }
143 }
144 }
145 return array_values($schema);
146 }
147
148 /**
149 * @param array $allowedEntities
150 * @return array
151 */
152 public static function getJoins(array $allowedEntities) {
153 $joins = [];
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'],
162 'description' => '',
163 'entity' => 'Contact',
164 'conditions' => self::getJoinConditions('entity_id', $alias . '.id'),
165 'defaults' => self::getJoinDefaults($alias, $targetEntity),
166 'alias' => $alias,
167 'multi' => FALSE,
168 ];
169 // Join from Contact to Custom group (n-n)
170 $alias = 'Contact_' . $entity['name'] . '_entity_id';
171 $joins['Contact'][] = [
172 'label' => $entity['title_plural'],
173 'description' => '',
174 'entity' => $entity['name'],
175 'conditions' => self::getJoinConditions('id', $alias . '.entity_id'),
176 'defaults' => self::getJoinDefaults($alias, $entity),
177 'alias' => $alias,
178 'multi' => TRUE,
179 ];
180 }
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;
189 });
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()
201 ) {
202 continue;
203 }
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']) {
209 continue;
210 }
211 $targetEntity = $allowedEntities[$targetEntityName];
212 // Non-bridge joins directly between 2 entities
213 if (!$bridge) {
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),
222 'alias' => $alias,
223 'multi' => FALSE,
224 ];
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),
233 'alias' => $alias,
234 'multi' => TRUE,
235 ];
236 }
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;
242 if (!$baseEntity) {
243 continue;
244 }
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(
254 [$bridge],
255 self::getJoinConditions('id', $alias . '.' . $baseKey, NULL, NULL)
256 ),
257 'defaults' => self::getJoinDefaults($alias, $targetEntity, $entity),
258 'bridge' => $bridge,
259 'alias' => $alias,
260 'multi' => TRUE,
261 ];
262 if (!$symmetric) {
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(
269 [$bridge],
270 self::getJoinConditions($reference->getTargetKey(), $alias . '.' . $keyField['name'], $targetTable, $dynamicCol ? $alias . '.' . $dynamicCol : NULL)
271 ),
272 'defaults' => self::getJoinDefaults($alias, $baseEntity, $entity),
273 'bridge' => $bridge,
274 'alias' => $alias,
275 'multi' => TRUE,
276 ];
277 }
278 }
279 }
280 }
281 }
282 }
283 return $joins;
284 }
285
286 /**
287 * Boilerplate join clause
288 *
289 * @param string $nearCol
290 * @param string $farCol
291 * @param string $targetTable
292 * @param string|null $dynamicCol
293 * @return array[]
294 */
295 private static function getJoinConditions($nearCol, $farCol, $targetTable = NULL, $dynamicCol = NULL) {
296 $conditions = [
297 [
298 $nearCol,
299 '=',
300 $farCol,
301 ],
302 ];
303 if ($dynamicCol) {
304 $conditions[] = [
305 $dynamicCol,
306 '=',
307 "'$targetTable'",
308 ];
309 }
310 return $conditions;
311 }
312
313 /**
314 * @param $alias
315 * @param array ...$entities
316 * @return array
317 */
318 private static function getJoinDefaults($alias, ...$entities):array {
319 $conditions = [];
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'],
326 ])->first();
327 $value = isset($field['options'][0]) ? json_encode($field['options'][0]['name']) : '';
328 $conditions[] = [
329 $alias . '.' . $fieldName . ($value ? ':name' : ''),
330 '=',
331 $value,
332 ];
333 }
334 }
335 return $conditions;
336 }
337
338 }