Merge pull request #22537 from jensschuppe/fix/typeErrorCustomFieldTokens
[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 * @throws \CRM_Core_Exception
501 */
502 protected function getCustomFieldName(int $id): string {
503 foreach ($this->getTokenMetadata() as $key => $field) {
504 if (($field['custom_field_id'] ?? NULL) === $id) {
505 return $key;
506 }
507 }
508 throw new CRM_Core_Exception(
509 "A custom field with the ID {$id} does not exist"
510 );
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);
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;
531 }
532 }
533
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 }
545 if (isset($this->getTokenMappingsForRelatedEntities()[$fieldName])) {
546 return $this->getTokenMetadata()[$this->getTokenMappingsForRelatedEntities()[$fieldName]];
547 }
548 return $this->getTokenMetadata()[$this->getDeprecatedTokens()[$fieldName]] ?? [];
549 }
550
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
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
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
602 /**
603 * Add the token to the metadata based on the field spec.
604 *
605 * @param array $tokensMetadata
606 * @param array $field
607 * @param array $exposedFields
608 * @param string $prefix
609 */
610 protected function addFieldToTokenMetadata(array &$tokensMetadata, array $field, array $exposedFields, string $prefix = ''): void {
611 if ($field['type'] !== 'Custom' && !in_array($field['name'], $exposedFields, TRUE)) {
612 return;
613 }
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'];
632 $tokensMetadata[$tokenName] = $field;
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 ) {
642 $tokensMetadata[$tokenName . ':label'] = $tokensMetadata[$tokenName . ':name'] = $field;
643 $fieldLabel = $field['input_attrs']['label'] ?? $field['label'];
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;
649 $field['audience'] = 'sysadmin';
650 }
651 if ($field['data_type'] === 'Boolean') {
652 $tokensMetadata[$tokenName . ':label'] = $field;
653 $tokensMetadata[$tokenName . ':label']['name'] = $field['name'] . ':label';
654 $field['audience'] = 'sysadmin';
655 }
656 $tokensMetadata[$tokenName] = $field;
657 }
658 }
659
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
673 }