3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
35 * Class to abstract token replacement.
37 class CRM_Utils_Token
{
38 static $_requiredTokens = NULL;
40 static $_tokens = array(
67 // we extract the stuff after the role / permission and return the
68 // civicrm email addresses of all users with that role / permission
69 // useful with rules integration
73 // populate this dynamically
75 // populate this dynamically
76 'contribution' => NULL,
85 'subscribe' => array('group'),
86 'unsubscribe' => array('group'),
87 'resubscribe' => array('group'),
88 'welcome' => array('group'),
94 * This is used by CiviMail but will be made redundant by FlexMailer.
97 public static function getRequiredTokens() {
98 if (self
::$_requiredTokens == NULL) {
99 self
::$_requiredTokens = array(
100 'domain.address' => ts("Domain address - displays your organization's postal address."),
101 'action.optOutUrl or action.unsubscribeUrl' => array(
102 'action.optOut' => ts("'Opt out via email' - displays an email address for recipients to opt out of receiving emails from your organization."),
103 '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."),
104 'action.unsubscribe' => ts("'Unsubscribe via email' - displays an email address for recipients to unsubscribe from the specific mailing list used to send this message."),
105 '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."),
109 return self
::$_requiredTokens;
113 * Check a string (mailing body) for required tokens.
119 * true if all required tokens are found,
120 * else an array of the missing tokens
122 public static function requiredTokens(&$str) {
123 // 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.
124 $requiredTokens = defined('CIVICRM_FLEXMAILER_HACK_REQUIRED_TOKENS') ? Civi\Core\Resolver
::singleton()->call(CIVICRM_FLEXMAILER_HACK_REQUIRED_TOKENS
, array()) : CRM_Utils_Token
::getRequiredTokens();
127 foreach ($requiredTokens as $token => $value) {
128 if (!is_array($value)) {
129 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
130 $missing[$token] = $value;
136 foreach ($value as $t => $d) {
138 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
143 $missing[$token] = $desc;
148 if (empty($missing)) {
155 * Wrapper for token matching.
157 * @param string $type
158 * The token type (domain,mailing,contact,action).
160 * The token variable.
162 * The string to search.
167 public static function token_match($type, $var, &$str) {
168 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
169 return preg_match("/(^|[^\{])$token/", $str);
173 * Wrapper for token replacing.
175 * @param string $type
178 * The token variable.
179 * @param string $value
180 * The value to substitute for the token.
181 * @param string (reference) $str The string to replace in
183 * @param bool $escapeSmarty
186 * The processed string
188 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
189 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
194 $value = self
::tokenEscapeSmarty($value);
196 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
201 * Get< the regex for token replacement
203 * @param string $token_type
204 * A string indicating the the type of token to be used in the expression.
207 * regular expression sutiable for using in preg_replace
209 private static function tokenRegex($token_type) {
210 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
214 * Escape the string so a malicious user cannot inject smarty code into the template.
216 * @param string $string
217 * A string that needs to be escaped from smarty parsing.
222 public static function tokenEscapeSmarty($string) {
223 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
224 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
228 * Replace all the domain-level tokens in $str
231 * The string with tokens to be replaced.
232 * @param object $domain
235 * Replace tokens with HTML or plain text.
237 * @param null $knownTokens
238 * @param bool $escapeSmarty
241 * The processed string
243 public static function &replaceDomainTokens(
248 $escapeSmarty = FALSE
252 !$knownTokens ||
empty($knownTokens[$key])
257 $str = preg_replace_callback(
258 self
::tokenRegex($key),
259 function ($matches) use (&$domain, $html, $escapeSmarty) {
260 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
271 * @param bool $escapeSmarty
273 * @return mixed|null|string
275 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
276 // check if the token we were passed is valid
277 // we have to do this because this function is
278 // called only when we find a token in the string
280 $loc = &$domain->getLocationValues();
282 if (!in_array($token, self
::$_tokens['domain'])) {
283 $value = "{domain.$token}";
285 elseif ($token == 'address') {
286 static $addressCache = array();
288 $cache_key = $html ?
'address-html' : 'address-text';
289 if (array_key_exists($cache_key, $addressCache)) {
290 return $addressCache[$cache_key];
294 // Construct the address token
296 if (!empty($loc[$token])) {
298 $value = $loc[$token][1]['display'];
299 $value = str_replace("\n", '<br />', $value);
302 $value = $loc[$token][1]['display_text'];
304 $addressCache[$cache_key] = $value;
307 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
308 $value = $domain->$token;
310 elseif ($token == 'phone' ||
$token == 'email') {
311 // Construct the phone and email tokens
314 if (!empty($loc[$token])) {
315 foreach ($loc[$token] as $index => $entity) {
316 $value = $entity[$token];
323 $value = self
::tokenEscapeSmarty($value);
330 * Replace all the org-level tokens in $str
332 * @fixme: This function appears to be broken, as it depends on
333 * nonexistant method: CRM_Core_BAO_CustomValue::getContactValues()
334 * Marking as deprecated until this is fixed
338 * The string with tokens to be replaced.
340 * Associative array of org properties.
342 * Replace tokens with HTML or plain text.
344 * @param bool $escapeSmarty
347 * The processed string
349 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
350 self
::$_tokens['org']
352 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
353 array('address', 'display_name', 'checksum', 'contact_id')
357 foreach (self
::$_tokens['org'] as $token) {
358 // print "Getting token value for $token<br/><br/>";
363 // If the string doesn't contain this token, skip it.
365 if (!self
::token_match('org', $token, $str)) {
369 // Construct value from $token and $contact
373 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
374 // only generate cv if we need it
376 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
378 foreach ($cv as $cvFieldID => $value) {
379 if ($cvFieldID == $cfID) {
380 $value = CRM_Core_BAO_CustomField
::displayValue($value, $cfID);
385 elseif ($token == 'checksum') {
386 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
389 elseif ($token == 'address') {
390 // Build the location values array
393 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
394 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
395 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
396 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
397 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
399 // Construct the address token
401 $value = CRM_Utils_Address
::format($loc);
403 $value = str_replace("\n", '<br />', $value);
407 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
410 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
417 * Replace all mailing tokens in $str
420 * The string with tokens to be replaced.
421 * @param object $mailing
422 * The mailing BAO, or null for validation.
424 * Replace tokens with HTML or plain text.
426 * @param null $knownTokens
427 * @param bool $escapeSmarty
430 * The processed string
432 public static function &replaceMailingTokens(
437 $escapeSmarty = FALSE
440 if (!$knownTokens ||
!isset($knownTokens[$key])) {
444 $str = preg_replace_callback(
445 self
::tokenRegex($key),
446 function ($matches) use (&$mailing, $escapeSmarty) {
447 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
457 * @param bool $escapeSmarty
461 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
467 $value = $mailing ?
$mailing->id
: 'undefined';
471 $value = $mailing ?
$mailing->name
: 'Mailing Name';
475 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
476 $value = implode(', ', $groups);
480 $value = $mailing->subject
;
484 $mailingKey = $mailing->id
;
485 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
488 $value = CRM_Utils_System
::url('civicrm/mailing/view',
489 "reset=1&id={$mailingKey}",
490 TRUE, NULL, FALSE, TRUE
496 // Note: editUrl and scheduleUrl used to be different, but now there's
497 // one screen which can adapt based on permissions (in workflow mode).
498 $value = CRM_Utils_System
::url('civicrm/mailing/send',
499 "reset=1&mid={$mailing->id}&continue=true",
500 TRUE, NULL, FALSE, TRUE
505 $page = new CRM_Mailing_Page_View();
506 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
509 case 'approvalStatus':
510 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
514 $value = $mailing->approval_note
;
518 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
519 "reset=1&mid={$mailing->id}",
520 TRUE, NULL, FALSE, TRUE
525 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
529 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
533 $value = "{mailing.$token}";
538 $value = self
::tokenEscapeSmarty($value);
544 * Replace all action tokens in $str
547 * The string with tokens to be replaced.
548 * @param array $addresses
549 * Assoc. array of VERP event addresses.
551 * Assoc. array of action URLs.
553 * Replace tokens with HTML or plain text.
554 * @param array $knownTokens
555 * A list of tokens that are known to exist in the email body.
557 * @param bool $escapeSmarty
560 * The processed string
562 public static function &replaceActionTokens(
568 $escapeSmarty = FALSE
571 // here we intersect with the list of pre-configured valid tokens
572 // so that we remove anything we do not recognize
573 // I hope to move this step out of here soon and
574 // then we will just iterate on a list of tokens that are passed to us
575 if (!$knownTokens ||
empty($knownTokens[$key])) {
579 $str = preg_replace_callback(
580 self
::tokenRegex($key),
581 function ($matches) use (&$addresses, &$urls, $html, $escapeSmarty) {
582 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
594 * @param bool $escapeSmarty
596 * @return mixed|string
598 public static function getActionTokenReplacement(
603 $escapeSmarty = FALSE
605 // If the token is an email action, use it. Otherwise, find the
608 if (!in_array($token, self
::$_tokens['action'])) {
609 $value = "{action.$token}";
612 $value = CRM_Utils_Array
::value($token, $addresses);
614 if ($value == NULL) {
615 $value = CRM_Utils_Array
::value($token, $urls);
618 if ($value && $html) {
620 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
621 $value = "mailto:$value";
624 elseif ($value && !$html) {
625 $value = str_replace('&', '&', $value);
630 $value = self
::tokenEscapeSmarty($value);
636 * Replace all the contact-level tokens in $str with information from
640 * The string with tokens to be replaced.
641 * @param array $contact
642 * Associative array of contact properties.
644 * Replace tokens with HTML or plain text.
645 * @param array $knownTokens
646 * A list of tokens that are known to exist in the email body.
647 * @param bool $returnBlankToken
648 * Return unevaluated token if value is null.
650 * @param bool $escapeSmarty
653 * The processed string
655 public static function &replaceContactTokens(
660 $returnBlankToken = FALSE,
661 $escapeSmarty = FALSE
664 if (self
::$_tokens[$key] == NULL) {
665 // This should come from UF
669 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
670 array('checksum', 'contact_id')
674 // here we intersect with the list of pre-configured valid tokens
675 // so that we remove anything we do not recognize
676 // I hope to move this step out of here soon and
677 // then we will just iterate on a list of tokens that are passed to us
678 if (!$knownTokens ||
empty($knownTokens[$key])) {
682 $str = preg_replace_callback(
683 self
::tokenRegex($key),
684 function ($matches) use (&$contact, $html, $returnBlankToken, $escapeSmarty) {
685 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
690 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
698 * @param bool $returnBlankToken
699 * @param bool $escapeSmarty
701 * @return bool|mixed|null|string
703 public static function getContactTokenReplacement(
707 $returnBlankToken = FALSE,
708 $escapeSmarty = FALSE
710 if (self
::$_tokens['contact'] == NULL) {
711 /* This should come from UF */
713 self
::$_tokens['contact']
715 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
716 array('checksum', 'contact_id')
720 // Construct value from $token and $contact
725 // Support legacy tokens
726 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
728 // check if the token we were passed is valid
729 // we have to do this because this function is
730 // called only when we find a token in the string
732 if (!in_array($token, self
::$_tokens['contact'])) {
735 elseif ($token == 'checksum') {
736 $hash = CRM_Utils_Array
::value('hash', $contact);
737 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
738 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
746 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
748 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
749 if (is_array($value)) {
752 // Convert pseudoconstants using metadata
753 elseif ($value && is_numeric($value)) {
754 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
755 if (!empty($allFields[$token]['pseudoconstant'])) {
756 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
759 elseif ($value && CRM_Utils_String
::endsWith($token, '_date')) {
760 $value = CRM_Utils_Date
::customFormat($value);
765 $value = str_replace('&', '&', $value);
768 // if null then return actual token
769 if ($returnBlankToken && !$value) {
774 $value = "{contact.$token}";
778 && !($returnBlankToken && $noReplace)
780 // $returnBlankToken means the caller wants to do further attempts at
781 // processing unreplaced tokens -- so don't escape them yet in this case.
782 $value = self
::tokenEscapeSmarty($value);
789 * Replace all the hook tokens in $str with information from
793 * The string with tokens to be replaced.
794 * @param array $contact
795 * Associative array of contact properties (including hook token values).
798 * Replace tokens with HTML or plain text.
800 * @param bool $escapeSmarty
803 * The processed string
805 public static function &replaceHookTokens(
810 $escapeSmarty = FALSE
812 foreach ($categories as $key) {
813 $str = preg_replace_callback(
814 self
::tokenRegex($key),
815 function ($matches) use (&$contact, $key, $html, $escapeSmarty) {
816 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
825 * Parse html through Smarty resolving any smarty functions.
826 * @param string $tokenHtml
827 * @param array $entity
828 * @param string $entityType
830 * html parsed through smarty
832 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
833 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
834 $smarty = CRM_Core_Smarty
::singleton();
835 // also add the tokens to the template
836 $smarty->assign_by_ref($entityType, $entity);
837 $tokenHtml = $smarty->fetch("string:$tokenHtml");
847 * @param bool $escapeSmarty
849 * @return mixed|string
851 public static function getHookTokenReplacement(
856 $escapeSmarty = FALSE
858 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
860 if ($value && !$html) {
861 $value = str_replace('&', '&', $value);
865 $value = self
::tokenEscapeSmarty($value);
872 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
873 * for example {{token}} or \{token} will result in {token} in the final email
875 * this routine will remove the extra backslashes and braces
877 * @param $str ref to the string that will be scanned and modified
879 public static function unescapeTokens(&$str) {
880 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
884 * Replace unsubscribe tokens.
887 * The string with tokens to be replaced.
888 * @param object $domain
890 * @param array $groups
891 * The groups (if any) being unsubscribed.
893 * Replace tokens with html or plain text.
894 * @param int $contact_id
896 * @param string $hash The security hash of the unsub event
899 * The processed string
901 public static function &replaceUnsubscribeTokens(
909 if (self
::token_match('unsubscribe', 'group', $str)) {
910 if (!empty($groups)) {
911 $config = CRM_Core_Config
::singleton();
912 $base = CRM_Utils_System
::baseURL();
914 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
915 $dao = new CRM_Contact_DAO_Group();
917 while ($dao->fetch()) {
918 if (substr($dao->visibility
, 0, 6) == 'Public') {
919 $visibleGroups[] = $dao->id
;
922 $value = implode(', ', $groups);
923 self
::token_replace('unsubscribe', 'group', $value, $str);
930 * Replace resubscribe tokens.
933 * The string with tokens to be replaced.
934 * @param object $domain
936 * @param array $groups
937 * The groups (if any) being resubscribed.
939 * Replace tokens with html or plain text.
940 * @param int $contact_id
942 * @param string $hash The security hash of the resub event
945 * The processed string
947 public static function &replaceResubscribeTokens(
948 $str, &$domain, &$groups, $html,
951 if (self
::token_match('resubscribe', 'group', $str)) {
952 if (!empty($groups)) {
953 $value = implode(', ', $groups);
954 self
::token_replace('resubscribe', 'group', $value, $str);
961 * Replace subscription-confirmation-request tokens
964 * The string with tokens to be replaced.
965 * @param string $group
966 * The name of the group being subscribed.
969 * Replace tokens with html or plain text.
972 * The processed string
974 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
975 if (self
::token_match('subscribe', 'group', $str)) {
976 self
::token_replace('subscribe', 'group', $group, $str);
978 if (self
::token_match('subscribe', 'url', $str)) {
979 self
::token_replace('subscribe', 'url', $url, $str);
985 * Replace subscription-invitation tokens
988 * The string with tokens to be replaced.
991 * The processed string
993 public static function &replaceSubscribeInviteTokens($str) {
994 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
995 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
997 TRUE, NULL, FALSE, TRUE
999 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
1002 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
1003 foreach ($matches as $key => $value) {
1004 $gid = substr($value, 21, -1);
1005 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
1006 "reset=1&gid={$gid}",
1007 TRUE, NULL, FALSE, TRUE
1009 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
1013 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
1014 foreach ($matches as $key => $value) {
1015 $gid = substr($value, 18, -1);
1016 $config = CRM_Core_Config
::singleton();
1017 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
1018 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1019 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1020 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1027 * Replace welcome/confirmation tokens
1029 * @param string $str
1030 * The string with tokens to be replaced.
1031 * @param string $group
1032 * The name of the group being subscribed.
1034 * Replace tokens with html or plain text.
1037 * The processed string
1039 public static function &replaceWelcomeTokens($str, $group, $html) {
1040 if (self
::token_match('welcome', 'group', $str)) {
1041 self
::token_replace('welcome', 'group', $group, $str);
1047 * Find unprocessed tokens (call this last)
1049 * @param string $str
1050 * The string to search.
1053 * Array of tokens that weren't replaced
1055 public static function &unmatchedTokens(&$str) {
1056 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1057 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1062 * Find and replace tokens for each component.
1064 * @param string $str
1065 * The string to search.
1066 * @param array $contact
1067 * Associative array of contact properties.
1068 * @param array $components
1069 * A list of tokens that are known to exist in the email body.
1071 * @param bool $escapeSmarty
1072 * @param bool $returnEmptyToken
1075 * The processed string
1077 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1078 if (!is_array($components) ||
empty($contact)) {
1082 foreach ($components as $name => $tokens) {
1083 if (!is_array($tokens) ||
empty($tokens)) {
1087 foreach ($tokens as $token) {
1088 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1089 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1091 elseif (!$returnEmptyToken) {
1092 //replacing empty token
1093 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1101 * Get array of string tokens.
1103 * @param string $string
1104 * The input string to parse for tokens.
1107 * array of tokens mentioned in field
1109 public static function getTokens($string) {
1112 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1119 foreach ($matches[1] as $token) {
1120 list($type, $name) = preg_split('/\./', $token, 2);
1121 if ($name && $type) {
1122 if (!isset($tokens[$type])) {
1123 $tokens[$type] = array();
1125 $tokens[$type][] = $name;
1133 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1134 * and getTokens appears to be historical rather than intentional and should be reviewed
1137 * fields to pass in as return properties when populating token
1139 public static function getReturnProperties(&$string) {
1140 $returnProperties = array();
1142 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1148 foreach ($matches[1] as $token) {
1149 list($type, $name) = preg_split('/\./', $token, 2);
1151 $returnProperties["{$name}"] = 1;
1156 return $returnProperties;
1160 * Gives required details of contacts in an indexed array format so we
1161 * can iterate in a nice loop and do token evaluation
1163 * @param $contactIDs
1164 * @param array $returnProperties
1165 * Of required properties.
1166 * @param bool $skipOnHold Don't return on_hold contact info also.
1167 * Don't return on_hold contact info also.
1168 * @param bool $skipDeceased Don't return deceased contact info.
1169 * Don't return deceased contact info.
1170 * @param array $extraParams
1172 * @param array $tokens
1173 * The list of tokens we've extracted from the content.
1174 * @param null $className
1176 * The mailing list jobID - this is a legacy param.
1180 public static function getTokenDetails(
1182 $returnProperties = NULL,
1184 $skipDeceased = TRUE,
1185 $extraParams = NULL,
1192 foreach ($contactIDs as $key => $contactID) {
1194 CRM_Core_Form
::CB_PREFIX
. $contactID,
1203 if ($skipDeceased) {
1204 $params[] = array('is_deceased', '=', 0, 0, 0);
1209 $params[] = array('on_hold', '=', 0, 0, 0);
1213 $params = array_merge($params, $extraParams);
1216 // if return properties are not passed then get all return properties
1217 if (empty($returnProperties)) {
1218 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1219 array('display_name', 'checksum', 'contact_id')
1221 foreach ($fields as $key => $val) {
1222 // The unavailable fields are not available as tokens, do not have a one-2-one relationship
1223 // with contacts and are expensive to resolve.
1224 // @todo see CRM-17253 - there are some other fields (e.g note) that should be excluded
1225 // and upstream calls to this should populate return properties.
1226 $unavailableFields = array('group', 'tag');
1227 if (!in_array($val, $unavailableFields)) {
1228 $returnProperties[$val] = 1;
1234 foreach ($returnProperties as $name => $dontCare) {
1235 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1241 $details = CRM_Contact_BAO_Query
::apiQuery($params, $returnProperties, NULL, NULL, 0, count($contactIDs), TRUE, FALSE, TRUE, CRM_Contact_BAO_Query
::MODE_CONTACTS
, NULL, TRUE);
1243 $contactDetails = &$details[0];
1245 foreach ($contactIDs as $key => $contactID) {
1246 if (array_key_exists($contactID, $contactDetails)) {
1247 if (!empty($contactDetails[$contactID]['preferred_communication_method'])
1249 $communicationPreferences = array();
1250 foreach ($contactDetails[$contactID]['preferred_communication_method'] as $key => $val) {
1252 $communicationPreferences[$val] = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_DAO_Contact', 'preferred_communication_method', $val);
1255 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $communicationPreferences);
1258 foreach ($custom as $cfID) {
1259 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1260 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::displayValue($contactDetails[$contactID]["custom_{$cfID}"], $cfID);
1264 // special case for greeting replacement
1270 if (!empty($contactDetails[$contactID][$val])) {
1271 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1277 // also call a hook and get token details
1278 CRM_Utils_Hook
::tokenValues($details[0],
1288 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1289 * specific tokens to be rendered
1291 * @param array $contactIDs
1292 * This should always be array(0) or its not anonymous - left to keep signature same.
1294 * @param string $returnProperties
1295 * @param bool $skipOnHold
1296 * @param bool $skipDeceased
1297 * @param string $extraParams
1298 * @param array $tokens
1299 * @param string $className
1300 * Sent as context to the hook.
1301 * @param string $jobID
1303 * contactDetails with hooks swapped out
1305 public static function getAnonymousTokenDetails($contactIDs = array(
1308 $returnProperties = NULL,
1310 $skipDeceased = TRUE,
1311 $extraParams = NULL,
1315 $details = array(0 => array());
1316 // also call a hook and get token details
1317 CRM_Utils_Hook
::tokenValues($details[0],
1327 * Get Membership Token Details.
1328 * @param array $membershipIDs
1329 * Array of membership IDS.
1331 public static function getMembershipTokenDetails($membershipIDs) {
1332 $memberships = civicrm_api3('membership', 'get', array(
1333 'options' => array('limit' => 0),
1334 'membership_id' => array('IN' => (array) $membershipIDs),
1336 return $memberships['values'];
1340 * Replace existing greeting tokens in message/subject.
1342 * This function operates by reference, modifying the first parameter. Other
1343 * methods for token replacement in this class return the modified string.
1344 * This leads to inconsistency in how these methods must be applied.
1346 * @TODO Remove that inconsistency in usage.
1348 * ::replaceContactTokens() may need to be called after this method, to
1349 * replace tokens supplied from this method.
1351 * @param string $tokenString
1352 * @param array $contactDetails
1353 * @param int $contactId
1354 * @param string $className
1355 * @param bool $escapeSmarty
1357 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1359 if (!$contactDetails && !$contactId) {
1363 // check if there are any tokens
1364 $greetingTokens = self
::getTokens($tokenString);
1366 if (!empty($greetingTokens)) {
1367 // first use the existing contact object for token replacement
1368 if (!empty($contactDetails)) {
1369 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1372 self
::removeNullContactTokens($tokenString, $contactDetails, $greetingTokens);
1373 // check if there are any unevaluated tokens
1374 $greetingTokens = self
::getTokens($tokenString);
1376 // $greetingTokens not empty, means there are few tokens which are not
1377 // evaluated, like custom data etc
1378 // so retrieve it from database
1379 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1380 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1381 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1382 $contactParams = array('contact_id' => $contactId);
1384 $greetingDetails = self
::getTokenDetails($contactParams,
1385 $greetingsReturnProperties,
1391 // again replace tokens
1392 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1401 // check if there are still any unevaluated tokens
1402 $remainingTokens = self
::getTokens($tokenString);
1404 // $greetingTokens not empty, there are customized or hook tokens to replace
1405 if (!empty($remainingTokens)) {
1406 // Fill the return properties array
1407 $greetingTokens = $remainingTokens;
1408 reset($greetingTokens);
1409 $greetingsReturnProperties = array();
1410 while (list($key) = each($greetingTokens)) {
1411 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1412 $props = array_fill_keys(array_keys($props), 1);
1413 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1415 $contactParams = array('contact_id' => $contactId);
1416 $greetingDetails = self
::getTokenDetails($contactParams,
1417 $greetingsReturnProperties,
1422 // Prepare variables for calling replaceHookTokens
1423 $categories = array_keys($greetingTokens);
1424 list($contact) = $greetingDetails;
1425 // Replace tokens defined in Hooks.
1426 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1432 * At this point, $contactDetails has loaded the contact from the DAO. Any
1433 * (non-custom) missing fields are null. By removing them, we can avoid
1434 * expensive calls to CRM_Contact_BAO_Query.
1436 * @param string $tokenString
1437 * @param array $contactDetails
1439 private static function removeNullContactTokens(&$tokenString, $contactDetails, &$greetingTokens) {
1440 $greetingTokensOriginal = $greetingTokens;
1441 $contactFieldList = CRM_Contact_DAO_Contact
::fields();
1442 // Sometimes contactDetails are in a multidemensional array, sometimes a
1443 // single-dimension array.
1444 if (array_key_exists(0, $contactDetails) && is_array($contactDetails[0])) {
1445 $contactDetails = current($contactDetails[0]);
1447 $nullFields = array_keys(array_diff_key($contactFieldList, $contactDetails));
1449 // Handle legacy tokens
1450 foreach (self
::legacyContactTokens() as $oldToken => $newToken) {
1451 if (CRM_Utils_Array
::key($newToken, $nullFields)) {
1452 $nullFields[] = $oldToken;
1456 // Remove null contact fields from $greetingTokens
1457 $greetingTokens['contact'] = array_diff($greetingTokens['contact'], $nullFields);
1459 // Also remove them from $tokenString
1460 $removedTokens = array_diff($greetingTokensOriginal['contact'], $greetingTokens['contact']);
1461 // Handle legacy tokens again, sigh
1462 if (!empty($removedTokens)) {
1463 foreach ($removedTokens as $token) {
1464 if (CRM_Utils_Array
::value($token, self
::legacyContactTokens()) !== NULL) {
1465 $removedTokens[] = CRM_Utils_Array
::value($token, self
::legacyContactTokens());
1468 foreach ($removedTokens as $token) {
1469 $tokenString = str_replace("{contact.$token}", '', $tokenString);
1479 public static function flattenTokens(&$tokens) {
1480 $flattenTokens = array();
1487 if (!isset($tokens[$prop])) {
1490 foreach ($tokens[$prop] as $type => $names) {
1491 if (!isset($flattenTokens[$type])) {
1492 $flattenTokens[$type] = array();
1494 foreach ($names as $name) {
1495 $flattenTokens[$type][$name] = 1;
1500 return $flattenTokens;
1504 * Replace all user tokens in $str
1506 * @param string $str
1507 * The string with tokens to be replaced.
1509 * @param null $knownTokens
1510 * @param bool $escapeSmarty
1513 * The processed string
1515 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1517 if (!$knownTokens ||
1518 !isset($knownTokens[$key])
1523 $str = preg_replace_callback(
1524 self
::tokenRegex($key),
1525 function ($matches) use ($escapeSmarty) {
1526 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1535 * @param bool $escapeSmarty
1539 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1542 list($objectName, $objectValue) = explode('-', $token, 2);
1544 switch ($objectName) {
1546 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1550 $value = CRM_Core_Permission
::roleEmails($objectValue);
1554 if ($escapeSmarty) {
1555 $value = self
::tokenEscapeSmarty($value);
1561 protected static function _buildContributionTokens() {
1562 $key = 'contribution';
1563 if (self
::$_tokens[$key] == NULL) {
1564 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1565 array('campaign', 'financial_type'),
1566 self
::getCustomFieldTokens('Contribution')
1572 * Store membership tokens on the static _tokens array.
1574 protected static function _buildMembershipTokens() {
1575 $key = 'membership';
1576 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1577 $membershipTokens = array();
1578 $tokens = CRM_Core_SelectValues
::membershipTokens();
1579 foreach ($tokens as $token => $dontCare) {
1580 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1582 self
::$_tokens[$key] = $membershipTokens;
1587 * Replace tokens for an entity.
1588 * @param string $entity
1589 * @param array $entityArray
1590 * (e.g. in format from api).
1591 * @param string $str
1592 * String to replace in.
1593 * @param array $knownTokens
1594 * Array of tokens present.
1595 * @param bool $escapeSmarty
1597 * string with replacements made
1599 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1600 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1604 $fn = 'get' . ucfirst($entity) . 'TokenReplacement';
1605 $fn = is_callable(array('CRM_Utils_Token', $fn)) ?
$fn : 'getApiTokenReplacement';
1606 // since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1607 foreach ($knownTokens[$entity] as $token) {
1608 $replacement = self
::$fn($entity, $token, $entityArray);
1609 if ($escapeSmarty) {
1610 $replacement = self
::tokenEscapeSmarty($replacement);
1612 $str = str_replace('{' . $entity . '.' . $token . '}', $replacement, $str);
1614 return preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1618 * @param int $caseId
1620 * @param array $knownTokens
1621 * @param bool $escapeSmarty
1623 * @throws \CiviCRM_API3_Exception
1625 public static function replaceCaseTokens($caseId, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1626 if (!$knownTokens ||
empty($knownTokens['case'])) {
1629 $case = civicrm_api3('case', 'getsingle', array('id' => $caseId));
1630 return self
::replaceEntityTokens('case', $case, $str, $knownTokens, $escapeSmarty);
1634 * Generic function for formatting token replacement for an api field
1636 * @param string $entity
1637 * @param string $token
1638 * @param array $entityArray
1640 * @throws \CiviCRM_API3_Exception
1642 public static function getApiTokenReplacement($entity, $token, $entityArray) {
1643 if (!isset($entityArray[$token])) {
1646 $field = civicrm_api3($entity, 'getfield', array('action' => 'get', 'name' => $token, 'get_options' => 'get'));
1647 $field = $field['values'];
1648 $fieldType = CRM_Utils_Array
::value('type', $field);
1650 if ($fieldType == CRM_Utils_Type
::T_BOOLEAN
&& empty($field['options'])) {
1651 $field['options'] = array(ts('No'), ts('Yes'));
1653 // Match pseudoconstants
1654 if (!empty($field['options'])) {
1656 foreach ((array) $entityArray[$token] as $val) {
1657 $ret[] = $field['options'][$val];
1659 return implode(', ', $ret);
1661 // Format date fields
1662 elseif ($entityArray[$token] && $fieldType == CRM_Utils_Type
::T_DATE
) {
1663 return CRM_Utils_Date
::customFormat($entityArray[$token]);
1665 return implode(', ', (array) $entityArray[$token]);
1669 * Replace Contribution tokens in html.
1671 * @param string $str
1672 * @param array $contribution
1673 * @param bool|string $html
1674 * @param string $knownTokens
1675 * @param bool|string $escapeSmarty
1679 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1680 $key = 'contribution';
1681 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1682 return $str; //early return
1684 self
::_buildContributionTokens();
1686 // here we intersect with the list of pre-configured valid tokens
1687 // so that we remove anything we do not recognize
1688 // I hope to move this step out of here soon and
1689 // then we will just iterate on a list of tokens that are passed to us
1691 $str = preg_replace_callback(
1692 self
::tokenRegex($key),
1693 function ($matches) use (&$contribution, $html, $escapeSmarty) {
1694 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1699 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1704 * We have a situation where we are rendering more than one token in each field because we are combining
1705 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1707 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1708 * it applies (other tokens are OK including date fields)
1710 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1711 * does - but the fields is already being formatted through a date function
1713 * @param string $separator
1714 * @param string $str
1715 * @param array $contribution
1716 * @param bool|string $html
1717 * @param string $knownTokens
1718 * @param bool|string $escapeSmarty
1722 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1723 if (empty($knownTokens['contribution'])) {
1727 if (in_array('receive_date', $knownTokens['contribution'])) {
1728 $formattedDates = array();
1729 $dates = explode($separator, $contribution['receive_date']);
1730 foreach ($dates as $date) {
1731 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1733 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1734 unset($knownTokens['contribution']['receive_date']);
1736 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1740 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1741 * - this is used by the pdfLetter task from membership search
1742 * @param string $entity
1743 * should always be "membership"
1744 * @param string $token
1746 * @param array $membership
1747 * An api result array for a single membership.
1748 * @return string token replacement
1750 public static function getMembershipTokenReplacement($entity, $token, $membership) {
1751 self
::_buildMembershipTokens();
1754 $value = $membership['membership_name'];
1758 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1759 $value = $statuses[$membership['status_id']];
1764 $value = civicrm_api3('membership_type', 'getvalue', array(
1765 'id' => $membership['membership_type_id'],
1766 'return' => 'minimum_fee',
1769 catch (CiviCRM_API3_Exception
$e) {
1770 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1771 // api handles NULL (4.4)
1777 if (in_array($token, self
::$_tokens[$entity])) {
1778 $value = $membership[$token];
1779 if (CRM_Utils_String
::endsWith($token, '_date')) {
1780 $value = CRM_Utils_Date
::customFormat($value);
1785 $value = "{$entity}.{$token}";
1795 * @param $contribution
1797 * @param bool $escapeSmarty
1799 * @return mixed|string
1801 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1802 self
::_buildContributionTokens();
1805 case 'total_amount':
1808 case 'non_deductible_amount':
1809 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1812 case 'receive_date':
1813 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1814 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1818 if (!in_array($token, self
::$_tokens['contribution'])) {
1819 $value = "{contribution.$token}";
1822 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1827 if ($escapeSmarty) {
1828 $value = self
::tokenEscapeSmarty($value);
1835 * [legacy_token => new_token]
1837 public static function legacyContactTokens() {
1839 'individual_prefix' => 'prefix_id',
1840 'individual_suffix' => 'suffix_id',
1841 'gender' => 'gender_id',
1842 'communication_style' => 'communication_style_id',
1847 * Get all custom field tokens of $entity
1849 * @param string $entity
1850 * @param bool $usedForTokenWidget
1852 * @return array $customTokens
1853 * return custom field tokens in array('custom_N' => 'label') format
1855 public static function getCustomFieldTokens($entity, $usedForTokenWidget = FALSE) {
1856 $customTokens = array();
1857 $tokenName = $usedForTokenWidget ?
"{contribution.custom_%d}" : "custom_%d";
1858 foreach (CRM_Core_BAO_CustomField
::getFields($entity) as $id => $info) {
1859 $customTokens[sprintf($tokenName, $id)] = $info['label'];
1862 return $customTokens;
1866 * Formats a token list for the select2 widget
1871 public static function formatTokensForDisplay($tokens) {
1872 $sorted = $output = array();
1874 // Sort in ascending order by ignoring word case
1875 natcasesort($tokens);
1877 // Attempt to place tokens into optgroups
1878 // @todo These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1879 foreach ($tokens as $k => $v) {
1880 // Check to see if this token is already in a group e.g. for custom fields
1881 $split = explode(' :: ', $v);
1882 if (!empty($split[1])) {
1883 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1887 $split = explode('.', trim($k, '{}'));
1888 if (isset($split[1])) {
1889 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1892 $entity = 'Contact';
1894 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1899 foreach ($sorted as $k => $v) {
1900 $output[] = array('text' => $k, 'children' => $v);