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 foreach ($this->getHookTokens() as $tokenValues) {
117 foreach ($tokenValues as $key => $value) {
118 if (is_numeric($key)) {
119 // This appears to be an attempt to compensate for
120 // inconsistencies described in https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_tokenValues/#example
121 // in effect there is a suggestion that
122 // Send an Email" and "CiviMail" send different parameters to the tokenValues hook
123 // As of now 'send an email' renders hooks through this class.
124 // CiviMail it depends on the use or otherwise of flexmailer.
127 if (preg_match('/^\{([^\}]+)\}$/', $value, $matches)) {
128 $value = $matches[1];
130 $keyParts = explode('.', $key);
132 'category' => $keyParts[0],
133 'name' => $keyParts[1],
142 * Get all tokens advertised as contact tokens.
146 protected function getExposedFields(): array {
155 'external_identifier',
160 'preferred_communication_method',
161 'preferred_language',
162 'preferred_mail_format',
171 'communication_style_id',
180 'email_greeting_display',
181 'postal_greeting_display',
187 * Get the fields exposed from related entities.
189 * @return \string[][]
191 protected function getRelatedEntityTokenMetadata(): array {
198 'street_number_suffix',
201 'supplemental_address_1',
202 'supplemental_address_2',
203 'supplemental_address_3',
205 'postal_code_suffix',
216 'phone' => ['phone', 'phone_ext', 'phone_type_id'],
217 'email' => ['email', 'signature_html', 'signature_text', 'on_hold'],
218 'website' => ['url'],
219 'openid' => ['openid'],
220 'im' => ['name', 'provider_id'],
225 * Load token data from legacy hooks.
227 * While our goal is for people to move towards implementing
228 * toke processors the old-style hooks can extend contact
231 * When that is happening we need to load the full contact record
232 * to send to the hooks (not great for performance but the
233 * fix is to move away from implementing legacy style hooks).
235 * Consistent with prior behaviour we only load the contact it it
236 * is already loaded. In that scenario we also load any extra fields
237 * that might be wanted for the contact tokens.
239 * @param \Civi\Token\Event\TokenValueEvent $e
241 * @throws \CRM_Core_Exception
243 public function evaluateLegacyHookTokens(TokenValueEvent
$e): void
{
244 $messageTokens = $e->getTokenProcessor()->getMessageTokens();
245 if (empty($messageTokens) ||
!array_intersect(array_keys($this->getHookTokens()), array_keys($messageTokens))) {
249 foreach ($e->getRows() as $row) {
250 if (empty($row->context
['contactId'])) {
254 $swapLocale = empty($row->context
['locale']) ?
NULL : \CRM_Utils_AutoClean
::swapLocale($row->context
['locale']);
255 if (empty($row->context
['contact'])) {
256 // If we don't have the contact already load it now, getting full
257 // details for hooks and anything the contact token resolution might
259 $row->context
['contact'] = $this->getContact($row->context
['contactId'], $messageTokens['contact'] ??
[], TRUE);
261 $contactArray = [$row->context
['contactId'] => $row->context
['contact']];
262 \CRM_Utils_Hook
::tokenValues($contactArray,
263 [$row->context
['contactId']],
264 empty($row->context
['mailingJobId']) ?
NULL : $row->context
['mailingJobId'],
266 $row->context
['controller']
268 foreach ($this->getHookTokens() as $category => $hookToken) {
269 if (!empty($messageTokens[$category])) {
270 foreach (array_keys($hookToken) as $tokenName) {
271 $tokenPartOnly = str_replace($category . '.', '', $tokenName);
272 if (in_array($tokenPartOnly, $messageTokens[$category], TRUE)) {
273 $row->format('text/html')
274 ->tokens($category, str_replace($category . '.', '', $tokenName), $contactArray[$row->context
['contactId']][$tokenName] ??
($contactArray[$row->context
['contactId']][$category . '.' . $tokenName] ??
''));
285 * @param \Civi\Token\Event\TokenValueEvent $e
287 * @throws TokenException
288 * @throws \CRM_Core_Exception
290 public function onEvaluate(TokenValueEvent
$e) {
291 $this->activeTokens
= $e->getTokenProcessor()->getMessageTokens()['contact'] ??
[];
292 if (empty($this->activeTokens
)) {
296 foreach ($e->getRows() as $row) {
297 if (empty($row->context
['contactId']) && empty($row->context
['contact'])) {
302 $swapLocale = empty($row->context
['locale']) ?
NULL : \CRM_Utils_AutoClean
::swapLocale($row->context
['locale']);
304 if (empty($row->context
['contact'])) {
305 $row->context
['contact'] = $this->getContact($row->context
['contactId'], $this->activeTokens
);
308 foreach ($this->activeTokens
as $token) {
309 if ($token === 'checksum') {
310 $cs = \CRM_Contact_BAO_Contact_Utils
::generateChecksum($row->context
['contactId'],
313 $row->context
['hash'] ??
NULL
315 $row->format('text/html')
316 ->tokens('contact', $token, "cs={$cs}");
318 elseif ($token === 'signature_html') {
319 $row->format('text/html')->tokens('contact', $token, html_entity_decode($this->getFieldValue($row, $token)));
322 parent
::evaluateToken($row, $this->entity
, $token, $row->context
['contact']);
329 * Get the field value.
331 * @param \Civi\Token\TokenRow $row
332 * @param string $field
335 protected function getFieldValue(TokenRow
$row, string $field) {
336 $entityName = 'contact';
337 if (isset($this->getDeprecatedTokens()[$field])) {
338 // Check the non-deprecated location first, fall back to deprecated
339 // this is important for the greetings because - they are weird in the query object.
340 $possibilities = [$this->getDeprecatedTokens()[$field], $field];
343 $possibilities = [$field];
344 if (in_array($field, $this->getDeprecatedTokens(), TRUE)) {
345 $possibilities[] = array_search($field, $this->getDeprecatedTokens(), TRUE);
349 foreach ($possibilities as $possibility) {
350 if (isset($row->context
[$entityName][$possibility])) {
351 return $row->context
[$entityName][$possibility];
354 $contactID = $this->getFieldValue($row, 'id');
356 $row->context
['contact'] = array_merge($this->getContact($contactID, $this->activeTokens
), $row->context
['contact']);
357 if (isset($row->context
[$entityName][$field])) {
358 return $row->context
[$entityName][$field];
365 * Get the metadata for the available fields.
368 * @noinspection PhpDocMissingThrowsInspection
369 * @noinspection PhpUnhandledExceptionInspection
371 protected function getTokenMetadata(): array {
372 if (Civi
::cache('metadata')->has($this->getCacheKey())) {
373 return Civi
::cache('metadata')->get($this->getCacheKey());
375 $this->fieldMetadata
= (array) civicrm_api4('Contact', 'getfields', ['checkPermissions' => FALSE], 'name');
376 $tokensMetadata = $this->getBespokeTokens();
377 foreach ($this->fieldMetadata
as $field) {
378 $this->addFieldToTokenMetadata($tokensMetadata, $field, $this->getExposedFields());
381 foreach ($this->getRelatedEntityTokenMetadata() as $entity => $exposedFields) {
382 $apiEntity = ($entity === 'openid') ?
'OpenID' : ucfirst($entity);
383 if ($apiEntity === 'Im') {
386 $metadata = (array) civicrm_api4($apiEntity, 'getfields', ['checkPermissions' => FALSE], 'name');
387 foreach ($metadata as $field) {
388 $this->addFieldToTokenMetadata($tokensMetadata, $field, $exposedFields, 'primary_' . $entity);
391 // Manually add in the abbreviated state province as that maps to
392 // what has traditionally been delivered.
393 $tokensMetadata['primary_address.state_province_id:abbr'] = $tokensMetadata['primary_address.state_province_id:label'];
394 $tokensMetadata['primary_address.state_province_id:abbr']['name'] = 'state_province_id:abbr';
395 $tokensMetadata['primary_address.state_province_id:abbr']['audience'] = 'user';
396 // Hide the label for now because we are not sure if there are paths
397 // where legacy token resolution is in play where this could not be resolved.
398 $tokensMetadata['primary_address.state_province_id:label']['audience'] = 'sysadmin';
399 // Hide this really obscure one. Just cos it annoys me.
400 $tokensMetadata['primary_address.manual_geo_code:label']['audience'] = 'sysadmin';
401 Civi
::cache('metadata')->set($this->getCacheKey(), $tokensMetadata);
402 return $tokensMetadata;
406 * Get the contact for the row.
408 * @param int $contactId
409 * @param array $requiredFields
410 * @param bool $getAll
413 * @throws \CRM_Core_Exception
415 protected function getContact(int $contactId, array $requiredFields, bool $getAll = FALSE): array {
416 $returnProperties = [];
417 if (in_array('checksum', $requiredFields, TRUE)) {
418 $returnProperties[] = 'hash';
420 foreach ($this->getTokenMappingsForRelatedEntities() as $oldName => $newName) {
421 if (in_array($oldName, $requiredFields, TRUE)) {
422 $returnProperties[] = $newName;
427 foreach ($requiredFields as $field) {
428 $fieldSpec = $this->getMetadataForField($field);
430 if (isset($fieldSpec['table_name']) && $fieldSpec['table_name'] !== 'civicrm_contact') {
431 $tableAlias = str_replace('civicrm_', 'primary_', $fieldSpec['table_name']);
432 $joins[$tableAlias] = $fieldSpec['entity'];
434 $prefix = $tableAlias . '.';
436 if ($fieldSpec['type'] === 'Custom') {
437 $customFields['custom_' . $fieldSpec['custom_field_id']] = $fieldSpec['name'];
439 $returnProperties[] = $prefix . $this->getMetadataForField($field)['name'];
443 $returnProperties = array_merge(['*', 'custom.*'], $this->getDeprecatedTokens(), $this->getTokenMappingsForRelatedEntities());
446 $contactApi = Contact
::get($this->checkPermissions
)
447 ->setSelect($returnProperties)->addWhere('id', '=', $contactId);
448 foreach ($joins as $alias => $joinEntity) {
449 $contactApi->addJoin($joinEntity . ' AS ' . $alias,
451 ['id', '=', $alias . '.contact_id'],
452 // For website the fact we use 'first' is the deduplication.
453 ($joinEntity !== 'Website' ?
[$alias . '.is_primary', '=', 1] : []));
455 $contact = $contactApi->execute()->first();
457 // This is probably a test-only situation where tokens are retrieved for a
458 // fake contact id - check `testReplaceGreetingTokens`
462 foreach ($this->getDeprecatedTokens() as $apiv3Name => $fieldName) {
463 // it would be set already with the right value for a greeting token
464 // the query object returns the db value for email_greeting_display
465 // and a numeric value for email_greeting if you put email_greeting
466 // in the return properties.
467 if (!isset($contact[$apiv3Name]) && array_key_exists($fieldName, $contact)) {
468 $contact[$apiv3Name] = $contact[$fieldName];
471 foreach ($this->getTokenMappingsForRelatedEntities() as $oldName => $newName) {
472 if (isset($contact[$newName])) {
473 $contact[$oldName] = $contact[$newName];
477 //update value of custom field token
478 foreach ($customFields as $apiv3Name => $fieldName) {
479 $value = $contact[$fieldName];
480 if ($this->getMetadataForField($apiv3Name)['data_type'] === 'Boolean') {
481 $value = (int) $value;
483 $contact[$apiv3Name] = \CRM_Core_BAO_CustomField
::displayValue($value, \CRM_Core_BAO_CustomField
::getKeyID($apiv3Name));
490 * Get the array of the return fields from 'get all'.
492 * This is the list from the BAO_Query object but copied
493 * here to be 'frozen in time'. The goal is to map to apiv4
494 * and stop using the legacy call to load the contact.
498 protected function getAllContactReturnFields(): array {
501 'legal_identifier' => 1,
502 'external_identifier' => 1,
504 'contact_sub_type' => 1,
507 'preferred_mail_format' => 1,
515 'communication_style_id' => 1,
518 'street_address' => 1,
519 'supplemental_address_1' => 1,
520 'supplemental_address_2' => 1,
521 'supplemental_address_3' => 1,
524 'postal_code_suffix' => 1,
525 'state_province' => 1,
534 'household_name' => 1,
535 'organization_name' => 1,
536 'deceased_date' => 1,
541 'current_employer' => 1,
548 'contact_is_deleted' => 1,
549 'preferred_communication_method' => 1,
550 'preferred_language' => 1,
555 * These tokens still work but we don't advertise them.
557 * We can remove from the following places
558 * - scheduled reminders
559 * - add to 'blocked' on pdf letter & email
561 * & then at some point start issuing warnings for them
562 * but contact tokens are pretty central so it might be
566 * Keys are deprecated tokens and values are their replacements.
568 protected function getDeprecatedTokens(): array {
570 'individual_prefix' => 'prefix_id:label',
571 'individual_suffix' => 'suffix_id:label',
572 'contact_type' => 'contact_type:label',
573 'gender' => 'gender_id:label',
574 'communication_style' => 'communication_style_id:label',
575 'preferred_communication_method' => 'preferred_communication_method:label',
576 'email_greeting' => 'email_greeting_display',
577 'postal_greeting' => 'postal_greeting_display',
578 'addressee' => 'addressee_display',
579 'contact_id' => 'id',
580 'contact_source' => 'source',
581 'contact_is_deleted' => 'is_deleted',
582 'current_employer_id' => 'employer_id',
587 * Get the tokens that are accessed by joining onto a related entity.
589 * Note the original thinking was to migrate to advertising the tokens
590 * that more accurately reflect the schema & also add support for e.g
591 * billing_address.street_address - which would be hugely useful for workflow
594 * However that feels like a bridge too far for this round
595 * since we haven't quite hit the goal of all token processing going through
596 * the token processor & we risk advertising tokens that don't work if we get
597 * ahead of that process.
601 protected function getTokenMappingsForRelatedEntities(): array {
603 'on_hold' => 'primary_email.on_hold',
604 'on_hold:label' => 'primary_email.on_hold:label',
605 'phone_type_id' => 'primary_phone.phone_type_id',
606 'phone_type_id:label' => 'primary_phone.phone_type_id:label',
607 'current_employer' => 'employer_id.display_name',
608 'location_type_id' => 'primary_address.location_type_id',
609 'location_type' => 'primary_address.location_type_id:label',
610 'location_type_id:label' => 'primary_address.location_type_id:label',
611 'street_address' => 'primary_address.street_address',
612 'address_id' => 'primary_address.id',
613 'address_name' => 'primary_address.name',
614 'street_number' => 'primary_address.street_number',
615 'street_number_suffix' => 'primary_address.street_number_suffix',
616 'street_name' => 'primary_address.street_name',
617 'street_unit' => 'primary_address.street_unit',
618 'supplemental_address_1' => 'primary_address.supplemental_address_1',
619 'supplemental_address_2' => 'primary_address.supplemental_address_2',
620 'supplemental_address_3' => 'primary_address.supplemental_address_3',
621 'city' => 'primary_address.city',
622 'postal_code' => 'primary_address.postal_code',
623 'postal_code_suffix' => 'primary_address.postal_code_suffix',
624 'geo_code_1' => 'primary_address.geo_code_1',
625 'geo_code_2' => 'primary_address.geo_code_2',
626 'manual_geo_code' => 'primary_address.manual_geo_code',
627 'master_id' => 'primary_address.master_id',
628 'county' => 'primary_address.county_id:label',
629 'county_id' => 'primary_address.county_id',
630 'state_province' => 'primary_address.state_province_id:abbr',
631 'state_province_id' => 'primary_address.state_province_id',
632 'country' => 'primary_address.country_id:label',
633 'country_id' => 'primary_address.country_id',
634 'world_region' => 'primary_address.country_id.region_id:name',
635 'phone_type' => 'primary_phone.phone_type_id:label',
636 'phone' => 'primary_phone.phone',
637 'phone_ext' => 'primary_phone.phone_ext',
638 'email' => 'primary_email.email',
639 'signature_text' => 'primary_email.signature_text',
640 'signature_html' => 'primary_email.signature_html',
641 'im' => 'primary_im.name',
642 'im_provider' => 'primary_im.provider_id',
643 'provider_id:label' => 'primary_im.provider_id:label',
644 'provider_id' => 'primary_im.provider_id',
645 'openid' => 'primary_openid.openid',
646 'url' => 'primary_website.url',
651 * Get calculated or otherwise 'special', tokens.
655 protected function getBespokeTokens(): array {
658 'title' => ts('Checksum'),
659 'name' => 'checksum',
660 'type' => 'calculated',
662 'data_type' => 'String',
663 'audience' => 'user',
665 'employer_id.display_name' => [
666 'title' => ts('Current Employer'),
667 'name' => 'employer_id.display_name',
669 'api_v3' => 'current_employer',
671 'data_type' => 'String',
672 'audience' => 'user',
674 'primary_address.country_id.region_id:name' => [
675 'title' => ts('World Region'),
676 'name' => 'country_id.region_id.name',
678 'api_v3' => 'world_region',
680 'data_type' => 'String',
681 'advertised_name' => 'world_region',
682 'audience' => 'user',
684 // this gets forced out if we specify individual fields
685 'organization_name' => [
686 'title' => ts('Organization name'),
687 'name' => 'organization_name',
690 'data_type' => 'String',
691 'audience' => 'sysadmin',
693 // this gets forced out if we specify individual fields
694 'household_name' => [
695 'title' => ts('Household name'),
696 'name' => 'household_name',
699 'data_type' => 'String',
700 'audience' => 'sysadmin',
706 * Get the tokens defined by the legacy hook.
710 protected function getHookTokens(): array {
711 if (isset(Civi
::$statics[__CLASS__
]['hook_tokens'])) {
712 return Civi
::$statics[__CLASS__
]['hook_tokens'];
715 \CRM_Utils_Hook
::tokens($tokens);
716 Civi
::$statics[__CLASS__
]['hook_tokens'] = $tokens;