Fix token metadata to be clearable outside tests
[civicrm-core.git] / CRM / Core / EntityTokens.php
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;
14 use Civi\Token\Event\TokenRegisterEvent;
15 use Civi\Token\Event\TokenValueEvent;
16 use Civi\Token\TokenRow;
17 use Civi\ActionSchedule\Event\MailingQueryEvent;
18 use Civi\Token\TokenProcessor;
19 use Brick\Money\Money;
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
33 /**
34 * Metadata about all tokens.
35 *
36 * @var array
37 */
38 protected $tokensMetadata = [];
39 /**
40 * @var array
41 */
42 protected $prefetch = [];
43
44 /**
45 * Should permissions be checked when loading tokens.
46 *
47 * @var bool
48 */
49 protected $checkPermissions = FALSE;
50
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 }
61 foreach ($this->getTokenMetadata() as $tokenName => $field) {
62 if ($field['audience'] === 'user') {
63 $e->register([
64 'entity' => $this->entity,
65 'field' => $tokenName,
66 'label' => $field['title'],
67 ]);
68 }
69 }
70 }
71
72 /**
73 * Get the metadata about the available tokens
74 *
75 * @return array
76 */
77 protected function getTokenMetadata(): array {
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());
83 }
84 foreach ($this->getHiddenTokens() as $name) {
85 $tokensMetadata[$name]['audience'] = 'hidden';
86 }
87 Civi::cache('metadata')->set($cacheKey, $tokensMetadata);
88 }
89 return Civi::cache('metadata')->get($cacheKey);
90 }
91
92 /**
93 * @inheritDoc
94 * @throws \CRM_Core_Exception
95 */
96 public function evaluateToken(TokenRow $row, $entity, $field, $prefetch = NULL) {
97 $this->prefetch = (array) $prefetch;
98 $fieldValue = $this->getFieldValue($row, $field);
99 if (is_array($fieldValue)) {
100 // eg. role_id for participant would be an array here.
101 $fieldValue = implode(',', $fieldValue);
102 }
103
104 if ($this->isPseudoField($field)) {
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.
111 $split = explode(':', $field);
112 return $row->tokens($entity, $field, $this->getPseudoValue($split[0], $split[1], $this->getFieldValue($row, $split[0])));
113 }
114 if ($this->isCustomField($field)) {
115 $prefetchedValue = $this->getCustomFieldValue($this->getFieldValue($row, 'id'), $field);
116 if ($prefetchedValue) {
117 return $row->format('text/html')->tokens($entity, $field, $prefetchedValue);
118 }
119 return $row->customToken($entity, \CRM_Core_BAO_CustomField::getKeyID($field), $this->getFieldValue($row, 'id'));
120 }
121 if ($this->isMoneyField($field)) {
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 }
128 return $row->format('text/plain')->tokens($entity, $field,
129 Money::of($fieldValue, $currency));
130
131 }
132 if ($this->isDateField($field)) {
133 try {
134 return $row->format('text/plain')
135 ->tokens($entity, $field, ($fieldValue ? new DateTime($fieldValue) : $fieldValue));
136 }
137 catch (Exception $e) {
138 Civi::log()->info('invalid date token');
139 }
140 }
141 $row->format('text/plain')->tokens($entity, $field, (string) $fieldValue);
142 }
143
144 /**
145 * Metadata about the entity fields.
146 *
147 * @var array
148 */
149 protected $fieldMetadata = [];
150
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
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
183 /**
184 * Get an array of fields to be requested.
185 *
186 * @todo this function should look up tokenMetadata that
187 * is already loaded.
188 *
189 * @return string[]
190 */
191 protected function getReturnFields(): array {
192 return array_keys($this->getBasicTokens());
193 }
194
195 /**
196 * Is the given field a boolean field.
197 *
198 * @param string $fieldName
199 *
200 * @return bool
201 */
202 protected function isBooleanField(string $fieldName): bool {
203 return $this->getMetadataForField($fieldName)['data_type'] === 'Boolean';
204 }
205
206 /**
207 * Is the given field a date field.
208 *
209 * @param string $fieldName
210 *
211 * @return bool
212 */
213 protected function isDateField(string $fieldName): bool {
214 return in_array($this->getMetadataForField($fieldName)['data_type'], ['Timestamp', 'Date'], TRUE);
215 }
216
217 /**
218 * Is the given field a pseudo field.
219 *
220 * @param string $fieldName
221 *
222 * @return bool
223 */
224 protected function isPseudoField(string $fieldName): bool {
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 */
235 protected function isCustomField(string $fieldName) : bool {
236 return (bool) \CRM_Core_BAO_CustomField::getKeyID($fieldName);
237 }
238
239 /**
240 * Is the given field a date field.
241 *
242 * @param string $fieldName
243 *
244 * @return bool
245 */
246 protected function isMoneyField(string $fieldName): bool {
247 return $this->getMetadataForField($fieldName)['data_type'] === 'Money';
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)) {
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 = [];
263 }
264 }
265 return $this->fieldMetadata;
266 }
267
268 /**
269 * Get any tokens with custom calculation.
270 */
271 protected function getBespokeTokens(): array {
272 return [];
273 }
274
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 */
287 protected function getPseudoValue(string $realField, string $pseudoKey, $fieldValue): string {
288 $bao = CRM_Core_DAO_AllCoreTables::getFullName($this->getMetadataForField($realField)['entity']);
289 if ($pseudoKey === 'name') {
290 $fieldValue = (string) CRM_Core_PseudoConstant::getName($bao, $realField, $fieldValue);
291 }
292 if ($pseudoKey === 'label') {
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);
298 }
299 return (string) $fieldValue;
300 }
301
302 /**
303 * @param \Civi\Token\TokenRow $row
304 * @param string $field
305 * @return string|int
306 */
307 protected function getFieldValue(TokenRow $row, string $field) {
308 $entityName = $this->getEntityName();
309 if (isset($row->context[$entityName][$field])) {
310 return $row->context[$entityName][$field];
311 }
312
313 $entityID = $row->context[$this->getEntityIDField()];
314 if ($field === 'id') {
315 return $entityID;
316 }
317 return $this->prefetch[$entityID][$field] ?? '';
318 }
319
320 /**
321 * Class constructor.
322 */
323 public function __construct() {
324 parent::__construct($this->getEntityName(), []);
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) {
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']);
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 }
350 $e->query->select('e.id AS tokenContext_' . $this->getEntityIDField());
351 }
352
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
364 /**
365 * @todo remove this function & use the metadata that is loaded.
366 *
367 * @return string[]
368 * @throws \API_Exception
369 */
370 protected function getBasicTokens(): array {
371 $return = [];
372 foreach ($this->getExposedFields() as $fieldName) {
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 }
379 }
380 return $return;
381 }
382
383 /**
384 * Get entity fields that should be exposed as tokens.
385 *
386 * @return string[]
387 *
388 */
389 protected function getExposedFields(): array {
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 */
404 protected function getSkippedFields(): array {
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.
408 $fields = ['tags'];
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
422 protected function getEntityIDField(): string {
423 return $this->getEntityName() . 'Id';
424 }
425
426 public function prefetch(TokenValueEvent $e): ?array {
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
442 protected function getCurrencyFieldName() {
443 return [];
444 }
445
446 /**
447 * Get the currency to use for formatting money.
448 * @param $row
449 *
450 * @return string
451 */
452 protected function getCurrency($row): string {
453 if (!empty($this->getCurrencyFieldName())) {
454 return $this->getFieldValue($row, $this->getCurrencyFieldName()[0]);
455 }
456 return CRM_Core_Config::singleton()->defaultCurrency;
457 }
458
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 */
467 public function getPrefetchFields(TokenValueEvent $e): array {
468 $allTokens = array_keys($this->getTokenMetadata());
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 */
489 protected function getDependencies(): array {
490 return [];
491 }
492
493 /**
494 * Get the apiv4 style custom field name.
495 *
496 * @param int $id
497 *
498 * @return string
499 */
500 protected function getCustomFieldName(int $id): string {
501 foreach ($this->getTokenMetadata() as $key => $field) {
502 if (($field['custom_field_id'] ?? NULL) === $id) {
503 return $key;
504 }
505 }
506 }
507
508 /**
509 * @param $entityID
510 * @param string $field eg. 'custom_1'
511 *
512 * @return array|string|void|null $mixed
513 *
514 * @throws \CRM_Core_Exception
515 */
516 protected function getCustomFieldValue($entityID, string $field) {
517 $id = str_replace('custom_', '', $field);
518 $value = $this->prefetch[$entityID][$this->getCustomFieldName($id)] ?? '';
519 if ($value !== NULL) {
520 return CRM_Core_BAO_CustomField::displayValue($value, $id);
521 }
522 }
523
524 /**
525 * Get the metadata for the field.
526 *
527 * @param string $fieldName
528 *
529 * @return array
530 */
531 protected function getMetadataForField($fieldName): array {
532 if (isset($this->getTokenMetadata()[$fieldName])) {
533 return $this->getTokenMetadata()[$fieldName];
534 }
535 if (isset($this->getTokenMappingsForRelatedEntities()[$fieldName])) {
536 return $this->getTokenMetadata()[$this->getTokenMappingsForRelatedEntities()[$fieldName]];
537 }
538 return $this->getTokenMetadata()[$this->getDeprecatedTokens()[$fieldName]] ?? [];
539 }
540
541 /**
542 * Get token mappings for related entities - specifically the contact entity.
543 *
544 * This function exists to help manage the way contact tokens is structured
545 * of an query-object style result set that needs to be mapped to apiv4.
546 *
547 * The end goal is likely to be to advertised tokens that better map to api
548 * v4 and deprecate the existing ones but that is a long-term migration.
549 *
550 * @return array
551 */
552 protected function getTokenMappingsForRelatedEntities(): array {
553 return [];
554 }
555
556 /**
557 * Get array of deprecated tokens and the new token they map to.
558 *
559 * @return array
560 */
561 protected function getDeprecatedTokens(): array {
562 return [];
563 }
564
565 /**
566 * Get any overrides for token metadata.
567 *
568 * This is most obviously used for setting the audience, which
569 * will affect widget-presence.
570 *
571 * @return \string[][]
572 */
573 protected function getTokenMetadataOverrides(): array {
574 return [];
575 }
576
577 /**
578 * To handle variable tokens, override this function and return the active tokens.
579 *
580 * @param \Civi\Token\Event\TokenValueEvent $e
581 *
582 * @return mixed
583 */
584 public function getActiveTokens(TokenValueEvent $e) {
585 $messageTokens = $e->getTokenProcessor()->getMessageTokens();
586 if (!isset($messageTokens[$this->entity])) {
587 return FALSE;
588 }
589 return array_intersect($messageTokens[$this->entity], array_keys($this->getTokenMetadata()));
590 }
591
592 /**
593 * Add the token to the metadata based on the field spec.
594 *
595 * @param array $tokensMetadata
596 * @param array $field
597 * @param array $exposedFields
598 * @param string $prefix
599 */
600 protected function addFieldToTokenMetadata(array &$tokensMetadata, array $field, array $exposedFields, string $prefix = ''): void {
601 if ($field['type'] !== 'Custom' && !in_array($field['name'], $exposedFields, TRUE)) {
602 return;
603 }
604 $field['audience'] = 'user';
605 if ($field['name'] === 'contact_id') {
606 // Since {contact.id} is almost always present don't confuse users
607 // by also adding (e.g {participant.contact_id)
608 $field['audience'] = 'sysadmin';
609 }
610 if (!empty($this->getTokenMetadataOverrides()[$field['name']])) {
611 $field = array_merge($field, $this->getTokenMetadataOverrides()[$field['name']]);
612 }
613 if ($field['type'] === 'Custom') {
614 // Convert to apiv3 style for now. Later we can add v4 with
615 // portable naming & support for labels/ dates etc so let's leave
616 // the space open for that.
617 // Not the existing quickform widget has handling for the custom field
618 // format based on the title using this syntax.
619 $parts = explode(': ', $field['label']);
620 $field['title'] = "{$parts[1]} :: {$parts[0]}";
621 $tokenName = 'custom_' . $field['custom_field_id'];
622 $tokensMetadata[$tokenName] = $field;
623 return;
624 }
625 $tokenName = $prefix ? ($prefix . '.' . $field['name']) : $field['name'];
626 if (in_array($field['name'], $exposedFields, TRUE)) {
627 if (
628 ($field['options'] || !empty($field['suffixes']))
629 // At the time of writing currency didn't have a label option - this may have changed.
630 && !in_array($field['name'], $this->getCurrencyFieldName(), TRUE)
631 ) {
632 $tokensMetadata[$tokenName . ':label'] = $tokensMetadata[$tokenName . ':name'] = $field;
633 $fieldLabel = $field['input_attrs']['label'] ?? $field['label'];
634 $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
635 $tokensMetadata[$tokenName . ':name']['name'] = $field['name'] . ':name';
636 $tokensMetadata[$tokenName . ':name']['audience'] = 'sysadmin';
637 $tokensMetadata[$tokenName . ':label']['title'] = $fieldLabel;
638 $tokensMetadata[$tokenName . ':name']['title'] = ts('Machine name') . ': ' . $fieldLabel;
639 $field['audience'] = 'sysadmin';
640 }
641 if ($field['data_type'] === 'Boolean') {
642 $tokensMetadata[$tokenName . ':label'] = $field;
643 $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
644 $field['audience'] = 'sysadmin';
645 }
646 $tokensMetadata[$tokenName] = $field;
647 }
648 }
649
650 /**
651 * Get a cache key appropriate to the current usage.
652 *
653 * @return string
654 */
655 protected function getCacheKey(): string {
656 $cacheKey = __CLASS__ . 'token_metadata' . $this->getApiEntityName() . CRM_Core_Config::domainID() . '_' . CRM_Core_I18n::getLocale();
657 if ($this->checkPermissions) {
658 $cacheKey .= '__' . CRM_Core_Session::getLoggedInContactID();
659 }
660 return $cacheKey;
661 }
662
663 }