3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
19 * Class to abstract token replacement.
21 class CRM_Utils_Token
{
22 public static $_requiredTokens = NULL;
24 public static $_tokens = [
51 // we extract the stuff after the role / permission and return the
52 // civicrm email addresses of all users with that role / permission
53 // useful with rules integration
57 // populate this dynamically
59 // populate this dynamically
60 'contribution' => NULL,
69 'subscribe' => ['group'],
70 'unsubscribe' => ['group'],
71 'resubscribe' => ['group'],
72 'welcome' => ['group'],
77 * This is used by CiviMail but will be made redundant by FlexMailer.
80 public static function getRequiredTokens() {
81 if (self
::$_requiredTokens == NULL) {
82 self
::$_requiredTokens = [
83 'domain.address' => ts("Domain address - displays your organization's postal address."),
84 'action.optOutUrl or action.unsubscribeUrl' => [
85 'action.optOut' => ts("'Opt out via email' - displays an email address for recipients to opt out of receiving emails from your organization."),
86 'action.optOutUrl' => ts("'Opt out via web page' - creates a link for recipients to click if they want to opt out of receiving emails from your organization. Alternatively, you can include the 'Opt out via email' token."),
87 'action.unsubscribe' => ts("'Unsubscribe via email' - displays an email address for recipients to unsubscribe from the specific mailing list used to send this message."),
88 'action.unsubscribeUrl' => ts("'Unsubscribe via web page' - creates a link for recipients to unsubscribe from the specific mailing list used to send this message. Alternatively, you can include the 'Unsubscribe via email' token or one of the Opt-out tokens."),
92 return self
::$_requiredTokens;
96 * Check a string (mailing body) for required tokens.
102 * true if all required tokens are found,
103 * else an array of the missing tokens
105 public static function requiredTokens(&$str) {
106 // FlexMailer is a refactoring of CiviMail which provides new hooks/APIs/docs. If the sysadmin has opted to enable it, then use that instead of CiviMail.
107 $requiredTokens = defined('CIVICRM_FLEXMAILER_HACK_REQUIRED_TOKENS') ? Civi\Core\Resolver
::singleton()->call(CIVICRM_FLEXMAILER_HACK_REQUIRED_TOKENS
, []) : CRM_Utils_Token
::getRequiredTokens();
110 foreach ($requiredTokens as $token => $value) {
111 if (!is_array($value)) {
112 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
113 $missing[$token] = $value;
119 foreach ($value as $t => $d) {
121 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
126 $missing[$token] = $desc;
131 if (empty($missing)) {
138 * Wrapper for token matching.
140 * @param string $type
141 * The token type (domain,mailing,contact,action).
143 * The token variable.
145 * The string to search.
150 public static function token_match($type, $var, &$str) {
151 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
152 return preg_match("/(^|[^\{])$token/", $str);
156 * Wrapper for token replacing.
158 * @param string $type
161 * The token variable.
162 * @param string $value
163 * The value to substitute for the token.
164 * @param string $str (reference) The string to replace in
166 * @param bool $escapeSmarty
169 * The processed string
171 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
172 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
177 $value = self
::tokenEscapeSmarty($value);
179 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
184 * Get< the regex for token replacement
186 * @param string $token_type
187 * A string indicating the the type of token to be used in the expression.
190 * regular expression sutiable for using in preg_replace
192 private static function tokenRegex($token_type) {
193 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
197 * Escape the string so a malicious user cannot inject smarty code into the template.
199 * @param string $string
200 * A string that needs to be escaped from smarty parsing.
205 public static function tokenEscapeSmarty($string) {
206 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
207 return preg_replace(['/{/', '/(?<!{ldelim)}/'], ['{ldelim}', '{rdelim}'], $string);
211 * Replace all the domain-level tokens in $str
214 * The string with tokens to be replaced.
215 * @param object $domain
218 * Replace tokens with HTML or plain text.
220 * @param null $knownTokens
221 * @param bool $escapeSmarty
224 * The processed string
226 public static function &replaceDomainTokens(
231 $escapeSmarty = FALSE
235 !$knownTokens ||
empty($knownTokens[$key])
240 $str = preg_replace_callback(
241 self
::tokenRegex($key),
242 function ($matches) use (&$domain, $html, $escapeSmarty) {
243 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
254 * @param bool $escapeSmarty
256 * @return mixed|null|string
258 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
259 // check if the token we were passed is valid
260 // we have to do this because this function is
261 // called only when we find a token in the string
263 $loc = &$domain->getLocationValues();
265 if (!in_array($token, self
::$_tokens['domain'])) {
266 $value = "{domain.$token}";
268 elseif ($token == 'address') {
269 static $addressCache = [];
271 $cache_key = $html ?
'address-html' : 'address-text';
272 if (array_key_exists($cache_key, $addressCache)) {
273 return $addressCache[$cache_key];
277 // Construct the address token
279 if (!empty($loc[$token])) {
281 $value = $loc[$token][1]['display'];
282 $value = str_replace("\n", '<br />', $value);
285 $value = $loc[$token][1]['display_text'];
287 $addressCache[$cache_key] = $value;
290 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
291 $value = $domain->$token;
293 elseif ($token == 'phone' ||
$token == 'email') {
294 // Construct the phone and email tokens
297 if (!empty($loc[$token])) {
298 foreach ($loc[$token] as $index => $entity) {
299 $value = $entity[$token];
306 $value = self
::tokenEscapeSmarty($value);
313 * Replace all the org-level tokens in $str
315 * @fixme: This function appears to be broken, as it depends on
316 * nonexistant method: CRM_Core_BAO_CustomValue::getContactValues()
317 * Marking as deprecated until this is fixed
321 * The string with tokens to be replaced.
323 * Associative array of org properties.
325 * Replace tokens with HTML or plain text.
327 * @param bool $escapeSmarty
330 * The processed string
332 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
333 self
::$_tokens['org']
335 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
336 ['address', 'display_name', 'checksum', 'contact_id']
340 foreach (self
::$_tokens['org'] as $token) {
341 // print "Getting token value for $token<br/><br/>";
346 // If the string doesn't contain this token, skip it.
348 if (!self
::token_match('org', $token, $str)) {
352 // Construct value from $token and $contact
356 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
357 // only generate cv if we need it
359 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
361 foreach ($cv as $cvFieldID => $value) {
362 if ($cvFieldID == $cfID) {
363 $value = CRM_Core_BAO_CustomField
::displayValue($value, $cfID);
368 elseif ($token == 'checksum') {
369 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
372 elseif ($token == 'address') {
373 // Build the location values array
376 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
377 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
378 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
379 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
380 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
382 // Construct the address token
384 $value = CRM_Utils_Address
::format($loc);
386 $value = str_replace("\n", '<br />', $value);
390 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
393 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
400 * Replace all mailing tokens in $str
403 * The string with tokens to be replaced.
404 * @param object $mailing
405 * The mailing BAO, or null for validation.
407 * Replace tokens with HTML or plain text.
409 * @param null $knownTokens
410 * @param bool $escapeSmarty
413 * The processed string
415 public static function &replaceMailingTokens(
420 $escapeSmarty = FALSE
423 if (!$knownTokens ||
!isset($knownTokens[$key])) {
427 $str = preg_replace_callback(
428 self
::tokenRegex($key),
429 function ($matches) use (&$mailing, $escapeSmarty) {
430 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
440 * @param bool $escapeSmarty
444 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
450 $value = $mailing ?
$mailing->id
: 'undefined';
454 $value = $mailing ?
$mailing->name
: 'Mailing Name';
458 $groups = $mailing ?
$mailing->getGroupNames() : ['Mailing Groups'];
459 $value = implode(', ', $groups);
463 $value = $mailing->subject
;
467 $mailingKey = $mailing->id
;
468 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
471 $value = CRM_Utils_System
::url('civicrm/mailing/view',
472 "reset=1&id={$mailingKey}",
473 TRUE, NULL, FALSE, TRUE
479 // Note: editUrl and scheduleUrl used to be different, but now there's
480 // one screen which can adapt based on permissions (in workflow mode).
481 $value = CRM_Utils_System
::url('civicrm/mailing/send',
482 "reset=1&mid={$mailing->id}&continue=true",
483 TRUE, NULL, FALSE, TRUE
488 $page = new CRM_Mailing_Page_View();
489 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
492 case 'approvalStatus':
493 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
497 $value = $mailing->approval_note
;
501 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
502 "reset=1&mid={$mailing->id}",
503 TRUE, NULL, FALSE, TRUE
508 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
512 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
516 $value = "{mailing.$token}";
521 $value = self
::tokenEscapeSmarty($value);
527 * Replace all action tokens in $str
530 * The string with tokens to be replaced.
531 * @param array $addresses
532 * Assoc. array of VERP event addresses.
534 * Assoc. array of action URLs.
536 * Replace tokens with HTML or plain text.
537 * @param array $knownTokens
538 * A list of tokens that are known to exist in the email body.
540 * @param bool $escapeSmarty
543 * The processed string
545 public static function &replaceActionTokens(
551 $escapeSmarty = FALSE
554 // here we intersect with the list of pre-configured valid tokens
555 // so that we remove anything we do not recognize
556 // I hope to move this step out of here soon and
557 // then we will just iterate on a list of tokens that are passed to us
558 if (!$knownTokens ||
empty($knownTokens[$key])) {
562 $str = preg_replace_callback(
563 self
::tokenRegex($key),
564 function ($matches) use (&$addresses, &$urls, $html, $escapeSmarty) {
565 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
577 * @param bool $escapeSmarty
579 * @return mixed|string
581 public static function getActionTokenReplacement(
586 $escapeSmarty = FALSE
588 // If the token is an email action, use it. Otherwise, find the
591 if (!in_array($token, self
::$_tokens['action'])) {
592 $value = "{action.$token}";
595 $value = CRM_Utils_Array
::value($token, $addresses);
597 if ($value == NULL) {
598 $value = CRM_Utils_Array
::value($token, $urls);
601 if ($value && $html) {
603 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
604 $value = "mailto:$value";
607 elseif ($value && !$html) {
608 $value = str_replace('&', '&', $value);
613 $value = self
::tokenEscapeSmarty($value);
619 * Replace all the contact-level tokens in $str with information from
623 * The string with tokens to be replaced.
624 * @param array $contact
625 * Associative array of contact properties.
627 * Replace tokens with HTML or plain text.
628 * @param array $knownTokens
629 * A list of tokens that are known to exist in the email body.
630 * @param bool $returnBlankToken
631 * Return unevaluated token if value is null.
633 * @param bool $escapeSmarty
636 * The processed string
638 public static function &replaceContactTokens(
643 $returnBlankToken = FALSE,
644 $escapeSmarty = FALSE
646 // Refresh contact tokens in case they have changed. There is heavy caching
647 // in exportable fields so there is no benefit in doing this conditionally.
648 self
::$_tokens['contact'] = array_merge(
649 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
650 ['checksum', 'contact_id']
654 // here we intersect with the list of pre-configured valid tokens
655 // so that we remove anything we do not recognize
656 // I hope to move this step out of here soon and
657 // then we will just iterate on a list of tokens that are passed to us
658 if (!$knownTokens ||
empty($knownTokens[$key])) {
662 $str = preg_replace_callback(
663 self
::tokenRegex($key),
664 function ($matches) use (&$contact, $html, $returnBlankToken, $escapeSmarty) {
665 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
670 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
678 * @param bool $returnBlankToken
679 * @param bool $escapeSmarty
681 * @return bool|mixed|null|string
683 public static function getContactTokenReplacement(
687 $returnBlankToken = FALSE,
688 $escapeSmarty = FALSE
690 if (self
::$_tokens['contact'] == NULL) {
691 /* This should come from UF */
693 self
::$_tokens['contact']
695 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
696 ['checksum', 'contact_id']
700 // Construct value from $token and $contact
705 // Support legacy tokens
706 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
708 // check if the token we were passed is valid
709 // we have to do this because this function is
710 // called only when we find a token in the string
712 if (!in_array($token, self
::$_tokens['contact'])) {
715 elseif ($token == 'checksum') {
716 $hash = CRM_Utils_Array
::value('hash', $contact);
717 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
718 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
726 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
728 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
729 if (is_array($value)) {
732 // Convert pseudoconstants using metadata
733 elseif ($value && is_numeric($value)) {
734 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
735 if (!empty($allFields[$token]['pseudoconstant'])) {
736 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
739 elseif ($value && CRM_Utils_String
::endsWith($token, '_date')) {
740 $value = CRM_Utils_Date
::customFormat($value);
745 $value = str_replace('&', '&', $value);
748 // if null then return actual token
749 if ($returnBlankToken && !$value) {
754 $value = "{contact.$token}";
758 && !($returnBlankToken && $noReplace)
760 // $returnBlankToken means the caller wants to do further attempts at
761 // processing unreplaced tokens -- so don't escape them yet in this case.
762 $value = self
::tokenEscapeSmarty($value);
769 * Replace all the hook tokens in $str with information from
773 * The string with tokens to be replaced.
774 * @param array $contact
775 * Associative array of contact properties (including hook token values).
778 * Replace tokens with HTML or plain text.
780 * @param bool $escapeSmarty
783 * The processed string
785 public static function &replaceHookTokens(
790 $escapeSmarty = FALSE
792 foreach ($categories as $key) {
793 $str = preg_replace_callback(
794 self
::tokenRegex($key),
795 function ($matches) use (&$contact, $key, $html, $escapeSmarty) {
796 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
805 * Parse html through Smarty resolving any smarty functions.
806 * @param string $tokenHtml
807 * @param array $entity
808 * @param string $entityType
810 * html parsed through smarty
812 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
813 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
814 $smarty = CRM_Core_Smarty
::singleton();
815 // also add the tokens to the template
816 $smarty->assign_by_ref($entityType, $entity);
817 $tokenHtml = $smarty->fetch("string:$tokenHtml");
827 * @param bool $escapeSmarty
829 * @return mixed|string
831 public static function getHookTokenReplacement(
836 $escapeSmarty = FALSE
838 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
840 if ($value && !$html) {
841 $value = str_replace('&', '&', $value);
845 $value = self
::tokenEscapeSmarty($value);
852 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
853 * for example {{token}} or \{token} will result in {token} in the final email
855 * this routine will remove the extra backslashes and braces
857 * @param $str ref to the string that will be scanned and modified
859 public static function unescapeTokens(&$str) {
860 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
864 * Replace unsubscribe tokens.
867 * The string with tokens to be replaced.
868 * @param object $domain
870 * @param array $groups
871 * The groups (if any) being unsubscribed.
873 * Replace tokens with html or plain text.
874 * @param int $contact_id
876 * @param string $hash The security hash of the unsub event
879 * The processed string
881 public static function &replaceUnsubscribeTokens(
889 if (self
::token_match('unsubscribe', 'group', $str)) {
890 if (!empty($groups)) {
891 $config = CRM_Core_Config
::singleton();
892 $base = CRM_Utils_System
::baseURL();
894 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
895 $dao = new CRM_Contact_DAO_Group();
897 while ($dao->fetch()) {
898 if (substr($dao->visibility
, 0, 6) == 'Public') {
899 $visibleGroups[] = $dao->id
;
902 $value = implode(', ', $groups);
903 self
::token_replace('unsubscribe', 'group', $value, $str);
910 * Replace resubscribe tokens.
913 * The string with tokens to be replaced.
914 * @param object $domain
916 * @param array $groups
917 * The groups (if any) being resubscribed.
919 * Replace tokens with html or plain text.
920 * @param int $contact_id
922 * @param string $hash The security hash of the resub event
925 * The processed string
927 public static function &replaceResubscribeTokens(
928 $str, &$domain, &$groups, $html,
931 if (self
::token_match('resubscribe', 'group', $str)) {
932 if (!empty($groups)) {
933 $value = implode(', ', $groups);
934 self
::token_replace('resubscribe', 'group', $value, $str);
941 * Replace subscription-confirmation-request tokens
944 * The string with tokens to be replaced.
945 * @param string $group
946 * The name of the group being subscribed.
949 * Replace tokens with html or plain text.
952 * The processed string
954 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
955 if (self
::token_match('subscribe', 'group', $str)) {
956 self
::token_replace('subscribe', 'group', $group, $str);
958 if (self
::token_match('subscribe', 'url', $str)) {
959 self
::token_replace('subscribe', 'url', $url, $str);
965 * Replace subscription-invitation tokens
968 * The string with tokens to be replaced.
971 * The processed string
973 public static function &replaceSubscribeInviteTokens($str) {
974 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
975 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
977 TRUE, NULL, FALSE, TRUE
979 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
982 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
983 foreach ($matches as $key => $value) {
984 $gid = substr($value, 21, -1);
985 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
986 "reset=1&gid={$gid}",
987 TRUE, NULL, FALSE, TRUE
989 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
993 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
994 foreach ($matches as $key => $value) {
995 $gid = substr($value, 18, -1);
996 $config = CRM_Core_Config
::singleton();
997 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
998 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
999 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1000 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1007 * Replace welcome/confirmation tokens
1009 * @param string $str
1010 * The string with tokens to be replaced.
1011 * @param string $group
1012 * The name of the group being subscribed.
1014 * Replace tokens with html or plain text.
1017 * The processed string
1019 public static function &replaceWelcomeTokens($str, $group, $html) {
1020 if (self
::token_match('welcome', 'group', $str)) {
1021 self
::token_replace('welcome', 'group', $group, $str);
1027 * Find unprocessed tokens (call this last)
1029 * @param string $str
1030 * The string to search.
1033 * Array of tokens that weren't replaced
1035 public static function &unmatchedTokens(&$str) {
1036 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1037 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1042 * Find and replace tokens for each component.
1044 * @param string $str
1045 * The string to search.
1046 * @param array $contact
1047 * Associative array of contact properties.
1048 * @param array $components
1049 * A list of tokens that are known to exist in the email body.
1051 * @param bool $escapeSmarty
1052 * @param bool $returnEmptyToken
1055 * The processed string
1057 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1058 if (!is_array($components) ||
empty($contact)) {
1062 foreach ($components as $name => $tokens) {
1063 if (!is_array($tokens) ||
empty($tokens)) {
1067 foreach ($tokens as $token) {
1068 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1069 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1071 elseif (!$returnEmptyToken) {
1072 //replacing empty token
1073 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1081 * Get array of string tokens.
1083 * @param string $string
1084 * The input string to parse for tokens.
1087 * array of tokens mentioned in field
1089 public static function getTokens($string) {
1092 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1099 foreach ($matches[1] as $token) {
1100 list($type, $name) = preg_split('/\./', $token, 2);
1101 if ($name && $type) {
1102 if (!isset($tokens[$type])) {
1103 $tokens[$type] = [];
1105 $tokens[$type][] = $name;
1113 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1114 * and getTokens appears to be historical rather than intentional and should be reviewed
1117 * fields to pass in as return properties when populating token
1119 public static function getReturnProperties(&$string) {
1120 $returnProperties = [];
1122 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1128 foreach ($matches[1] as $token) {
1129 list($type, $name) = preg_split('/\./', $token, 2);
1131 $returnProperties["{$name}"] = 1;
1136 return $returnProperties;
1140 * Gives required details of contacts in an indexed array format so we
1141 * can iterate in a nice loop and do token evaluation
1143 * @param array $contactIDs
1144 * @param array $returnProperties
1145 * Of required properties.
1146 * @param bool $skipOnHold Don't return on_hold contact info also.
1147 * Don't return on_hold contact info also.
1148 * @param bool $skipDeceased Don't return deceased contact info.
1149 * Don't return deceased contact info.
1150 * @param array $extraParams
1152 * @param array $tokens
1153 * The list of tokens we've extracted from the content.
1154 * @param null $className
1156 * The mailing list jobID - this is a legacy param.
1160 public static function getTokenDetails(
1162 $returnProperties = NULL,
1164 $skipDeceased = TRUE,
1165 $extraParams = NULL,
1172 foreach ($contactIDs as $contactID) {
1174 CRM_Core_Form
::CB_PREFIX
. $contactID,
1183 if ($skipDeceased) {
1184 $params[] = ['is_deceased', '=', 0, 0, 0];
1189 $params[] = ['on_hold', '=', 0, 0, 0];
1193 $params = array_merge($params, $extraParams);
1196 // if return properties are not passed then get all return properties
1197 if (empty($returnProperties)) {
1198 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1199 ['display_name', 'checksum', 'contact_id']
1201 foreach ($fields as $val) {
1202 // The unavailable fields are not available as tokens, do not have a one-2-one relationship
1203 // with contacts and are expensive to resolve.
1204 // @todo see CRM-17253 - there are some other fields (e.g note) that should be excluded
1205 // and upstream calls to this should populate return properties.
1206 $unavailableFields = ['group', 'tag'];
1207 if (!in_array($val, $unavailableFields)) {
1208 $returnProperties[$val] = 1;
1214 foreach ($returnProperties as $name => $dontCare) {
1215 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1221 $details = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, count($contactIDs), TRUE, FALSE, TRUE, CRM_Contact_BAO_Query
::MODE_CONTACTS
, NULL, TRUE);
1223 $contactDetails = &$details[0];
1225 foreach ($contactIDs as $contactID) {
1226 if (array_key_exists($contactID, $contactDetails)) {
1227 if (!empty($contactDetails[$contactID]['preferred_communication_method'])
1229 $communicationPreferences = [];
1230 foreach ($contactDetails[$contactID]['preferred_communication_method'] as $val) {
1232 $communicationPreferences[$val] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_communication_method', $val);
1235 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $communicationPreferences);
1238 foreach ($custom as $cfID) {
1239 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1240 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::displayValue($contactDetails[$contactID]["custom_{$cfID}"], $cfID);
1244 // special case for greeting replacement
1250 if (!empty($contactDetails[$contactID][$val])) {
1251 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1257 // also call a hook and get token details
1258 CRM_Utils_Hook
::tokenValues($details[0],
1268 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1269 * specific tokens to be rendered
1271 * @param array $contactIDs
1272 * This should always be array(0) or its not anonymous - left to keep signature same.
1274 * @param string $returnProperties
1275 * @param bool $skipOnHold
1276 * @param bool $skipDeceased
1277 * @param string $extraParams
1278 * @param array $tokens
1279 * @param string $className
1280 * Sent as context to the hook.
1281 * @param string $jobID
1283 * contactDetails with hooks swapped out
1285 public static function getAnonymousTokenDetails($contactIDs = [
1288 $returnProperties = NULL,
1290 $skipDeceased = TRUE,
1291 $extraParams = NULL,
1295 $details = [0 => []];
1296 // also call a hook and get token details
1297 CRM_Utils_Hook
::tokenValues($details[0],
1307 * Get Membership Token Details.
1308 * @param array $membershipIDs
1309 * Array of membership IDS.
1311 public static function getMembershipTokenDetails($membershipIDs) {
1312 $memberships = civicrm_api3('membership', 'get', [
1313 'options' => ['limit' => 0],
1314 'membership_id' => ['IN' => (array) $membershipIDs],
1316 return $memberships['values'];
1320 * Replace existing greeting tokens in message/subject.
1322 * This function operates by reference, modifying the first parameter. Other
1323 * methods for token replacement in this class return the modified string.
1324 * This leads to inconsistency in how these methods must be applied.
1326 * @TODO Remove that inconsistency in usage.
1328 * ::replaceContactTokens() may need to be called after this method, to
1329 * replace tokens supplied from this method.
1331 * @param string $tokenString
1332 * @param array $contactDetails
1333 * @param int $contactId
1334 * @param string $className
1335 * @param bool $escapeSmarty
1337 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1339 if (!$contactDetails && !$contactId) {
1343 // check if there are any tokens
1344 $greetingTokens = self
::getTokens($tokenString);
1346 if (!empty($greetingTokens)) {
1347 // first use the existing contact object for token replacement
1348 if (!empty($contactDetails)) {
1349 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1352 self
::removeNullContactTokens($tokenString, $contactDetails, $greetingTokens);
1353 // check if there are any unevaluated tokens
1354 $greetingTokens = self
::getTokens($tokenString);
1356 // $greetingTokens not empty, means there are few tokens which are not
1357 // evaluated, like custom data etc
1358 // so retrieve it from database
1359 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1360 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1361 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1362 $contactParams = ['contact_id' => $contactId];
1364 $greetingDetails = self
::getTokenDetails($contactParams,
1365 $greetingsReturnProperties,
1371 // again replace tokens
1372 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1381 // check if there are still any unevaluated tokens
1382 $remainingTokens = self
::getTokens($tokenString);
1384 // $greetingTokens not empty, there are customized or hook tokens to replace
1385 if (!empty($remainingTokens)) {
1386 // Fill the return properties array
1387 $greetingTokens = $remainingTokens;
1388 reset($greetingTokens);
1389 $greetingsReturnProperties = [];
1390 foreach ($greetingTokens as $value) {
1391 $props = array_flip($value);
1392 $props = array_fill_keys(array_keys($props), 1);
1393 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1395 $contactParams = ['contact_id' => $contactId];
1396 $greetingDetails = self
::getTokenDetails($contactParams,
1397 $greetingsReturnProperties,
1402 // Prepare variables for calling replaceHookTokens
1403 $categories = array_keys($greetingTokens);
1404 list($contact) = $greetingDetails;
1405 // Replace tokens defined in Hooks.
1406 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1412 * At this point, $contactDetails has loaded the contact from the DAO. Any
1413 * (non-custom) missing fields are null. By removing them, we can avoid
1414 * expensive calls to CRM_Contact_BAO_Query.
1416 * @param string $tokenString
1417 * @param array $contactDetails
1418 * @param array $greetingTokens
1420 private static function removeNullContactTokens(&$tokenString, $contactDetails, &$greetingTokens) {
1422 // Only applies to contact tokens
1423 if (!array_key_exists('contact', $greetingTokens)) {
1427 $greetingTokensOriginal = $greetingTokens;
1428 $contactFieldList = CRM_Contact_DAO_Contact
::fields();
1429 // Sometimes contactDetails are in a multidemensional array, sometimes a
1430 // single-dimension array.
1431 if (array_key_exists(0, $contactDetails) && is_array($contactDetails[0])) {
1432 $contactDetails = current($contactDetails[0]);
1434 $nullFields = array_keys(array_diff_key($contactFieldList, $contactDetails));
1436 // Handle legacy tokens
1437 foreach (self
::legacyContactTokens() as $oldToken => $newToken) {
1438 if (CRM_Utils_Array
::key($newToken, $nullFields)) {
1439 $nullFields[] = $oldToken;
1443 // Remove null contact fields from $greetingTokens
1444 $greetingTokens['contact'] = array_diff($greetingTokens['contact'], $nullFields);
1446 // Also remove them from $tokenString
1447 $removedTokens = array_diff($greetingTokensOriginal['contact'], $greetingTokens['contact']);
1448 // Handle legacy tokens again, sigh
1449 if (!empty($removedTokens)) {
1450 foreach ($removedTokens as $token) {
1451 if (CRM_Utils_Array
::value($token, self
::legacyContactTokens()) !== NULL) {
1452 $removedTokens[] = CRM_Utils_Array
::value($token, self
::legacyContactTokens());
1455 foreach ($removedTokens as $token) {
1456 $tokenString = str_replace("{contact.$token}", '', $tokenString);
1466 public static function flattenTokens(&$tokens) {
1467 $flattenTokens = [];
1474 if (!isset($tokens[$prop])) {
1477 foreach ($tokens[$prop] as $type => $names) {
1478 if (!isset($flattenTokens[$type])) {
1479 $flattenTokens[$type] = [];
1481 foreach ($names as $name) {
1482 $flattenTokens[$type][$name] = 1;
1487 return $flattenTokens;
1491 * Replace all user tokens in $str
1493 * @param string $str
1494 * The string with tokens to be replaced.
1496 * @param null $knownTokens
1497 * @param bool $escapeSmarty
1500 * The processed string
1502 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1504 if (!$knownTokens ||
1505 !isset($knownTokens[$key])
1510 $str = preg_replace_callback(
1511 self
::tokenRegex($key),
1512 function ($matches) use ($escapeSmarty) {
1513 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1522 * @param bool $escapeSmarty
1526 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1529 list($objectName, $objectValue) = explode('-', $token, 2);
1531 switch ($objectName) {
1533 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1537 $value = CRM_Core_Permission
::roleEmails($objectValue);
1541 if ($escapeSmarty) {
1542 $value = self
::tokenEscapeSmarty($value);
1548 protected static function _buildContributionTokens() {
1549 $key = 'contribution';
1550 if (self
::$_tokens[$key] == NULL) {
1551 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1552 ['campaign', 'financial_type'],
1553 self
::getCustomFieldTokens('Contribution')
1559 * Store membership tokens on the static _tokens array.
1561 protected static function _buildMembershipTokens() {
1562 $key = 'membership';
1563 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1564 $membershipTokens = [];
1565 $tokens = CRM_Core_SelectValues
::membershipTokens();
1566 foreach ($tokens as $token => $dontCare) {
1567 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1569 self
::$_tokens[$key] = $membershipTokens;
1574 * Replace tokens for an entity.
1575 * @param string $entity
1576 * @param array $entityArray
1577 * (e.g. in format from api).
1578 * @param string $str
1579 * String to replace in.
1580 * @param array $knownTokens
1581 * Array of tokens present.
1582 * @param bool $escapeSmarty
1584 * string with replacements made
1586 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = [], $escapeSmarty = FALSE) {
1587 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1591 $fn = 'get' . ucfirst($entity) . 'TokenReplacement';
1592 $fn = is_callable(['CRM_Utils_Token', $fn]) ?
$fn : 'getApiTokenReplacement';
1593 // since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1594 foreach ($knownTokens[$entity] as $token) {
1595 $replacement = self
::$fn($entity, $token, $entityArray);
1596 if ($escapeSmarty) {
1597 $replacement = self
::tokenEscapeSmarty($replacement);
1599 $str = str_replace('{' . $entity . '.' . $token . '}', $replacement, $str);
1601 return preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1605 * @param int $caseId
1607 * @param array $knownTokens
1608 * @param bool $escapeSmarty
1610 * @throws \CiviCRM_API3_Exception
1612 public static function replaceCaseTokens($caseId, $str, $knownTokens = [], $escapeSmarty = FALSE) {
1613 if (!$knownTokens ||
empty($knownTokens['case'])) {
1616 $case = civicrm_api3('case', 'getsingle', ['id' => $caseId]);
1617 return self
::replaceEntityTokens('case', $case, $str, $knownTokens, $escapeSmarty);
1621 * Generic function for formatting token replacement for an api field
1623 * @param string $entity
1624 * @param string $token
1625 * @param array $entityArray
1627 * @throws \CiviCRM_API3_Exception
1629 public static function getApiTokenReplacement($entity, $token, $entityArray) {
1630 if (!isset($entityArray[$token])) {
1633 $field = civicrm_api3($entity, 'getfield', ['action' => 'get', 'name' => $token, 'get_options' => 'get']);
1634 $field = $field['values'];
1635 $fieldType = CRM_Utils_Array
::value('type', $field);
1637 if ($fieldType == CRM_Utils_Type
::T_BOOLEAN
&& empty($field['options'])) {
1638 $field['options'] = [ts('No'), ts('Yes')];
1640 // Match pseudoconstants
1641 if (!empty($field['options'])) {
1643 foreach ((array) $entityArray[$token] as $val) {
1644 $ret[] = $field['options'][$val];
1646 return implode(', ', $ret);
1648 // Format date fields
1649 elseif ($entityArray[$token] && $fieldType == CRM_Utils_Type
::T_DATE
) {
1650 return CRM_Utils_Date
::customFormat($entityArray[$token]);
1652 return implode(', ', (array) $entityArray[$token]);
1656 * Replace Contribution tokens in html.
1658 * @param string $str
1659 * @param array $contribution
1660 * @param bool|string $html
1661 * @param string $knownTokens
1662 * @param bool|string $escapeSmarty
1666 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1667 $key = 'contribution';
1668 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1672 self
::_buildContributionTokens();
1674 // here we intersect with the list of pre-configured valid tokens
1675 // so that we remove anything we do not recognize
1676 // I hope to move this step out of here soon and
1677 // then we will just iterate on a list of tokens that are passed to us
1679 $str = preg_replace_callback(
1680 self
::tokenRegex($key),
1681 function ($matches) use (&$contribution, $html, $escapeSmarty) {
1682 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1687 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1692 * We have a situation where we are rendering more than one token in each field because we are combining
1693 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1695 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1696 * it applies (other tokens are OK including date fields)
1698 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1699 * does - but the fields is already being formatted through a date function
1701 * @param string $separator
1702 * @param string $str
1703 * @param array $contribution
1704 * @param bool|string $html
1705 * @param string $knownTokens
1706 * @param bool|string $escapeSmarty
1710 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1711 if (empty($knownTokens['contribution'])) {
1715 if (in_array('receive_date', $knownTokens['contribution'])) {
1716 $formattedDates = [];
1717 $dates = explode($separator, $contribution['receive_date']);
1718 foreach ($dates as $date) {
1719 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, ['j', 'm', 'Y']);
1721 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1722 unset($knownTokens['contribution']['receive_date']);
1724 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1728 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1729 * - this is used by the pdfLetter task from membership search
1730 * @param string $entity
1731 * should always be "membership"
1732 * @param string $token
1734 * @param array $membership
1735 * An api result array for a single membership.
1736 * @return string token replacement
1738 public static function getMembershipTokenReplacement($entity, $token, $membership) {
1739 self
::_buildMembershipTokens();
1742 $value = $membership['membership_name'];
1746 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1747 $value = $statuses[$membership['status_id']];
1752 $value = civicrm_api3('membership_type', 'getvalue', [
1753 'id' => $membership['membership_type_id'],
1754 'return' => 'minimum_fee',
1756 $value = CRM_Utils_Money
::format($value, NULL, NULL, TRUE);
1758 catch (CiviCRM_API3_Exception
$e) {
1759 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1760 // api handles NULL (4.4)
1766 if (in_array($token, self
::$_tokens[$entity])) {
1767 $value = $membership[$token];
1768 if (CRM_Utils_String
::endsWith($token, '_date')) {
1769 $value = CRM_Utils_Date
::customFormat($value);
1774 $value = "{$entity}.{$token}";
1784 * @param $contribution
1786 * @param bool $escapeSmarty
1788 * @return mixed|string
1790 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1791 self
::_buildContributionTokens();
1794 case 'total_amount':
1797 case 'non_deductible_amount':
1798 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1801 case 'receive_date':
1802 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1803 $value = CRM_Utils_Date
::customFormat($value, NULL, ['j', 'm', 'Y']);
1807 if (!in_array($token, self
::$_tokens['contribution'])) {
1808 $value = "{contribution.$token}";
1811 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1816 if ($escapeSmarty) {
1817 $value = self
::tokenEscapeSmarty($value);
1824 * [legacy_token => new_token]
1826 public static function legacyContactTokens() {
1828 'individual_prefix' => 'prefix_id',
1829 'individual_suffix' => 'suffix_id',
1830 'gender' => 'gender_id',
1831 'communication_style' => 'communication_style_id',
1836 * Get all custom field tokens of $entity
1838 * @param string $entity
1839 * @param bool $usedForTokenWidget
1842 * return custom field tokens in array('custom_N' => 'label') format
1844 public static function getCustomFieldTokens($entity, $usedForTokenWidget = FALSE) {
1846 $tokenName = $usedForTokenWidget ?
"{contribution.custom_%d}" : "custom_%d";
1847 foreach (CRM_Core_BAO_CustomField
::getFields($entity) as $id => $info) {
1848 $customTokens[sprintf($tokenName, $id)] = $info['label'];
1851 return $customTokens;
1855 * Formats a token list for the select2 widget
1860 public static function formatTokensForDisplay($tokens) {
1861 $sorted = $output = [];
1863 // Sort in ascending order by ignoring word case
1864 natcasesort($tokens);
1866 // Attempt to place tokens into optgroups
1867 // @todo These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1868 foreach ($tokens as $k => $v) {
1869 // Check to see if this token is already in a group e.g. for custom fields
1870 $split = explode(' :: ', $v);
1871 if (!empty($split[1])) {
1872 $sorted[$split[1]][] = ['id' => $k, 'text' => $split[0]];
1876 $split = explode('.', trim($k, '{}'));
1877 if (isset($split[1])) {
1878 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1881 $entity = 'Contact';
1883 $sorted[ts($entity)][] = ['id' => $k, 'text' => $v];
1888 foreach ($sorted as $k => $v) {
1889 $output[] = ['text' => $k, 'children' => $v];