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