Merge pull request #21620 from colemanw/purifier2
[civicrm-core.git] / CRM / Contact / Tokens.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\Api4\Contact;
14 use Civi\Token\Event\TokenRegisterEvent;
15 use Civi\Token\Event\TokenValueEvent;
16 use Civi\Token\TokenProcessor;
17 use Civi\Token\TokenRow;
18
19 /**
20 * Class CRM_Contact_Tokens
21 *
22 * Generate "contact.*" tokens.
23 */
24 class CRM_Contact_Tokens extends CRM_Core_EntityTokens {
25
26 /**
27 * Get the entity name for api v4 calls.
28 *
29 * @return string
30 */
31 protected function getApiEntityName(): string {
32 return 'Contact';
33 }
34
35 /**
36 * @inheritDoc
37 */
38 public static function getSubscribedEvents(): array {
39 return [
40 'civi.token.eval' => [
41 ['evaluateLegacyHookTokens', 500],
42 ['onEvaluate'],
43 ],
44 'civi.token.list' => 'registerTokens',
45 ];
46 }
47
48 /**
49 * Register the declared tokens.
50 *
51 * @param \Civi\Token\Event\TokenRegisterEvent $e
52 * The registration event. Add new tokens using register().
53 *
54 * @throws \CRM_Core_Exception
55 */
56 public function registerTokens(TokenRegisterEvent $e): void {
57 if (!$this->checkActive($e->getTokenProcessor())) {
58 return;
59 }
60 $relatedTokens = array_flip($this->getTokenMappingsForRelatedEntities());
61 foreach ($this->getTokenMetadata() as $tokenName => $field) {
62 if ($field['audience'] === 'user') {
63 $e->register([
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'],
70 ]);
71 }
72 }
73 foreach ($this->getLegacyHookTokens() as $legacyHookToken) {
74 $e->register([
75 'entity' => $legacyHookToken['category'],
76 'field' => $legacyHookToken['name'],
77 'label' => $legacyHookToken['label'],
78 ]);
79 }
80 }
81
82 /**
83 * Determine whether this token-handler should be used with
84 * the given processor.
85 *
86 * To short-circuit token-processing in irrelevant contexts,
87 * override this.
88 *
89 * @param \Civi\Token\TokenProcessor $processor
90 * @return bool
91 */
92 public function checkActive(TokenProcessor $processor): bool {
93 return in_array($this->getEntityIDField(), $processor->context['schema'], TRUE);
94 }
95
96 /**
97 * @return string
98 */
99 protected function getEntityIDField(): string {
100 return 'contactId';
101 }
102
103 /**
104 * Get functions declared using the legacy hook.
105 *
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
109 * entity IDs.)
110 *
111 * @return array
112 */
113 protected function getLegacyHookTokens(): array {
114 $tokens = [];
115 $hookTokens = [];
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.
126 $key = $value;
127 }
128 if (preg_match('/^\{([^\}]+)\}$/', $value, $matches)) {
129 $value = $matches[1];
130 }
131 $keyParts = explode('.', $key);
132 $tokens[$key] = [
133 'category' => $keyParts[0],
134 'name' => $keyParts[1],
135 'label' => $value,
136 ];
137 }
138 }
139 return $tokens;
140 }
141
142 /**
143 * Get all tokens advertised as contact tokens.
144 *
145 * @return string[]
146 */
147 protected function getExposedFields(): array {
148 return [
149 'contact_type',
150 'do_not_email',
151 'do_not_phone',
152 'do_not_mail',
153 'do_not_sms',
154 'do_not_trade',
155 'is_opt_out',
156 'external_identifier',
157 'sort_name',
158 'display_name',
159 'nick_name',
160 'image_URL',
161 'preferred_communication_method',
162 'preferred_language',
163 'preferred_mail_format',
164 'hash',
165 'source',
166 'first_name',
167 'middle_name',
168 'last_name',
169 'prefix_id',
170 'suffix_id',
171 'formal_title',
172 'communication_style_id',
173 'job_title',
174 'gender_id',
175 'birth_date',
176 'employer_id',
177 'is_deleted',
178 'created_date',
179 'modified_date',
180 'addressee_display',
181 'email_greeting_display',
182 'postal_greeting_display',
183 'id',
184 ];
185 }
186
187 /**
188 * Get the fields exposed from related entities.
189 *
190 * @return \string[][]
191 */
192 protected function getRelatedEntityTokenMetadata(): array {
193 return [
194 'address' => [
195 'location_type_id',
196 'id',
197 'street_address',
198 'street_number',
199 'street_number_suffix',
200 'street_name',
201 'street_unit',
202 'supplemental_address_1',
203 'supplemental_address_2',
204 'supplemental_address_3',
205 'city',
206 'postal_code_suffix',
207 'postal_code',
208 'manual_geo_code',
209 'geo_code_1',
210 'geo_code_2',
211 'name',
212 'master_id',
213 'county_id',
214 'state_province_id',
215 'country_id',
216 ],
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'],
222 ];
223 }
224
225 /**
226 * Load token data from legacy hooks.
227 *
228 * While our goal is for people to move towards implementing
229 * toke processors the old-style hooks can extend contact
230 * token data.
231 *
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).
235 *
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.
239 *
240 * @param \Civi\Token\Event\TokenValueEvent $e
241 *
242 * @throws \CRM_Core_Exception
243 */
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)) {
248 return;
249 }
250 foreach ($e->getRows() as $row) {
251 if (empty($row->context['contactId'])) {
252 continue;
253 }
254 unset($swapLocale);
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
259 // want later.
260 $row->context['contact'] = $this->getContact($row->context['contactId'], $messageTokens['contact'] ?? [], TRUE);
261 }
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'],
266 $messageTokens,
267 $row->context['controller']
268 );
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}"] ?? '');
272 }
273 }
274 }
275 }
276
277 /**
278 * Load token data.
279 *
280 * @param \Civi\Token\Event\TokenValueEvent $e
281 *
282 * @throws TokenException
283 * @throws \CRM_Core_Exception
284 */
285 public function onEvaluate(TokenValueEvent $e) {
286 $messageTokens = $e->getTokenProcessor()->getMessageTokens()['contact'] ?? [];
287 if (empty($messageTokens)) {
288 return;
289 }
290
291 foreach ($e->getRows() as $row) {
292 if (empty($row->context['contactId']) && empty($row->context['contact'])) {
293 continue;
294 }
295
296 unset($swapLocale);
297 $swapLocale = empty($row->context['locale']) ? NULL : \CRM_Utils_AutoClean::swapLocale($row->context['locale']);
298
299 if (empty($row->context['contact'])) {
300 $row->context['contact'] = $this->getContact($row->context['contactId'], $messageTokens);
301 }
302
303 foreach ($messageTokens as $token) {
304 if ($token === 'checksum') {
305 $cs = \CRM_Contact_BAO_Contact_Utils::generateChecksum($row->context['contactId'],
306 NULL,
307 NULL,
308 $row->context['hash'] ?? NULL
309 );
310 $row->format('text/html')
311 ->tokens('contact', $token, "cs={$cs}");
312 }
313 elseif ($token === 'signature_html') {
314 $row->format('text/html')->tokens('contact', $token, html_entity_decode($row->context['contact'][$token]));
315 }
316 else {
317 parent::evaluateToken($row, $this->entity, $token, $row->context['contact']);
318 }
319 }
320 }
321 }
322
323 /**
324 * Get the field value.
325 *
326 * @param \Civi\Token\TokenRow $row
327 * @param string $field
328 * @return string|int
329 */
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];
336 }
337 else {
338 $possibilities = [$field];
339 if (in_array($field, $this->getDeprecatedTokens(), TRUE)) {
340 $possibilities[] = array_search($field, $this->getDeprecatedTokens(), TRUE);
341 }
342 }
343
344 foreach ($possibilities as $possibility) {
345 if (isset($row->context[$entityName][$possibility])) {
346 return $row->context[$entityName][$possibility];
347 }
348 }
349 return '';
350 }
351
352 /**
353 * Get the metadata for the available fields.
354 *
355 * @return array
356 * @noinspection PhpDocMissingThrowsInspection
357 * @noinspection PhpUnhandledExceptionInspection
358 */
359 protected function getTokenMetadata(): array {
360 if ($this->tokensMetadata) {
361 return $this->tokensMetadata;
362 }
363 if (Civi::cache('metadata')->has($this->getCacheKey())) {
364 return Civi::cache('metadata')->get($this->getCacheKey());
365 }
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());
370 }
371
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);
377 }
378 }
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;
391 }
392
393 /**
394 * Get the contact for the row.
395 *
396 * @param int $contactId
397 * @param array $requiredFields
398 * @param bool $getAll
399 *
400 * @return array
401 * @throws \CRM_Core_Exception
402 */
403 protected function getContact(int $contactId, array $requiredFields, bool $getAll = FALSE): array {
404 $returnProperties = [];
405 if (in_array('checksum', $requiredFields, TRUE)) {
406 $returnProperties[] = 'hash';
407 }
408 foreach ($this->getTokenMappingsForRelatedEntities() as $oldName => $newName) {
409 if (in_array($oldName, $requiredFields, TRUE)) {
410 $returnProperties[] = $newName;
411 }
412 }
413 $joins = [];
414 $customFields = [];
415 foreach ($requiredFields as $field) {
416 $fieldSpec = $this->getMetadataForField($field);
417 $prefix = '';
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'];
421
422 $prefix = $tableAlias . '.';
423 }
424 if ($fieldSpec['type'] === 'Custom') {
425 $customFields['custom_' . $fieldSpec['custom_field_id']] = $fieldSpec['name'];
426 }
427 $returnProperties[] = $prefix . $this->getMetadataForField($field)['name'];
428 }
429
430 if ($getAll) {
431 $returnProperties = array_merge(['*', 'custom.*'], $this->getDeprecatedTokens(), $this->getTokenMappingsForRelatedEntities());
432 }
433
434 $contactApi = Contact::get($this->checkPermissions)
435 ->setSelect($returnProperties)->addWhere('id', '=', $contactId);
436 foreach ($joins as $alias => $joinEntity) {
437 $contactApi->addJoin($joinEntity . ' AS ' . $alias,
438 'LEFT',
439 ['id', '=', $alias . '.contact_id'],
440 // For website the fact we use 'first' is the deduplication.
441 ($joinEntity !== 'Website' ? [$alias . '.is_primary', '=', 1] : []));
442 }
443 $contact = $contactApi->execute()->first();
444
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];
452 }
453 }
454 foreach ($this->getTokenMappingsForRelatedEntities() as $oldName => $newName) {
455 if (isset($contact[$newName])) {
456 $contact[$oldName] = $contact[$newName];
457 }
458 }
459
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;
465 }
466 $contact[$apiv3Name] = \CRM_Core_BAO_CustomField::displayValue($value, \CRM_Core_BAO_CustomField::getKeyID($apiv3Name));
467 }
468
469 return $contact;
470 }
471
472 /**
473 * Get the array of the return fields from 'get all'.
474 *
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.
478 *
479 * @return array
480 */
481 protected function getAllContactReturnFields(): array {
482 return [
483 'image_URL' => 1,
484 'legal_identifier' => 1,
485 'external_identifier' => 1,
486 'contact_type' => 1,
487 'contact_sub_type' => 1,
488 'sort_name' => 1,
489 'display_name' => 1,
490 'preferred_mail_format' => 1,
491 'nick_name' => 1,
492 'first_name' => 1,
493 'middle_name' => 1,
494 'last_name' => 1,
495 'prefix_id' => 1,
496 'suffix_id' => 1,
497 'formal_title' => 1,
498 'communication_style_id' => 1,
499 'birth_date' => 1,
500 'gender_id' => 1,
501 'street_address' => 1,
502 'supplemental_address_1' => 1,
503 'supplemental_address_2' => 1,
504 'supplemental_address_3' => 1,
505 'city' => 1,
506 'postal_code' => 1,
507 'postal_code_suffix' => 1,
508 'state_province' => 1,
509 'country' => 1,
510 'world_region' => 1,
511 'geo_code_1' => 1,
512 'geo_code_2' => 1,
513 'email' => 1,
514 'on_hold' => 1,
515 'phone' => 1,
516 'im' => 1,
517 'household_name' => 1,
518 'organization_name' => 1,
519 'deceased_date' => 1,
520 'is_deceased' => 1,
521 'job_title' => 1,
522 'legal_name' => 1,
523 'sic_code' => 1,
524 'current_employer' => 1,
525 'do_not_email' => 1,
526 'do_not_mail' => 1,
527 'do_not_sms' => 1,
528 'do_not_phone' => 1,
529 'do_not_trade' => 1,
530 'is_opt_out' => 1,
531 'contact_is_deleted' => 1,
532 'preferred_communication_method' => 1,
533 'preferred_language' => 1,
534 ];
535 }
536
537 /**
538 * These tokens still work but we don't advertise them.
539 *
540 * We can remove from the following places
541 * - scheduled reminders
542 * - add to 'blocked' on pdf letter & email
543 *
544 * & then at some point start issuing warnings for them
545 * but contact tokens are pretty central so it might be
546 * a bit drawn out.
547 *
548 * @return string[]
549 * Keys are deprecated tokens and values are their replacements.
550 */
551 protected function getDeprecatedTokens(): array {
552 return [
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',
566 ];
567 }
568
569 /**
570 * Get the tokens that are accessed by joining onto a related entity.
571 *
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
575 * message templates.
576 *
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.
581 *
582 * @return string[]
583 */
584 protected function getTokenMappingsForRelatedEntities(): array {
585 return [
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',
630 ];
631 }
632
633 /**
634 * Get calculated or otherwise 'special', tokens.
635 *
636 * @return array[]
637 */
638 protected function getBespokeTokens(): array {
639 return [
640 'checksum' => [
641 'title' => ts('Checksum'),
642 'name' => 'checksum',
643 'type' => 'calculated',
644 'options' => NULL,
645 'data_type' => 'String',
646 'audience' => 'user',
647 ],
648 'employer_id.display_name' => [
649 'title' => ts('Current Employer'),
650 'name' => 'employer_id.display_name',
651 'type' => 'mapped',
652 'api_v3' => 'current_employer',
653 'options' => NULL,
654 'data_type' => 'String',
655 'audience' => 'user',
656 ],
657 'primary_address.country_id.region_id:name' => [
658 'title' => ts('World Region'),
659 'name' => 'country_id.region_id.name',
660 'type' => 'mapped',
661 'api_v3' => 'world_region',
662 'options' => NULL,
663 'data_type' => 'String',
664 'advertised_name' => 'world_region',
665 'audience' => 'user',
666 ],
667 // this gets forced out if we specify individual fields
668 'organization_name' => [
669 'title' => ts('Organization name'),
670 'name' => 'organization_name',
671 'type' => 'Field',
672 'options' => NULL,
673 'data_type' => 'String',
674 'audience' => 'sysadmin',
675 ],
676 ];
677 }
678
679 }