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