3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
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'),
95 public static function getRequiredTokens() {
96 if (self
::$_requiredTokens == NULL) {
97 self
::$_requiredTokens = array(
98 'domain.address' => ts("Domain address - displays your organization's postal address."),
99 'action.optOutUrl or action.unsubscribeUrl' => array(
100 'action.optOut' => ts("'Opt out via email' - displays an email address for recipients to opt out of receiving emails from your organization."),
101 '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."),
102 'action.unsubscribe' => ts("'Unsubscribe via email' - displays an email address for recipients to unsubscribe from the specific mailing list used to send this message."),
103 '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."),
107 return self
::$_requiredTokens;
111 * Check a string (mailing body) for required tokens.
117 * true if all required tokens are found,
118 * else an array of the missing tokens
120 public static function requiredTokens(&$str) {
121 $requiredTokens = self
::getRequiredTokens();
124 foreach ($requiredTokens as $token => $value) {
125 if (!is_array($value)) {
126 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
127 $missing[$token] = $value;
133 foreach ($value as $t => $d) {
135 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
140 $missing[$token] = $desc;
145 if (empty($missing)) {
152 * Wrapper for token matching.
154 * @param string $type
155 * The token type (domain,mailing,contact,action).
157 * The token variable.
159 * The string to search.
164 public static function token_match($type, $var, &$str) {
165 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
166 return preg_match("/(^|[^\{])$token/", $str);
170 * Wrapper for token replacing.
172 * @param string $type
175 * The token variable.
176 * @param string $value
177 * The value to substitute for the token.
178 * @param string (reference) $str The string to replace in
180 * @param bool $escapeSmarty
183 * The processed string
185 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
186 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
191 $value = self
::tokenEscapeSmarty($value);
193 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
198 * Get< the regex for token replacement
200 * @param string $token_type
201 * A string indicating the the type of token to be used in the expression.
204 * regular expression sutiable for using in preg_replace
206 private static function tokenRegex($token_type) {
207 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
211 * Escape the string so a malicious user cannot inject smarty code into the template.
213 * @param string $string
214 * A string that needs to be escaped from smarty parsing.
219 public static function tokenEscapeSmarty($string) {
220 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
221 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
225 * Replace all the domain-level tokens in $str
228 * The string with tokens to be replaced.
229 * @param object $domain
232 * Replace tokens with HTML or plain text.
234 * @param null $knownTokens
235 * @param bool $escapeSmarty
238 * The processed string
240 public static function &replaceDomainTokens(
245 $escapeSmarty = FALSE
249 !$knownTokens ||
empty($knownTokens[$key])
254 $str = preg_replace_callback(
255 self
::tokenRegex($key),
256 function ($matches) use (&$domain, $html, $escapeSmarty) {
257 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
268 * @param bool $escapeSmarty
270 * @return mixed|null|string
272 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
273 // check if the token we were passed is valid
274 // we have to do this because this function is
275 // called only when we find a token in the string
277 $loc = &$domain->getLocationValues();
279 if (!in_array($token, self
::$_tokens['domain'])) {
280 $value = "{domain.$token}";
282 elseif ($token == 'address') {
283 static $addressCache = array();
285 $cache_key = $html ?
'address-html' : 'address-text';
286 if (array_key_exists($cache_key, $addressCache)) {
287 return $addressCache[$cache_key];
291 // Construct the address token
293 if (!empty($loc[$token])) {
295 $value = $loc[$token][1]['display'];
296 $value = str_replace("\n", '<br />', $value);
299 $value = $loc[$token][1]['display_text'];
301 $addressCache[$cache_key] = $value;
304 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
305 $value = $domain->$token;
307 elseif ($token == 'phone' ||
$token == 'email') {
308 // Construct the phone and email tokens
311 if (!empty($loc[$token])) {
312 foreach ($loc[$token] as $index => $entity) {
313 $value = $entity[$token];
320 $value = self
::tokenEscapeSmarty($value);
327 * Replace all the org-level tokens in $str
330 * The string with tokens to be replaced.
332 * Associative array of org properties.
334 * Replace tokens with HTML or plain text.
336 * @param bool $escapeSmarty
339 * The processed string
341 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
342 self
::$_tokens['org']
344 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
345 array('address', 'display_name', 'checksum', 'contact_id')
349 foreach (self
::$_tokens['org'] as $token) {
350 // print "Getting token value for $token<br/><br/>";
355 // If the string doesn't contain this token, skip it.
357 if (!self
::token_match('org', $token, $str)) {
361 // Construct value from $token and $contact
365 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
366 // only generate cv if we need it
368 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
370 foreach ($cv as $cvFieldID => $value) {
371 if ($cvFieldID == $cfID) {
372 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
377 elseif ($token == 'checksum') {
378 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
381 elseif ($token == 'address') {
382 // Build the location values array
385 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
386 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
387 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
388 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
389 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
391 // Construct the address token
393 $value = CRM_Utils_Address
::format($loc);
395 $value = str_replace("\n", '<br />', $value);
399 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
402 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
409 * Replace all mailing tokens in $str
412 * The string with tokens to be replaced.
413 * @param object $mailing
414 * The mailing BAO, or null for validation.
416 * Replace tokens with HTML or plain text.
418 * @param null $knownTokens
419 * @param bool $escapeSmarty
422 * The processed string
424 public static function &replaceMailingTokens(
429 $escapeSmarty = FALSE
432 if (!$knownTokens ||
!isset($knownTokens[$key])) {
436 $str = preg_replace_callback(
437 self
::tokenRegex($key),
438 function ($matches) use (&$mailing, $escapeSmarty) {
439 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
449 * @param bool $escapeSmarty
453 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
459 $value = $mailing ?
$mailing->id
: 'undefined';
463 $value = $mailing ?
$mailing->name
: 'Mailing Name';
467 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
468 $value = implode(', ', $groups);
472 $value = $mailing->subject
;
476 $mailingKey = $mailing->id
;
477 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
480 $value = CRM_Utils_System
::url('civicrm/mailing/view',
481 "reset=1&id={$mailingKey}",
482 TRUE, NULL, FALSE, TRUE
488 // Note: editUrl and scheduleUrl used to be different, but now there's
489 // one screen which can adapt based on permissions (in workflow mode).
490 $value = CRM_Utils_System
::url('civicrm/mailing/send',
491 "reset=1&mid={$mailing->id}&continue=true",
492 TRUE, NULL, FALSE, TRUE
497 $page = new CRM_Mailing_Page_View();
498 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
501 case 'approvalStatus':
502 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
506 $value = $mailing->approval_note
;
510 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
511 "reset=1&mid={$mailing->id}",
512 TRUE, NULL, FALSE, TRUE
517 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
521 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
525 $value = "{mailing.$token}";
530 $value = self
::tokenEscapeSmarty($value);
536 * Replace all action tokens in $str
539 * The string with tokens to be replaced.
540 * @param array $addresses
541 * Assoc. array of VERP event addresses.
543 * Assoc. array of action URLs.
545 * Replace tokens with HTML or plain text.
546 * @param array $knownTokens
547 * A list of tokens that are known to exist in the email body.
549 * @param bool $escapeSmarty
552 * The processed string
554 public static function &replaceActionTokens(
560 $escapeSmarty = FALSE
563 // here we intersect with the list of pre-configured valid tokens
564 // so that we remove anything we do not recognize
565 // I hope to move this step out of here soon and
566 // then we will just iterate on a list of tokens that are passed to us
567 if (!$knownTokens ||
empty($knownTokens[$key])) {
571 $str = preg_replace_callback(
572 self
::tokenRegex($key),
573 function ($matches) use (&$addresses, &$urls, $html, $escapeSmarty) {
574 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
586 * @param bool $escapeSmarty
588 * @return mixed|string
590 public static function getActionTokenReplacement(
595 $escapeSmarty = FALSE
597 // If the token is an email action, use it. Otherwise, find the
600 if (!in_array($token, self
::$_tokens['action'])) {
601 $value = "{action.$token}";
604 $value = CRM_Utils_Array
::value($token, $addresses);
606 if ($value == NULL) {
607 $value = CRM_Utils_Array
::value($token, $urls);
610 if ($value && $html) {
612 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
613 $value = "mailto:$value";
616 elseif ($value && !$html) {
617 $value = str_replace('&', '&', $value);
622 $value = self
::tokenEscapeSmarty($value);
628 * Replace all the contact-level tokens in $str with information from
632 * The string with tokens to be replaced.
633 * @param array $contact
634 * Associative array of contact properties.
636 * Replace tokens with HTML or plain text.
637 * @param array $knownTokens
638 * A list of tokens that are known to exist in the email body.
639 * @param bool $returnBlankToken
640 * Return unevaluated token if value is null.
642 * @param bool $escapeSmarty
645 * The processed string
647 public static function &replaceContactTokens(
652 $returnBlankToken = FALSE,
653 $escapeSmarty = FALSE
656 if (self
::$_tokens[$key] == NULL) {
657 // This should come from UF
661 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
662 array('checksum', 'contact_id')
666 // here we intersect with the list of pre-configured valid tokens
667 // so that we remove anything we do not recognize
668 // I hope to move this step out of here soon and
669 // then we will just iterate on a list of tokens that are passed to us
670 if (!$knownTokens ||
empty($knownTokens[$key])) {
674 $str = preg_replace_callback(
675 self
::tokenRegex($key),
676 function ($matches) use (&$contact, $html, $returnBlankToken, $escapeSmarty) {
677 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
682 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
690 * @param bool $returnBlankToken
691 * @param bool $escapeSmarty
693 * @return bool|mixed|null|string
695 public static function getContactTokenReplacement(
699 $returnBlankToken = FALSE,
700 $escapeSmarty = FALSE
702 if (self
::$_tokens['contact'] == NULL) {
703 /* This should come from UF */
705 self
::$_tokens['contact']
707 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
708 array('checksum', 'contact_id')
712 // Construct value from $token and $contact
717 // Support legacy tokens
718 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
720 // check if the token we were passed is valid
721 // we have to do this because this function is
722 // called only when we find a token in the string
724 if (!in_array($token, self
::$_tokens['contact'])) {
727 elseif ($token == 'checksum') {
728 $hash = CRM_Utils_Array
::value('hash', $contact);
729 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
730 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
738 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
740 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
741 if (is_array($value)) {
744 // Convert pseudoconstants using metadata
745 elseif ($value && is_numeric($value)) {
746 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
747 if (!empty($allFields[$token]['pseudoconstant'])) {
748 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
754 $value = str_replace('&', '&', $value);
757 // if null then return actual token
758 if ($returnBlankToken && !$value) {
763 $value = "{contact.$token}";
767 && !($returnBlankToken && $noReplace)
769 // $returnBlankToken means the caller wants to do further attempts at
770 // processing unreplaced tokens -- so don't escape them yet in this case.
771 $value = self
::tokenEscapeSmarty($value);
778 * Replace all the hook tokens in $str with information from
782 * The string with tokens to be replaced.
783 * @param array $contact
784 * Associative array of contact properties (including hook token values).
787 * Replace tokens with HTML or plain text.
789 * @param bool $escapeSmarty
792 * The processed string
794 public static function &replaceHookTokens(
799 $escapeSmarty = FALSE
801 foreach ($categories as $key) {
802 $str = preg_replace_callback(
803 self
::tokenRegex($key),
804 function ($matches) use (&$contact, $key, $html, $escapeSmarty) {
805 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
814 * Parse html through Smarty resolving any smarty functions.
815 * @param string $tokenHtml
816 * @param array $entity
817 * @param string $entityType
819 * html parsed through smarty
821 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
822 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
823 $smarty = CRM_Core_Smarty
::singleton();
824 // also add the tokens to the template
825 $smarty->assign_by_ref($entityType, $entity);
826 $tokenHtml = $smarty->fetch("string:$tokenHtml");
836 * @param bool $escapeSmarty
838 * @return mixed|string
840 public static function getHookTokenReplacement(
845 $escapeSmarty = FALSE
847 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
849 if ($value && !$html) {
850 $value = str_replace('&', '&', $value);
854 $value = self
::tokenEscapeSmarty($value);
861 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
862 * for example {{token}} or \{token} will result in {token} in the final email
864 * this routine will remove the extra backslashes and braces
866 * @param $str ref to the string that will be scanned and modified
868 public static function unescapeTokens(&$str) {
869 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
873 * Replace unsubscribe tokens.
876 * The string with tokens to be replaced.
877 * @param object $domain
879 * @param array $groups
880 * The groups (if any) being unsubscribed.
882 * Replace tokens with html or plain text.
883 * @param int $contact_id
885 * @param string $hash The security hash of the unsub event
888 * The processed string
890 public static function &replaceUnsubscribeTokens(
898 if (self
::token_match('unsubscribe', 'group', $str)) {
899 if (!empty($groups)) {
900 $config = CRM_Core_Config
::singleton();
901 $base = CRM_Utils_System
::baseURL();
903 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
904 $dao = new CRM_Contact_DAO_Group();
906 while ($dao->fetch()) {
907 if (substr($dao->visibility
, 0, 6) == 'Public') {
908 $visibleGroups[] = $dao->id
;
911 $value = implode(', ', $groups);
912 self
::token_replace('unsubscribe', 'group', $value, $str);
919 * Replace resubscribe tokens.
922 * The string with tokens to be replaced.
923 * @param object $domain
925 * @param array $groups
926 * The groups (if any) being resubscribed.
928 * Replace tokens with html or plain text.
929 * @param int $contact_id
931 * @param string $hash The security hash of the resub event
934 * The processed string
936 public static function &replaceResubscribeTokens(
937 $str, &$domain, &$groups, $html,
940 if (self
::token_match('resubscribe', 'group', $str)) {
941 if (!empty($groups)) {
942 $value = implode(', ', $groups);
943 self
::token_replace('resubscribe', 'group', $value, $str);
950 * Replace subscription-confirmation-request tokens
953 * The string with tokens to be replaced.
954 * @param string $group
955 * The name of the group being subscribed.
958 * Replace tokens with html or plain text.
961 * The processed string
963 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
964 if (self
::token_match('subscribe', 'group', $str)) {
965 self
::token_replace('subscribe', 'group', $group, $str);
967 if (self
::token_match('subscribe', 'url', $str)) {
968 self
::token_replace('subscribe', 'url', $url, $str);
974 * Replace subscription-invitation tokens
977 * The string with tokens to be replaced.
980 * The processed string
982 public static function &replaceSubscribeInviteTokens($str) {
983 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
984 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
986 TRUE, NULL, TRUE, TRUE
988 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
991 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
992 foreach ($matches as $key => $value) {
993 $gid = substr($value, 21, -1);
994 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
995 "reset=1&gid={$gid}",
996 TRUE, NULL, TRUE, TRUE
998 $url = str_replace('&', '&', $url);
999 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
1003 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
1004 foreach ($matches as $key => $value) {
1005 $gid = substr($value, 18, -1);
1006 $config = CRM_Core_Config
::singleton();
1007 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
1008 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1009 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1010 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1017 * Replace welcome/confirmation tokens
1019 * @param string $str
1020 * The string with tokens to be replaced.
1021 * @param string $group
1022 * The name of the group being subscribed.
1024 * Replace tokens with html or plain text.
1027 * The processed string
1029 public static function &replaceWelcomeTokens($str, $group, $html) {
1030 if (self
::token_match('welcome', 'group', $str)) {
1031 self
::token_replace('welcome', 'group', $group, $str);
1037 * Find unprocessed tokens (call this last)
1039 * @param string $str
1040 * The string to search.
1043 * Array of tokens that weren't replaced
1045 public static function &unmatchedTokens(&$str) {
1046 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1047 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1052 * Find and replace tokens for each component.
1054 * @param string $str
1055 * The string to search.
1056 * @param array $contact
1057 * Associative array of contact properties.
1058 * @param array $components
1059 * A list of tokens that are known to exist in the email body.
1061 * @param bool $escapeSmarty
1062 * @param bool $returnEmptyToken
1065 * The processed string
1067 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1068 if (!is_array($components) ||
empty($contact)) {
1072 foreach ($components as $name => $tokens) {
1073 if (!is_array($tokens) ||
empty($tokens)) {
1077 foreach ($tokens as $token) {
1078 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1079 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1081 elseif (!$returnEmptyToken) {
1082 //replacing empty token
1083 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1091 * Get array of string tokens.
1093 * @param string $string
1094 * The input string to parse for tokens.
1097 * array of tokens mentioned in field
1099 public static function getTokens($string) {
1102 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1109 foreach ($matches[1] as $token) {
1110 list($type, $name) = preg_split('/\./', $token, 2);
1111 if ($name && $type) {
1112 if (!isset($tokens[$type])) {
1113 $tokens[$type] = array();
1115 $tokens[$type][] = $name;
1123 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1124 * and getTokens appears to be historical rather than intentional and should be reviewed
1127 * fields to pass in as return properties when populating token
1129 public static function getReturnProperties(&$string) {
1130 $returnProperties = array();
1132 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1138 foreach ($matches[1] as $token) {
1139 list($type, $name) = preg_split('/\./', $token, 2);
1141 $returnProperties["{$name}"] = 1;
1146 return $returnProperties;
1150 * Gives required details of contacts in an indexed array format so we
1151 * can iterate in a nice loop and do token evaluation
1153 * @param $contactIDs
1154 * @param array $returnProperties
1155 * Of required properties.
1156 * @param bool $skipOnHold Don't return on_hold contact info also.
1157 * Don't return on_hold contact info also.
1158 * @param bool $skipDeceased Don't return deceased contact info.
1159 * Don't return deceased contact info.
1160 * @param array $extraParams
1162 * @param array $tokens
1163 * The list of tokens we've extracted from the content.
1164 * @param null $className
1166 * The mailing list jobID - this is a legacy param.
1170 public static function getTokenDetails(
1172 $returnProperties = NULL,
1174 $skipDeceased = TRUE,
1175 $extraParams = NULL,
1180 if (empty($contactIDs)) {
1181 // putting a fatal here so we can track if/when this happens
1182 CRM_Core_Error
::fatal();
1184 // @todo this functions needs unit tests.
1186 foreach ($contactIDs as $key => $contactID) {
1188 CRM_Core_Form
::CB_PREFIX
. $contactID,
1197 if ($skipDeceased) {
1198 $params[] = array('is_deceased', '=', 0, 0, 0);
1203 $params[] = array('on_hold', '=', 0, 0, 0);
1207 $params = array_merge($params, $extraParams);
1210 // if return properties are not passed then get all return properties
1211 if (empty($returnProperties)) {
1212 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1213 array('display_name', 'checksum', 'contact_id')
1215 foreach ($fields as $key => $val) {
1216 // The unavailable fields are not available as tokens, do not have a one-2-one relationship
1217 // with contacts and are expensive to resolve.
1218 // @todo see CRM-17253 - there are some other fields (e.g note) that should be excluded
1219 // and upstream calls to this should populate return properties.
1220 $unavailableFields = array('group', 'tag');
1221 if (!in_array($val, $unavailableFields)) {
1222 $returnProperties[$val] = 1;
1228 foreach ($returnProperties as $name => $dontCare) {
1229 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1235 //get the total number of contacts to fetch from database.
1236 $numberofContacts = count($contactIDs);
1237 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1239 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1241 $contactDetails = &$details[0];
1243 foreach ($contactIDs as $key => $contactID) {
1244 if (array_key_exists($contactID, $contactDetails)) {
1245 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1246 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1248 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1250 // communication Preference
1251 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1252 $contactDetails[$contactID]['preferred_communication_method']
1255 foreach ($contactPcm as $key => $val) {
1257 $result[$val] = $pcm[$val];
1260 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1263 foreach ($custom as $cfID) {
1264 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1265 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1271 // special case for greeting replacement
1277 if (!empty($contactDetails[$contactID][$val])) {
1278 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1284 // also call a hook and get token details
1285 CRM_Utils_Hook
::tokenValues($details[0],
1295 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1296 * specific tokens to be rendered
1298 * @param array $contactIDs
1299 * This should always be array(0) or its not anonymous - left to keep signature same.
1301 * @param string $returnProperties
1302 * @param bool $skipOnHold
1303 * @param bool $skipDeceased
1304 * @param string $extraParams
1305 * @param array $tokens
1306 * @param string $className
1307 * Sent as context to the hook.
1308 * @param string $jobID
1310 * contactDetails with hooks swapped out
1312 public function getAnonymousTokenDetails($contactIDs = array(
1315 $returnProperties = NULL,
1317 $skipDeceased = TRUE,
1318 $extraParams = NULL,
1322 $details = array(0 => array());
1323 // also call a hook and get token details
1324 CRM_Utils_Hook
::tokenValues($details[0],
1334 * Gives required details of contribuion in an indexed array format so we
1335 * can iterate in a nice loop and do token evaluation
1337 * @param array $contributionIDs
1338 * @param array $returnProperties
1339 * Of required properties.
1340 * @param array $extraParams
1342 * @param array $tokens
1343 * The list of tokens we've extracted from the content.
1344 * @param string $className
1348 public static function getContributionTokenDetails(
1350 $returnProperties = NULL,
1351 $extraParams = NULL,
1355 // @todo this function basically replicates calling
1356 // civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1357 if (empty($contributionIDs)) {
1358 // putting a fatal here so we can track if/when this happens
1359 CRM_Core_Error
::fatal();
1364 // no apiQuery helper yet, so do a loop and find contribution by id
1365 foreach ($contributionIDs as $contributionID) {
1367 $dao = new CRM_Contribute_DAO_Contribution();
1368 $dao->id
= $contributionID;
1370 if ($dao->find(TRUE)) {
1372 $details[$dao->id
] = array();
1373 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1375 // do the necessary transformation
1376 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1377 $piId = $details[$dao->id
]['payment_instrument_id'];
1378 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1379 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1381 if (!empty($details[$dao->id
]['campaign_id'])) {
1382 $campaignId = $details[$dao->id
]['campaign_id'];
1383 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1384 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1387 if (!empty($details[$dao->id
]['financial_type_id'])) {
1388 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1389 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1390 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1393 // @todo call a hook to get token contribution details
1401 * Get Membership Token Details.
1402 * @param array $membershipIDs
1403 * Array of membership IDS.
1405 public static function getMembershipTokenDetails($membershipIDs) {
1406 $memberships = civicrm_api3('membership', 'get', array(
1407 'options' => array('limit' => 200000),
1408 'membership_id' => array('IN' => (array) $membershipIDs),
1410 return $memberships['values'];
1414 * Replace existing greeting tokens in message/subject.
1416 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1418 if (!$contactDetails && !$contactId) {
1422 // check if there are any tokens
1423 $greetingTokens = self
::getTokens($tokenString);
1425 if (!empty($greetingTokens)) {
1426 // first use the existing contact object for token replacement
1427 if (!empty($contactDetails)) {
1428 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1431 // check if there are any unevaluated tokens
1432 $greetingTokens = self
::getTokens($tokenString);
1434 // $greetingTokens not empty, means there are few tokens which are not
1435 // evaluated, like custom data etc
1436 // so retrieve it from database
1437 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1438 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1439 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1440 $contactParams = array('contact_id' => $contactId);
1442 $greetingDetails = self
::getTokenDetails($contactParams,
1443 $greetingsReturnProperties,
1449 // again replace tokens
1450 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1459 // check if there are still any unevaluated tokens
1460 $remainingTokens = self
::getTokens($tokenString);
1462 // $greetingTokens not empty, there are customized or hook tokens to replace
1463 if (!empty($remainingTokens)) {
1464 // Fill the return properties array
1465 $greetingTokens = $remainingTokens;
1466 reset($greetingTokens);
1467 $greetingsReturnProperties = array();
1468 while (list($key) = each($greetingTokens)) {
1469 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1470 $props = array_fill_keys(array_keys($props), 1);
1471 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1473 $contactParams = array('contact_id' => $contactId);
1474 $greetingDetails = self
::getTokenDetails($contactParams,
1475 $greetingsReturnProperties,
1480 // Prepare variables for calling replaceHookTokens
1481 $categories = array_keys($greetingTokens);
1482 list($contact) = $greetingDetails;
1483 // Replace tokens defined in Hooks.
1484 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1494 public static function flattenTokens(&$tokens) {
1495 $flattenTokens = array();
1502 if (!isset($tokens[$prop])) {
1505 foreach ($tokens[$prop] as $type => $names) {
1506 if (!isset($flattenTokens[$type])) {
1507 $flattenTokens[$type] = array();
1509 foreach ($names as $name) {
1510 $flattenTokens[$type][$name] = 1;
1515 return $flattenTokens;
1519 * Replace all user tokens in $str
1521 * @param string $str
1522 * The string with tokens to be replaced.
1524 * @param null $knownTokens
1525 * @param bool $escapeSmarty
1528 * The processed string
1530 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1532 if (!$knownTokens ||
1533 !isset($knownTokens[$key])
1538 $str = preg_replace_callback(
1539 self
::tokenRegex($key),
1540 function ($matches) use ($escapeSmarty) {
1541 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1550 * @param bool $escapeSmarty
1554 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1557 list($objectName, $objectValue) = explode('-', $token, 2);
1559 switch ($objectName) {
1561 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1565 $value = CRM_Core_Permission
::roleEmails($objectValue);
1569 if ($escapeSmarty) {
1570 $value = self
::tokenEscapeSmarty($value);
1576 protected static function _buildContributionTokens() {
1577 $key = 'contribution';
1578 if (self
::$_tokens[$key] == NULL) {
1579 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1580 array('campaign', 'financial_type')
1586 * Store membership tokens on the static _tokens array.
1588 protected static function _buildMembershipTokens() {
1589 $key = 'membership';
1590 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1591 $membershipTokens = array();
1592 $tokens = CRM_Core_SelectValues
::membershipTokens();
1593 foreach ($tokens as $token => $dontCare) {
1594 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1596 self
::$_tokens[$key] = $membershipTokens;
1601 * Replace tokens for an entity.
1602 * @param string $entity
1603 * @param array $entityArray
1604 * (e.g. in format from api).
1605 * @param string $str
1606 * String to replace in.
1607 * @param array $knownTokens
1608 * Array of tokens present.
1609 * @param bool $escapeSmarty
1611 * string with replacements made
1613 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1614 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1618 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1619 // since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1620 foreach ($knownTokens[$entity] as $token) {
1621 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1622 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1624 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1629 * Replace Contribution tokens in html.
1631 * @param string $str
1632 * @param array $contribution
1633 * @param bool|string $html
1634 * @param string $knownTokens
1635 * @param bool|string $escapeSmarty
1639 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1640 $key = 'contribution';
1641 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1642 return $str; //early return
1644 self
::_buildContributionTokens();
1646 // here we intersect with the list of pre-configured valid tokens
1647 // so that we remove anything we do not recognize
1648 // I hope to move this step out of here soon and
1649 // then we will just iterate on a list of tokens that are passed to us
1651 $str = preg_replace_callback(
1652 self
::tokenRegex($key),
1653 function ($matches) use (&$contribution, $html, $escapeSmarty) {
1654 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1659 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1664 * We have a situation where we are rendering more than one token in each field because we are combining
1665 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1667 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1668 * it applies (other tokens are OK including date fields)
1670 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1671 * does - but the fields is already being formatted through a date function
1673 * @param string $separator
1674 * @param string $str
1675 * @param array $contribution
1676 * @param bool|string $html
1677 * @param string $knownTokens
1678 * @param bool|string $escapeSmarty
1680 * @return \Ambigous|mixed|string|\unknown
1682 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1683 if (empty($knownTokens['contribution'])) {
1687 if (in_array('receive_date', $knownTokens['contribution'])) {
1688 $formattedDates = array();
1689 $dates = explode($separator, $contribution['receive_date']);
1690 foreach ($dates as $date) {
1691 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1693 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1694 unset($knownTokens['contribution']['receive_date']);
1696 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1700 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1701 * - this is used by the pdfLetter task from membership search
1702 * @param string $token
1703 * @param array $membership
1704 * An api result array for a single membership.
1705 * @param bool $escapeSmarty
1709 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1710 $entity = 'membership';
1711 self
::_buildMembershipTokens();
1714 $value = $membership['membership_name'];
1718 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1719 $value = $statuses[$membership['status_id']];
1724 $value = civicrm_api3('membership_type', 'getvalue', array(
1725 'id' => $membership['membership_type_id'],
1726 'return' => 'minimum_fee',
1729 catch (CiviCRM_API3_Exception
$e) {
1730 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1731 // api handles NULL (4.4)
1737 if (in_array($token, self
::$_tokens[$entity])) {
1738 $value = $membership[$token];
1742 $value = "{$entity}.{$token}";
1747 if ($escapeSmarty) {
1748 $value = self
::tokenEscapeSmarty($value);
1755 * @param $contribution
1757 * @param bool $escapeSmarty
1759 * @return mixed|string
1761 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1762 self
::_buildContributionTokens();
1765 case 'total_amount':
1768 case 'non_deductible_amount':
1769 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1772 case 'receive_date':
1773 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1774 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1778 if (!in_array($token, self
::$_tokens['contribution'])) {
1779 $value = "{contribution.$token}";
1782 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1787 if ($escapeSmarty) {
1788 $value = self
::tokenEscapeSmarty($value);
1795 * legacy_token => new_token
1797 public static function legacyContactTokens() {
1799 'individual_prefix' => 'prefix_id',
1800 'individual_suffix' => 'suffix_id',
1801 'gender' => 'gender_id',
1802 'communication_style' => 'communication_style_id',
1807 * Formats a token list for the select2 widget
1812 public static function formatTokensForDisplay($tokens) {
1813 $sorted = $output = array();
1815 // Sort in ascending order by ignoring word case
1816 natcasesort($tokens);
1818 // Attempt to place tokens into optgroups
1819 // @todo These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1820 foreach ($tokens as $k => $v) {
1821 // Check to see if this token is already in a group e.g. for custom fields
1822 $split = explode(' :: ', $v);
1823 if (!empty($split[1])) {
1824 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1828 $split = explode('.', trim($k, '{}'));
1829 if (isset($split[1])) {
1830 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1833 $entity = 'Contact';
1835 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1840 foreach ($sorted as $k => $v) {
1841 $output[] = array('text' => $k, 'children' => $v);