4 +--------------------------------------------------------------------+
5 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
13 use Civi\Api4\Contact
;
14 use Civi\Token\Event\TokenRegisterEvent
;
15 use Civi\Token\Event\TokenValueEvent
;
16 use Civi\Token\TokenProcessor
;
17 use Civi\Token\TokenRow
;
20 * Class CRM_Contact_Tokens
22 * Generate "contact.*" tokens.
24 class CRM_Contact_Tokens
extends CRM_Core_EntityTokens
{
27 * Get the entity name for api v4 calls.
31 protected function getApiEntityName(): string {
38 public static function getSubscribedEvents(): array {
40 'civi.token.eval' => [
41 ['evaluateLegacyHookTokens', 500],
44 'civi.token.list' => 'registerTokens',
49 * Register the declared tokens.
51 * @param \Civi\Token\Event\TokenRegisterEvent $e
52 * The registration event. Add new tokens using register().
54 * @throws \CRM_Core_Exception
56 public function registerTokens(TokenRegisterEvent
$e): void
{
57 if (!$this->checkActive($e->getTokenProcessor())) {
60 $relatedTokens = array_flip($this->getTokenMappingsForRelatedEntities());
61 foreach ($this->getTokenMetadata() as $tokenName => $field) {
62 if ($field['audience'] === 'user') {
64 'entity' => $this->entity
,
65 // Preserve legacy token names. It generally feels like
66 // it would be good to switch to the more specific token names
67 // but other code paths are still in use which can't handle them.
68 'field' => $relatedTokens[$tokenName] ??
$tokenName,
69 'label' => $field['title'],
73 foreach ($this->getLegacyHookTokens() as $legacyHookToken) {
75 'entity' => $legacyHookToken['category'],
76 'field' => $legacyHookToken['name'],
77 'label' => $legacyHookToken['label'],
83 * Determine whether this token-handler should be used with
84 * the given processor.
86 * To short-circuit token-processing in irrelevant contexts,
89 * @param \Civi\Token\TokenProcessor $processor
92 public function checkActive(TokenProcessor
$processor): bool {
93 return in_array($this->getEntityIDField(), $processor->context
['schema'], TRUE);
99 protected function getEntityIDField(): string {
104 * Get functions declared using the legacy hook.
106 * Note that these only extend the contact entity (
107 * ie they are based on having a contact ID which they.
108 * may or may not use, but they don't have other
113 protected function getLegacyHookTokens(): array {
116 \CRM_Utils_Hook
::tokens($hookTokens);
117 foreach ($hookTokens as $tokenValues) {
118 foreach ($tokenValues as $key => $value) {
119 if (is_numeric($key)) {
120 // This appears to be an attempt to compensate for
121 // inconsistencies described in https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_tokenValues/#example
122 // in effect there is a suggestion that
123 // Send an Email" and "CiviMail" send different parameters to the tokenValues hook
124 // As of now 'send an email' renders hooks through this class.
125 // CiviMail it depends on the use or otherwise of flexmailer.
128 if (preg_match('/^\{([^\}]+)\}$/', $value, $matches)) {
129 $value = $matches[1];
131 $keyParts = explode('.', $key);
133 'category' => $keyParts[0],
134 'name' => $keyParts[1],
143 * Get all tokens advertised as contact tokens.
147 protected function getExposedFields(): array {
156 'external_identifier',
161 'preferred_communication_method',
162 'preferred_language',
163 'preferred_mail_format',
172 'communication_style_id',
181 'email_greeting_display',
182 'postal_greeting_display',
188 * Get the fields exposed from related entities.
190 * @return \string[][]
192 protected function getRelatedEntityTokenMetadata(): array {
199 'street_number_suffix',
202 'supplemental_address_1',
203 'supplemental_address_2',
204 'supplemental_address_3',
206 'postal_code_suffix',
217 'phone' => ['phone', 'phone_ext', 'phone_type_id'],
218 'email' => ['email', 'signature_html', 'signature_text', 'on_hold'],
219 'website' => ['url'],
220 'openid' => ['openid'],
221 'im' => ['name', 'provider_id'],
226 * Load token data from legacy hooks.
228 * While our goal is for people to move towards implementing
229 * toke processors the old-style hooks can extend contact
232 * When that is happening we need to load the full contact record
233 * to send to the hooks (not great for performance but the
234 * fix is to move away from implementing legacy style hooks).
236 * Consistent with prior behaviour we only load the contact it it
237 * is already loaded. In that scenario we also load any extra fields
238 * that might be wanted for the contact tokens.
240 * @param \Civi\Token\Event\TokenValueEvent $e
242 * @throws \CRM_Core_Exception
244 public function evaluateLegacyHookTokens(TokenValueEvent
$e): void
{
245 $messageTokens = $e->getTokenProcessor()->getMessageTokens();
246 $hookTokens = array_intersect(\CRM_Utils_Token
::getTokenCategories(), array_keys($messageTokens));
247 if (empty($hookTokens)) {
250 foreach ($e->getRows() as $row) {
251 if (empty($row->context
['contactId'])) {
255 $swapLocale = empty($row->context
['locale']) ?
NULL : \CRM_Utils_AutoClean
::swapLocale($row->context
['locale']);
256 if (empty($row->context
['contact'])) {
257 // If we don't have the contact already load it now, getting full
258 // details for hooks and anything the contact token resolution might
260 $row->context
['contact'] = $this->getContact($row->context
['contactId'], $messageTokens['contact'] ??
[], TRUE);
262 $contactArray = [$row->context
['contactId'] => $row->context
['contact']];
263 \CRM_Utils_Hook
::tokenValues($contactArray,
264 [$row->context
['contactId']],
265 empty($row->context
['mailingJobId']) ?
NULL : $row->context
['mailingJobId'],
267 $row->context
['controller']
269 foreach ($hookTokens as $hookToken) {
270 foreach ($messageTokens[$hookToken] as $tokenName) {
271 $row->format('text/html')->tokens($hookToken, $tokenName, $contactArray[$row->context
['contactId']]["{$hookToken}.{$tokenName}"] ??
'');
280 * @param \Civi\Token\Event\TokenValueEvent $e
282 * @throws TokenException
283 * @throws \CRM_Core_Exception
285 public function onEvaluate(TokenValueEvent
$e) {
286 $messageTokens = $e->getTokenProcessor()->getMessageTokens()['contact'] ??
[];
287 if (empty($messageTokens)) {
291 foreach ($e->getRows() as $row) {
292 if (empty($row->context
['contactId']) && empty($row->context
['contact'])) {
297 $swapLocale = empty($row->context
['locale']) ?
NULL : \CRM_Utils_AutoClean
::swapLocale($row->context
['locale']);
299 if (empty($row->context
['contact'])) {
300 $row->context
['contact'] = $this->getContact($row->context
['contactId'], $messageTokens);
303 foreach ($messageTokens as $token) {
304 if ($token === 'checksum') {
305 $cs = \CRM_Contact_BAO_Contact_Utils
::generateChecksum($row->context
['contactId'],
308 $row->context
['hash'] ??
NULL
310 $row->format('text/html')
311 ->tokens('contact', $token, "cs={$cs}");
313 elseif ($token === 'signature_html') {
314 $row->format('text/html')->tokens('contact', $token, html_entity_decode($row->context
['contact'][$token]));
317 parent
::evaluateToken($row, $this->entity
, $token, $row->context
['contact']);
324 * Get the field value.
326 * @param \Civi\Token\TokenRow $row
327 * @param string $field
330 protected function getFieldValue(TokenRow
$row, string $field) {
331 $entityName = 'contact';
332 if (isset($this->getDeprecatedTokens()[$field])) {
333 // Check the non-deprecated location first, fall back to deprecated
334 // this is important for the greetings because - they are weird in the query object.
335 $possibilities = [$this->getDeprecatedTokens()[$field], $field];
338 $possibilities = [$field];
339 if (in_array($field, $this->getDeprecatedTokens(), TRUE)) {
340 $possibilities[] = array_search($field, $this->getDeprecatedTokens(), TRUE);
344 foreach ($possibilities as $possibility) {
345 if (isset($row->context
[$entityName][$possibility])) {
346 return $row->context
[$entityName][$possibility];
353 * Get the metadata for the available fields.
356 * @noinspection PhpDocMissingThrowsInspection
357 * @noinspection PhpUnhandledExceptionInspection
359 protected function getTokenMetadata(): array {
360 if ($this->tokensMetadata
) {
361 return $this->tokensMetadata
;
363 if (Civi
::cache('metadata')->has($this->getCacheKey())) {
364 return Civi
::cache('metadata')->get($this->getCacheKey());
366 $this->fieldMetadata
= (array) civicrm_api4('Contact', 'getfields', ['checkPermissions' => FALSE], 'name');
367 $this->tokensMetadata
= $this->getBespokeTokens();
368 foreach ($this->fieldMetadata
as $field) {
369 $this->addFieldToTokenMetadata($field, $this->getExposedFields());
372 foreach ($this->getRelatedEntityTokenMetadata() as $entity => $exposedFields) {
373 $apiEntity = ($entity === 'openid') ?
'OpenID' : $entity;
374 $metadata = (array) civicrm_api4($apiEntity, 'getfields', ['checkPermissions' => FALSE], 'name');
375 foreach ($metadata as $field) {
376 $this->addFieldToTokenMetadata($field, $exposedFields, 'primary_' . $entity);
379 // Manually add in the abbreviated state province as that maps to
380 // what has traditionally been delivered.
381 $this->tokensMetadata
['primary_address.state_province_id:abbr'] = $this->tokensMetadata
['primary_address.state_province_id:label'];
382 $this->tokensMetadata
['primary_address.state_province_id:abbr']['name'] = 'state_province_id:abbr';
383 $this->tokensMetadata
['primary_address.state_province_id:abbr']['audience'] = 'user';
384 // Hide the label for now because we are not sure if there are paths
385 // where legacy token resolution is in play where this could not be resolved.
386 $this->tokensMetadata
['primary_address.state_province_id:label']['audience'] = 'sysadmin';
387 // Hide this really obscure one. Just cos it annoys me.
388 $this->tokensMetadata
['primary_address.manual_geo_code:label']['audience'] = 'sysadmin';
389 Civi
::cache('metadata')->set($this->getCacheKey(), $this->tokensMetadata
);
390 return $this->tokensMetadata
;
394 * Get the contact for the row.
396 * @param int $contactId
397 * @param array $requiredFields
398 * @param bool $getAll
401 * @throws \CRM_Core_Exception
403 protected function getContact(int $contactId, array $requiredFields, bool $getAll = FALSE): array {
404 $returnProperties = [];
405 if (in_array('checksum', $requiredFields, TRUE)) {
406 $returnProperties[] = 'hash';
408 foreach ($this->getTokenMappingsForRelatedEntities() as $oldName => $newName) {
409 if (in_array($oldName, $requiredFields, TRUE)) {
410 $returnProperties[] = $newName;
415 foreach ($requiredFields as $field) {
416 $fieldSpec = $this->getMetadataForField($field);
418 if (isset($fieldSpec['table_name']) && $fieldSpec['table_name'] !== 'civicrm_contact') {
419 $tableAlias = str_replace('civicrm_', 'primary_', $fieldSpec['table_name']);
420 $joins[$tableAlias] = $fieldSpec['entity'];
422 $prefix = $tableAlias . '.';
424 if ($fieldSpec['type'] === 'Custom') {
425 $customFields['custom_' . $fieldSpec['custom_field_id']] = $fieldSpec['name'];
427 $returnProperties[] = $prefix . $this->getMetadataForField($field)['name'];
431 $returnProperties = array_merge(['*', 'custom.*'], $this->getDeprecatedTokens(), $this->getTokenMappingsForRelatedEntities());
434 $contactApi = Contact
::get($this->checkPermissions
)
435 ->setSelect($returnProperties)->addWhere('id', '=', $contactId);
436 foreach ($joins as $alias => $joinEntity) {
437 $contactApi->addJoin($joinEntity . ' AS ' . $alias,
439 ['id', '=', $alias . '.contact_id'],
440 // For website the fact we use 'first' is the deduplication.
441 ($joinEntity !== 'Website' ?
[$alias . '.is_primary', '=', 1] : []));
443 $contact = $contactApi->execute()->first();
445 foreach ($this->getDeprecatedTokens() as $apiv3Name => $fieldName) {
446 // it would be set already with the right value for a greeting token
447 // the query object returns the db value for email_greeting_display
448 // and a numeric value for email_greeting if you put email_greeting
449 // in the return properties.
450 if (!isset($contact[$apiv3Name]) && array_key_exists($fieldName, $contact)) {
451 $contact[$apiv3Name] = $contact[$fieldName];
454 foreach ($this->getTokenMappingsForRelatedEntities() as $oldName => $newName) {
455 if (isset($contact[$newName])) {
456 $contact[$oldName] = $contact[$newName];
460 //update value of custom field token
461 foreach ($customFields as $apiv3Name => $fieldName) {
462 $value = $contact[$fieldName];
463 if ($this->getMetadataForField($apiv3Name)['data_type'] === 'Boolean') {
464 $value = (int) $value;
466 $contact[$apiv3Name] = \CRM_Core_BAO_CustomField
::displayValue($value, \CRM_Core_BAO_CustomField
::getKeyID($apiv3Name));
473 * Get the array of the return fields from 'get all'.
475 * This is the list from the BAO_Query object but copied
476 * here to be 'frozen in time'. The goal is to map to apiv4
477 * and stop using the legacy call to load the contact.
481 protected function getAllContactReturnFields(): array {
484 'legal_identifier' => 1,
485 'external_identifier' => 1,
487 'contact_sub_type' => 1,
490 'preferred_mail_format' => 1,
498 'communication_style_id' => 1,
501 'street_address' => 1,
502 'supplemental_address_1' => 1,
503 'supplemental_address_2' => 1,
504 'supplemental_address_3' => 1,
507 'postal_code_suffix' => 1,
508 'state_province' => 1,
517 'household_name' => 1,
518 'organization_name' => 1,
519 'deceased_date' => 1,
524 'current_employer' => 1,
531 'contact_is_deleted' => 1,
532 'preferred_communication_method' => 1,
533 'preferred_language' => 1,
538 * These tokens still work but we don't advertise them.
540 * We can remove from the following places
541 * - scheduled reminders
542 * - add to 'blocked' on pdf letter & email
544 * & then at some point start issuing warnings for them
545 * but contact tokens are pretty central so it might be
549 * Keys are deprecated tokens and values are their replacements.
551 protected function getDeprecatedTokens(): array {
553 'individual_prefix' => 'prefix_id:label',
554 'individual_suffix' => 'suffix_id:label',
555 'contact_type' => 'contact_type:label',
556 'gender' => 'gender_id:label',
557 'communication_style' => 'communication_style_id:label',
558 'preferred_communication_method' => 'preferred_communication_method:label',
559 'email_greeting' => 'email_greeting_display',
560 'postal_greeting' => 'postal_greeting_display',
561 'addressee' => 'addressee_display',
562 'contact_id' => 'id',
563 'contact_source' => 'source',
564 'contact_is_deleted' => 'is_deleted',
565 'current_employer_id' => 'employer_id',
570 * Get the tokens that are accessed by joining onto a related entity.
572 * Note the original thinking was to migrate to advertising the tokens
573 * that more accurately reflect the schema & also add support for e.g
574 * billing_address.street_address - which would be hugely useful for workflow
577 * However that feels like a bridge too far for this round
578 * since we haven't quite hit the goal of all token processing going through
579 * the token processor & we risk advertising tokens that don't work if we get
580 * ahead of that process.
584 protected function getTokenMappingsForRelatedEntities(): array {
586 'on_hold' => 'primary_email.on_hold',
587 'on_hold:label' => 'primary_email.on_hold:label',
588 'phone_type_id' => 'primary_phone.phone_type_id',
589 'phone_type_id:label' => 'primary_phone.phone_type_id:label',
590 'current_employer' => 'employer_id.display_name',
591 'location_type_id' => 'primary_address.location_type_id',
592 'location_type' => 'primary_address.location_type_id:label',
593 'location_type_id:label' => 'primary_address.location_type_id:label',
594 'street_address' => 'primary_address.street_address',
595 'address_id' => 'primary_address.id',
596 'address_name' => 'primary_address.name',
597 'street_number' => 'primary_address.street_number',
598 'street_number_suffix' => 'primary_address.street_number_suffix',
599 'street_name' => 'primary_address.street_name',
600 'street_unit' => 'primary_address.street_unit',
601 'supplemental_address_1' => 'primary_address.supplemental_address_1',
602 'supplemental_address_2' => 'primary_address.supplemental_address_2',
603 'supplemental_address_3' => 'primary_address.supplemental_address_3',
604 'city' => 'primary_address.city',
605 'postal_code' => 'primary_address.postal_code',
606 'postal_code_suffix' => 'primary_address.postal_code_suffix',
607 'geo_code_1' => 'primary_address.geo_code_1',
608 'geo_code_2' => 'primary_address.geo_code_2',
609 'manual_geo_code' => 'primary_address.manual_geo_code',
610 'master_id' => 'primary_address.master_id',
611 'county' => 'primary_address.county_id:label',
612 'county_id' => 'primary_address.county_id',
613 'state_province' => 'primary_address.state_province_id:abbr',
614 'state_province_id' => 'primary_address.state_province_id',
615 'country' => 'primary_address.country_id:label',
616 'country_id' => 'primary_address.country_id',
617 'world_region' => 'primary_address.country_id.region_id:name',
618 'phone_type' => 'primary_phone.phone_type_id:label',
619 'phone' => 'primary_phone.phone',
620 'phone_ext' => 'primary_phone.phone_ext',
621 'email' => 'primary_email.email',
622 'signature_text' => 'primary_email.signature_text',
623 'signature_html' => 'primary_email.signature_html',
624 'im' => 'primary_im.name',
625 'im_provider' => 'primary_im.provider_id',
626 'provider_id:label' => 'primary_im.provider_id:label',
627 'provider_id' => 'primary_im.provider_id',
628 'openid' => 'primary_openid.openid',
629 'url' => 'primary_website.url',
634 * Get calculated or otherwise 'special', tokens.
638 protected function getBespokeTokens(): array {
641 'title' => ts('Checksum'),
642 'name' => 'checksum',
643 'type' => 'calculated',
645 'data_type' => 'String',
646 'audience' => 'user',
648 'employer_id.display_name' => [
649 'title' => ts('Current Employer'),
650 'name' => 'employer_id.display_name',
652 'api_v3' => 'current_employer',
654 'data_type' => 'String',
655 'audience' => 'user',
657 'primary_address.country_id.region_id:name' => [
658 'title' => ts('World Region'),
659 'name' => 'country_id.region_id.name',
661 'api_v3' => 'world_region',
663 'data_type' => 'String',
664 'advertised_name' => 'world_region',
665 'audience' => 'user',
667 // this gets forced out if we specify individual fields
668 'organization_name' => [
669 'title' => ts('Organization name'),
670 'name' => 'organization_name',
673 'data_type' => 'String',
674 'audience' => 'sysadmin',