Commit | Line | Data |
---|---|---|
17b6f179 EM |
1 | <?php |
2 | ||
3 | /* | |
4 | +--------------------------------------------------------------------+ | |
5 | | Copyright CiviCRM LLC. All rights reserved. | | |
6 | | | | |
7 | | This work is published under the GNU AGPLv3 license with some | | |
8 | | permitted exceptions and without any warranty. For full license | | |
9 | | and copyright information, see https://civicrm.org/licensing | | |
10 | +--------------------------------------------------------------------+ | |
11 | */ | |
12 | ||
13 | use Civi\Token\AbstractTokenSubscriber; | |
e80f2261 | 14 | use Civi\Token\Event\TokenRegisterEvent; |
69863342 | 15 | use Civi\Token\Event\TokenValueEvent; |
17b6f179 | 16 | use Civi\Token\TokenRow; |
45e8391a EM |
17 | use Civi\ActionSchedule\Event\MailingQueryEvent; |
18 | use Civi\Token\TokenProcessor; | |
f70a513f | 19 | use Brick\Money\Money; |
17b6f179 EM |
20 | |
21 | /** | |
22 | * Class CRM_Core_EntityTokens | |
23 | * | |
24 | * Parent class for generic entity token functionality. | |
25 | * | |
26 | * WARNING - this class is highly likely to be temporary and | |
27 | * to be consolidated with the TokenTrait and / or the | |
28 | * AbstractTokenSubscriber in future. It is being used to clarify | |
29 | * functionality but should NOT be used from outside of core tested code. | |
30 | */ | |
31 | class CRM_Core_EntityTokens extends AbstractTokenSubscriber { | |
32 | ||
889b0617 EM |
33 | /** |
34 | * Metadata about all tokens. | |
35 | * | |
36 | * @var array | |
37 | */ | |
38 | protected $tokensMetadata = []; | |
eba15732 EM |
39 | /** |
40 | * @var array | |
41 | */ | |
42 | protected $prefetch = []; | |
43 | ||
889b0617 EM |
44 | /** |
45 | * Should permissions be checked when loading tokens. | |
46 | * | |
47 | * @var bool | |
48 | */ | |
49 | protected $checkPermissions = FALSE; | |
50 | ||
e80f2261 EM |
51 | /** |
52 | * Register the declared tokens. | |
53 | * | |
54 | * @param \Civi\Token\Event\TokenRegisterEvent $e | |
55 | * The registration event. Add new tokens using register(). | |
56 | */ | |
57 | public function registerTokens(TokenRegisterEvent $e) { | |
58 | if (!$this->checkActive($e->getTokenProcessor())) { | |
59 | return; | |
60 | } | |
cc17ec91 | 61 | foreach ($this->getTokenMetadata() as $tokenName => $field) { |
889b0617 | 62 | if ($field['audience'] === 'user') { |
e80f2261 EM |
63 | $e->register([ |
64 | 'entity' => $this->entity, | |
cc17ec91 | 65 | 'field' => $tokenName, |
889b0617 | 66 | 'label' => $field['title'], |
e80f2261 EM |
67 | ]); |
68 | } | |
69 | } | |
70 | } | |
71 | ||
889b0617 EM |
72 | /** |
73 | * Get the metadata about the available tokens | |
74 | * | |
75 | * @return array | |
76 | */ | |
77 | protected function getTokenMetadata(): array { | |
32b856d7 EM |
78 | $cacheKey = $this->getCacheKey(); |
79 | if (!Civi::cache('metadata')->has($cacheKey)) { | |
80 | $tokensMetadata = $this->getBespokeTokens(); | |
81 | foreach ($this->getFieldMetadata() as $field) { | |
82 | $this->addFieldToTokenMetadata($tokensMetadata, $field, $this->getExposedFields()); | |
889b0617 | 83 | } |
32b856d7 EM |
84 | foreach ($this->getHiddenTokens() as $name) { |
85 | $tokensMetadata[$name]['audience'] = 'hidden'; | |
889b0617 | 86 | } |
32b856d7 | 87 | Civi::cache('metadata')->set($cacheKey, $tokensMetadata); |
889b0617 | 88 | } |
32b856d7 | 89 | return Civi::cache('metadata')->get($cacheKey); |
889b0617 EM |
90 | } |
91 | ||
17b6f179 | 92 | /** |
17b6f179 | 93 | * @inheritDoc |
45e8391a | 94 | * @throws \CRM_Core_Exception |
17b6f179 EM |
95 | */ |
96 | public function evaluateToken(TokenRow $row, $entity, $field, $prefetch = NULL) { | |
eba15732 | 97 | $this->prefetch = (array) $prefetch; |
45e8391a | 98 | $fieldValue = $this->getFieldValue($row, $field); |
b7472bd6 EM |
99 | if (is_array($fieldValue)) { |
100 | // eg. role_id for participant would be an array here. | |
101 | $fieldValue = implode(',', $fieldValue); | |
102 | } | |
45e8391a EM |
103 | |
104 | if ($this->isPseudoField($field)) { | |
0f4031da EM |
105 | if (!empty($fieldValue)) { |
106 | // If it's set here it has already been loaded in pre-fetch. | |
107 | return $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue); | |
108 | } | |
109 | // Once prefetch is fully standardised we can remove this - as long | |
110 | // as tests pass we should be fine as tests cover this. | |
45e8391a EM |
111 | $split = explode(':', $field); |
112 | return $row->tokens($entity, $field, $this->getPseudoValue($split[0], $split[1], $this->getFieldValue($row, $split[0]))); | |
113 | } | |
0f4031da | 114 | if ($this->isCustomField($field)) { |
e80f2261 EM |
115 | $prefetchedValue = $this->getCustomFieldValue($this->getFieldValue($row, 'id'), $field); |
116 | if ($prefetchedValue) { | |
117 | return $row->format('text/html')->tokens($entity, $field, $prefetchedValue); | |
118 | } | |
0f4031da EM |
119 | return $row->customToken($entity, \CRM_Core_BAO_CustomField::getKeyID($field), $this->getFieldValue($row, 'id')); |
120 | } | |
45e8391a | 121 | if ($this->isMoneyField($field)) { |
f70a513f EM |
122 | $currency = $this->getCurrency($row); |
123 | if (!$currency) { | |
124 | // too hard basket for now - just do what we always did. | |
125 | return $row->format('text/plain')->tokens($entity, $field, | |
126 | \CRM_Utils_Money::format($fieldValue, $currency)); | |
127 | } | |
45e8391a | 128 | return $row->format('text/plain')->tokens($entity, $field, |
f70a513f EM |
129 | Money::of($fieldValue, $currency)); |
130 | ||
45e8391a EM |
131 | } |
132 | if ($this->isDateField($field)) { | |
34795e7a EM |
133 | try { |
134 | return $row->format('text/plain') | |
8d1eafc0 | 135 | ->tokens($entity, $field, ($fieldValue ? new DateTime($fieldValue) : $fieldValue)); |
34795e7a EM |
136 | } |
137 | catch (Exception $e) { | |
138 | Civi::log()->info('invalid date token'); | |
139 | } | |
45e8391a | 140 | } |
0f4031da | 141 | $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue); |
17b6f179 EM |
142 | } |
143 | ||
45e8391a EM |
144 | /** |
145 | * Metadata about the entity fields. | |
146 | * | |
147 | * @var array | |
148 | */ | |
149 | protected $fieldMetadata = []; | |
150 | ||
29f2b53e EM |
151 | /** |
152 | * Get the entity name for api v4 calls. | |
153 | * | |
154 | * @return string | |
155 | */ | |
156 | protected function getApiEntityName(): string { | |
157 | return ''; | |
158 | } | |
159 | ||
160 | /** | |
161 | * Get the entity alias to use within queries. | |
162 | * | |
163 | * The default has a double underscore which should prevent any | |
164 | * ambiguity with an existing table name. | |
165 | * | |
166 | * @return string | |
167 | */ | |
168 | protected function getEntityAlias(): string { | |
169 | return $this->getApiEntityName() . '__'; | |
170 | } | |
171 | ||
3fcf0983 EM |
172 | /** |
173 | * Get the name of the table this token class can extend. | |
174 | * | |
175 | * The default is based on the entity but some token classes, | |
176 | * specifically the event class, latch on to other tables - ie | |
177 | * the participant table. | |
178 | */ | |
179 | public function getExtendableTableName(): string { | |
180 | return CRM_Core_DAO_AllCoreTables::getTableForEntityName($this->getApiEntityName()); | |
181 | } | |
182 | ||
3fcf0983 EM |
183 | /** |
184 | * Get an array of fields to be requested. | |
185 | * | |
e6ebebad EM |
186 | * @todo this function should look up tokenMetadata that |
187 | * is already loaded. | |
188 | * | |
3fcf0983 EM |
189 | * @return string[] |
190 | */ | |
e6ebebad | 191 | protected function getReturnFields(): array { |
3fcf0983 EM |
192 | return array_keys($this->getBasicTokens()); |
193 | } | |
194 | ||
97ca72e4 EM |
195 | /** |
196 | * Is the given field a boolean field. | |
197 | * | |
198 | * @param string $fieldName | |
199 | * | |
200 | * @return bool | |
201 | */ | |
e6ebebad | 202 | protected function isBooleanField(string $fieldName): bool { |
cc17ec91 | 203 | return $this->getMetadataForField($fieldName)['data_type'] === 'Boolean'; |
4a526c1b EM |
204 | } |
205 | ||
17b6f179 EM |
206 | /** |
207 | * Is the given field a date field. | |
208 | * | |
209 | * @param string $fieldName | |
210 | * | |
211 | * @return bool | |
212 | */ | |
e6ebebad | 213 | protected function isDateField(string $fieldName): bool { |
cc17ec91 | 214 | return in_array($this->getMetadataForField($fieldName)['data_type'], ['Timestamp', 'Date'], TRUE); |
29f2b53e EM |
215 | } |
216 | ||
217 | /** | |
218 | * Is the given field a pseudo field. | |
219 | * | |
220 | * @param string $fieldName | |
221 | * | |
222 | * @return bool | |
223 | */ | |
e6ebebad | 224 | protected function isPseudoField(string $fieldName): bool { |
29f2b53e EM |
225 | return strpos($fieldName, ':') !== FALSE; |
226 | } | |
227 | ||
228 | /** | |
229 | * Is the given field a custom field. | |
230 | * | |
231 | * @param string $fieldName | |
232 | * | |
233 | * @return bool | |
234 | */ | |
e6ebebad | 235 | protected function isCustomField(string $fieldName) : bool { |
29f2b53e | 236 | return (bool) \CRM_Core_BAO_CustomField::getKeyID($fieldName); |
17b6f179 EM |
237 | } |
238 | ||
239 | /** | |
240 | * Is the given field a date field. | |
241 | * | |
242 | * @param string $fieldName | |
243 | * | |
244 | * @return bool | |
245 | */ | |
e6ebebad | 246 | protected function isMoneyField(string $fieldName): bool { |
cc17ec91 | 247 | return $this->getMetadataForField($fieldName)['data_type'] === 'Money'; |
17b6f179 EM |
248 | } |
249 | ||
250 | /** | |
251 | * Get the metadata for the available fields. | |
252 | * | |
253 | * @return array | |
254 | */ | |
255 | protected function getFieldMetadata(): array { | |
256 | if (empty($this->fieldMetadata)) { | |
29f2b53e EM |
257 | try { |
258 | // Tests fail without checkPermissions = FALSE | |
259 | $this->fieldMetadata = (array) civicrm_api4($this->getApiEntityName(), 'getfields', ['checkPermissions' => FALSE], 'name'); | |
260 | } | |
261 | catch (API_Exception $e) { | |
262 | $this->fieldMetadata = []; | |
17b6f179 EM |
263 | } |
264 | } | |
265 | return $this->fieldMetadata; | |
266 | } | |
267 | ||
e80f2261 EM |
268 | /** |
269 | * Get any tokens with custom calculation. | |
270 | */ | |
e9841a51 | 271 | protected function getBespokeTokens(): array { |
e80f2261 EM |
272 | return []; |
273 | } | |
274 | ||
29f2b53e EM |
275 | /** |
276 | * Get the value for the relevant pseudo field. | |
277 | * | |
278 | * @param string $realField e.g contribution_status_id | |
279 | * @param string $pseudoKey e.g name | |
280 | * @param int|string $fieldValue e.g 1 | |
281 | * | |
282 | * @return string | |
283 | * Eg. 'Completed' in the example above. | |
284 | * | |
285 | * @internal function will likely be protected soon. | |
286 | */ | |
7a39d045 | 287 | protected function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string { |
e6ebebad | 288 | $bao = CRM_Core_DAO_AllCoreTables::getFullName($this->getMetadataForField($realField)['entity']); |
29f2b53e | 289 | if ($pseudoKey === 'name') { |
e6ebebad | 290 | $fieldValue = (string) CRM_Core_PseudoConstant::getName($bao, $realField, $fieldValue); |
29f2b53e EM |
291 | } |
292 | if ($pseudoKey === 'label') { | |
e6ebebad EM |
293 | $fieldValue = (string) CRM_Core_PseudoConstant::getLabel($bao, $realField, $fieldValue); |
294 | } | |
295 | if ($pseudoKey === 'abbr' && $realField === 'state_province_id') { | |
296 | // hack alert - currently only supported for state. | |
297 | $fieldValue = (string) CRM_Core_PseudoConstant::stateProvinceAbbreviation($fieldValue); | |
29f2b53e EM |
298 | } |
299 | return (string) $fieldValue; | |
300 | } | |
301 | ||
9c9c61af EM |
302 | /** |
303 | * @param \Civi\Token\TokenRow $row | |
304 | * @param string $field | |
305 | * @return string|int | |
306 | */ | |
307 | protected function getFieldValue(TokenRow $row, string $field) { | |
595cc868 TO |
308 | $entityName = $this->getEntityName(); |
309 | if (isset($row->context[$entityName][$field])) { | |
310 | return $row->context[$entityName][$field]; | |
311 | } | |
312 | ||
eba15732 | 313 | $entityID = $row->context[$this->getEntityIDField()]; |
e80f2261 EM |
314 | if ($field === 'id') { |
315 | return $entityID; | |
316 | } | |
eba15732 | 317 | return $this->prefetch[$entityID][$field] ?? ''; |
9c9c61af EM |
318 | } |
319 | ||
45e8391a EM |
320 | /** |
321 | * Class constructor. | |
322 | */ | |
323 | public function __construct() { | |
889b0617 | 324 | parent::__construct($this->getEntityName(), []); |
45e8391a EM |
325 | } |
326 | ||
327 | /** | |
328 | * Check if the token processor is active. | |
329 | * | |
330 | * @param \Civi\Token\TokenProcessor $processor | |
331 | * | |
332 | * @return bool | |
333 | */ | |
334 | public function checkActive(TokenProcessor $processor) { | |
eba15732 EM |
335 | return (!empty($processor->context['actionMapping']) |
336 | // This makes the 'schema context compulsory - which feels accidental | |
337 | // since recent discu | |
338 | && $processor->context['actionMapping']->getEntity()) || in_array($this->getEntityIDField(), $processor->context['schema']); | |
45e8391a EM |
339 | } |
340 | ||
341 | /** | |
342 | * Alter action schedule query. | |
343 | * | |
344 | * @param \Civi\ActionSchedule\Event\MailingQueryEvent $e | |
345 | */ | |
346 | public function alterActionScheduleQuery(MailingQueryEvent $e): void { | |
347 | if ($e->mapping->getEntity() !== $this->getExtendableTableName()) { | |
348 | return; | |
349 | } | |
afd0de5d | 350 | $e->query->select('e.id AS tokenContext_' . $this->getEntityIDField()); |
45e8391a EM |
351 | } |
352 | ||
e80f2261 EM |
353 | /** |
354 | * Get tokens to be suppressed from the widget. | |
355 | * | |
356 | * Note this is expected to be an interim function. Now we are no | |
357 | * longer working around the parent function we can just define them once... | |
358 | * with metadata, in a future refactor. | |
359 | */ | |
360 | protected function getHiddenTokens(): array { | |
361 | return []; | |
362 | } | |
363 | ||
bd6b5299 | 364 | /** |
e6ebebad | 365 | * @todo remove this function & use the metadata that is loaded. |
bd6b5299 EM |
366 | * |
367 | * @return string[] | |
368 | * @throws \API_Exception | |
369 | */ | |
e6ebebad | 370 | protected function getBasicTokens(): array { |
bd6b5299 EM |
371 | $return = []; |
372 | foreach ($this->getExposedFields() as $fieldName) { | |
c2f1897e EM |
373 | // Custom fields are still added v3 style - we want to keep v4 naming 'unpoluted' |
374 | // for now to allow us to consider how to handle names vs labels vs values | |
375 | // and other raw vs not raw options. | |
376 | if ($this->getFieldMetadata()[$fieldName]['type'] !== 'Custom') { | |
377 | $return[$fieldName] = $this->getFieldMetadata()[$fieldName]['title']; | |
378 | } | |
bd6b5299 EM |
379 | } |
380 | return $return; | |
381 | } | |
382 | ||
383 | /** | |
384 | * Get entity fields that should be exposed as tokens. | |
385 | * | |
386 | * @return string[] | |
387 | * | |
388 | */ | |
e9841a51 | 389 | protected function getExposedFields(): array { |
bd6b5299 EM |
390 | $return = []; |
391 | foreach ($this->getFieldMetadata() as $field) { | |
392 | if (!in_array($field['name'], $this->getSkippedFields(), TRUE)) { | |
393 | $return[] = $field['name']; | |
394 | } | |
395 | } | |
396 | return $return; | |
397 | } | |
398 | ||
399 | /** | |
400 | * Get entity fields that should not be exposed as tokens. | |
401 | * | |
402 | * @return string[] | |
403 | */ | |
889b0617 | 404 | protected function getSkippedFields(): array { |
78ffc4d7 EM |
405 | // tags is offered in 'case' & is one of the only fields that is |
406 | // 'not a real field' offered up by case - seems like an oddity | |
407 | // we should skip at the top level for now. | |
889b0617 | 408 | $fields = ['tags']; |
bd6b5299 EM |
409 | if (!CRM_Campaign_BAO_Campaign::isCampaignEnable()) { |
410 | $fields[] = 'campaign_id'; | |
411 | } | |
412 | return $fields; | |
413 | } | |
414 | ||
415 | /** | |
416 | * @return string | |
417 | */ | |
418 | protected function getEntityName(): string { | |
419 | return CRM_Core_DAO_AllCoreTables::convertEntityNameToLower($this->getApiEntityName()); | |
420 | } | |
421 | ||
e6ebebad | 422 | protected function getEntityIDField(): string { |
eba15732 EM |
423 | return $this->getEntityName() . 'Id'; |
424 | } | |
425 | ||
69863342 | 426 | public function prefetch(TokenValueEvent $e): ?array { |
eba15732 EM |
427 | $entityIDs = $e->getTokenProcessor()->getContextValues($this->getEntityIDField()); |
428 | if (empty($entityIDs)) { | |
429 | return []; | |
430 | } | |
431 | $select = $this->getPrefetchFields($e); | |
432 | $result = (array) civicrm_api4($this->getApiEntityName(), 'get', [ | |
433 | 'checkPermissions' => FALSE, | |
434 | // Note custom fields are not yet added - I need to | |
435 | // re-do the unit tests to support custom fields first. | |
436 | 'select' => $select, | |
437 | 'where' => [['id', 'IN', $entityIDs]], | |
438 | ], 'id'); | |
439 | return $result; | |
440 | } | |
441 | ||
e6ebebad | 442 | protected function getCurrencyFieldName() { |
eba15732 EM |
443 | return []; |
444 | } | |
445 | ||
446 | /** | |
447 | * Get the currency to use for formatting money. | |
448 | * @param $row | |
449 | * | |
450 | * @return string | |
451 | */ | |
e6ebebad | 452 | protected function getCurrency($row): string { |
eba15732 EM |
453 | if (!empty($this->getCurrencyFieldName())) { |
454 | return $this->getFieldValue($row, $this->getCurrencyFieldName()[0]); | |
455 | } | |
456 | return CRM_Core_Config::singleton()->defaultCurrency; | |
457 | } | |
458 | ||
d568dbe0 EM |
459 | /** |
460 | * Get the fields required to prefetch the entity. | |
461 | * | |
462 | * @param \Civi\Token\Event\TokenValueEvent $e | |
463 | * | |
464 | * @return array | |
465 | * @throws \API_Exception | |
466 | */ | |
69863342 | 467 | public function getPrefetchFields(TokenValueEvent $e): array { |
889b0617 | 468 | $allTokens = array_keys($this->getTokenMetadata()); |
d568dbe0 EM |
469 | $requiredFields = array_intersect($this->getActiveTokens($e), $allTokens); |
470 | if (empty($requiredFields)) { | |
471 | return []; | |
472 | } | |
473 | $requiredFields = array_merge($requiredFields, array_intersect($allTokens, array_merge(['id'], $this->getCurrencyFieldName()))); | |
474 | foreach ($this->getDependencies() as $field => $required) { | |
475 | if (in_array($field, $this->getActiveTokens($e), TRUE)) { | |
476 | foreach ((array) $required as $key) { | |
477 | $requiredFields[] = $key; | |
478 | } | |
479 | } | |
480 | } | |
481 | return $requiredFields; | |
482 | } | |
483 | ||
484 | /** | |
485 | * Get fields which need to be returned to render another token. | |
486 | * | |
487 | * @return array | |
488 | */ | |
e6ebebad | 489 | protected function getDependencies(): array { |
d568dbe0 | 490 | return []; |
eba15732 EM |
491 | } |
492 | ||
e80f2261 EM |
493 | /** |
494 | * Get the apiv4 style custom field name. | |
495 | * | |
496 | * @param int $id | |
497 | * | |
498 | * @return string | |
df03b9a3 JS |
499 | * |
500 | * @throws \CRM_Core_Exception | |
e80f2261 EM |
501 | */ |
502 | protected function getCustomFieldName(int $id): string { | |
cc17ec91 | 503 | foreach ($this->getTokenMetadata() as $key => $field) { |
e80f2261 EM |
504 | if (($field['custom_field_id'] ?? NULL) === $id) { |
505 | return $key; | |
506 | } | |
507 | } | |
df03b9a3 JS |
508 | throw new CRM_Core_Exception( |
509 | "A custom field with the ID {$id} does not exist" | |
510 | ); | |
e80f2261 EM |
511 | } |
512 | ||
513 | /** | |
514 | * @param $entityID | |
515 | * @param string $field eg. 'custom_1' | |
516 | * | |
517 | * @return array|string|void|null $mixed | |
518 | * | |
519 | * @throws \CRM_Core_Exception | |
520 | */ | |
521 | protected function getCustomFieldValue($entityID, string $field) { | |
522 | $id = str_replace('custom_', '', $field); | |
df03b9a3 JS |
523 | try { |
524 | $value = $this->prefetch[$entityID][$this->getCustomFieldName($id)] ?? ''; | |
525 | if ($value !== NULL) { | |
526 | return CRM_Core_BAO_CustomField::displayValue($value, $id); | |
527 | } | |
528 | } | |
529 | catch (CRM_Core_Exception $exception) { | |
530 | return NULL; | |
e80f2261 EM |
531 | } |
532 | } | |
533 | ||
cc17ec91 EM |
534 | /** |
535 | * Get the metadata for the field. | |
536 | * | |
537 | * @param string $fieldName | |
538 | * | |
539 | * @return array | |
540 | */ | |
541 | protected function getMetadataForField($fieldName): array { | |
542 | if (isset($this->getTokenMetadata()[$fieldName])) { | |
543 | return $this->getTokenMetadata()[$fieldName]; | |
544 | } | |
12ea84cf EM |
545 | if (isset($this->getTokenMappingsForRelatedEntities()[$fieldName])) { |
546 | return $this->getTokenMetadata()[$this->getTokenMappingsForRelatedEntities()[$fieldName]]; | |
547 | } | |
4f5f985c | 548 | return $this->getTokenMetadata()[$this->getDeprecatedTokens()[$fieldName]] ?? []; |
cc17ec91 EM |
549 | } |
550 | ||
12ea84cf EM |
551 | /** |
552 | * Get token mappings for related entities - specifically the contact entity. | |
553 | * | |
554 | * This function exists to help manage the way contact tokens is structured | |
555 | * of an query-object style result set that needs to be mapped to apiv4. | |
556 | * | |
557 | * The end goal is likely to be to advertised tokens that better map to api | |
558 | * v4 and deprecate the existing ones but that is a long-term migration. | |
559 | * | |
560 | * @return array | |
561 | */ | |
562 | protected function getTokenMappingsForRelatedEntities(): array { | |
563 | return []; | |
564 | } | |
565 | ||
cc17ec91 EM |
566 | /** |
567 | * Get array of deprecated tokens and the new token they map to. | |
568 | * | |
569 | * @return array | |
570 | */ | |
571 | protected function getDeprecatedTokens(): array { | |
572 | return []; | |
573 | } | |
574 | ||
889b0617 EM |
575 | /** |
576 | * Get any overrides for token metadata. | |
577 | * | |
578 | * This is most obviously used for setting the audience, which | |
579 | * will affect widget-presence. | |
580 | * | |
581 | * @return \string[][] | |
582 | */ | |
583 | protected function getTokenMetadataOverrides(): array { | |
584 | return []; | |
585 | } | |
586 | ||
587 | /** | |
588 | * To handle variable tokens, override this function and return the active tokens. | |
589 | * | |
590 | * @param \Civi\Token\Event\TokenValueEvent $e | |
591 | * | |
592 | * @return mixed | |
593 | */ | |
594 | public function getActiveTokens(TokenValueEvent $e) { | |
595 | $messageTokens = $e->getTokenProcessor()->getMessageTokens(); | |
596 | if (!isset($messageTokens[$this->entity])) { | |
597 | return FALSE; | |
598 | } | |
599 | return array_intersect($messageTokens[$this->entity], array_keys($this->getTokenMetadata())); | |
600 | } | |
601 | ||
c75e1fbc EM |
602 | /** |
603 | * Add the token to the metadata based on the field spec. | |
604 | * | |
32b856d7 | 605 | * @param array $tokensMetadata |
c75e1fbc EM |
606 | * @param array $field |
607 | * @param array $exposedFields | |
608 | * @param string $prefix | |
609 | */ | |
32b856d7 | 610 | protected function addFieldToTokenMetadata(array &$tokensMetadata, array $field, array $exposedFields, string $prefix = ''): void { |
e6ebebad EM |
611 | if ($field['type'] !== 'Custom' && !in_array($field['name'], $exposedFields, TRUE)) { |
612 | return; | |
613 | } | |
c75e1fbc EM |
614 | $field['audience'] = 'user'; |
615 | if ($field['name'] === 'contact_id') { | |
616 | // Since {contact.id} is almost always present don't confuse users | |
617 | // by also adding (e.g {participant.contact_id) | |
618 | $field['audience'] = 'sysadmin'; | |
619 | } | |
620 | if (!empty($this->getTokenMetadataOverrides()[$field['name']])) { | |
621 | $field = array_merge($field, $this->getTokenMetadataOverrides()[$field['name']]); | |
622 | } | |
623 | if ($field['type'] === 'Custom') { | |
624 | // Convert to apiv3 style for now. Later we can add v4 with | |
625 | // portable naming & support for labels/ dates etc so let's leave | |
626 | // the space open for that. | |
627 | // Not the existing quickform widget has handling for the custom field | |
628 | // format based on the title using this syntax. | |
629 | $parts = explode(': ', $field['label']); | |
630 | $field['title'] = "{$parts[1]} :: {$parts[0]}"; | |
631 | $tokenName = 'custom_' . $field['custom_field_id']; | |
32b856d7 | 632 | $tokensMetadata[$tokenName] = $field; |
c75e1fbc EM |
633 | return; |
634 | } | |
635 | $tokenName = $prefix ? ($prefix . '.' . $field['name']) : $field['name']; | |
636 | if (in_array($field['name'], $exposedFields, TRUE)) { | |
637 | if ( | |
638 | ($field['options'] || !empty($field['suffixes'])) | |
639 | // At the time of writing currency didn't have a label option - this may have changed. | |
640 | && !in_array($field['name'], $this->getCurrencyFieldName(), TRUE) | |
641 | ) { | |
32b856d7 | 642 | $tokensMetadata[$tokenName . ':label'] = $tokensMetadata[$tokenName . ':name'] = $field; |
c75e1fbc | 643 | $fieldLabel = $field['input_attrs']['label'] ?? $field['label']; |
32b856d7 EM |
644 | $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label'; |
645 | $tokensMetadata[$tokenName . ':name']['name'] = $field['name'] . ':name'; | |
646 | $tokensMetadata[$tokenName . ':name']['audience'] = 'sysadmin'; | |
647 | $tokensMetadata[$tokenName . ':label']['title'] = $fieldLabel; | |
648 | $tokensMetadata[$tokenName . ':name']['title'] = ts('Machine name') . ': ' . $fieldLabel; | |
c75e1fbc EM |
649 | $field['audience'] = 'sysadmin'; |
650 | } | |
651 | if ($field['data_type'] === 'Boolean') { | |
32b856d7 EM |
652 | $tokensMetadata[$tokenName . ':label'] = $field; |
653 | $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label'; | |
c75e1fbc EM |
654 | $field['audience'] = 'sysadmin'; |
655 | } | |
32b856d7 | 656 | $tokensMetadata[$tokenName] = $field; |
c75e1fbc EM |
657 | } |
658 | } | |
659 | ||
35f5d891 EM |
660 | /** |
661 | * Get a cache key appropriate to the current usage. | |
662 | * | |
663 | * @return string | |
664 | */ | |
665 | protected function getCacheKey(): string { | |
666 | $cacheKey = __CLASS__ . 'token_metadata' . $this->getApiEntityName() . CRM_Core_Config::domainID() . '_' . CRM_Core_I18n::getLocale(); | |
667 | if ($this->checkPermissions) { | |
668 | $cacheKey .= '__' . CRM_Core_Session::getLoggedInContactID(); | |
669 | } | |
670 | return $cacheKey; | |
671 | } | |
672 | ||
17b6f179 | 673 | } |