3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
37 * Class to abstract token replacement
39 class CRM_Utils_Token
{
40 static $_requiredTokens = NULL;
42 static $_tokens = array(
69 // we extract the stuff after the role / permission and return the
70 // civicrm email addresses of all users with that role / permission
71 // useful with rules integration
75 // populate this dynamically
77 // populate this dynamically
78 'contribution' => NULL,
87 'subscribe' => array('group'),
88 'unsubscribe' => array('group'),
89 'resubscribe' => array('group'),
90 'welcome' => array('group'),
94 * Check a string (mailing body) for required tokens.
99 * @return true|array true if all required tokens are found,
100 * else an array of the missing tokens
103 public static function requiredTokens(&$str) {
104 if (self
::$_requiredTokens == NULL) {
105 self
::$_requiredTokens = array(
106 'domain.address' => ts("Domain address - displays your organization's postal address."),
107 'action.optOutUrl or action.unsubscribeUrl' => array(
108 'action.optOut' => ts("'Opt out via email' - displays an email address for recipients to opt out of receiving emails from your organization."),
109 '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."),
110 'action.unsubscribe' => ts("'Unsubscribe via email' - displays an email address for recipients to unsubscribe from the specific mailing list used to send this message."),
111 '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."),
117 foreach (self
::$_requiredTokens as $token => $value) {
118 if (!is_array($value)) {
119 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
120 $missing[$token] = $value;
126 foreach ($value as $t => $d) {
128 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
133 $missing[$token] = $desc;
138 if (empty($missing)) {
145 * Wrapper for token matching
147 * @param string $type
148 * The token type (domain,mailing,contact,action).
150 * The token variable.
152 * The string to search.
158 public static function token_match($type, $var, &$str) {
159 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
160 return preg_match("/(^|[^\{])$token/", $str);
164 * Wrapper for token replacing
166 * @param string $type
169 * The token variable.
170 * @param string $value
171 * The value to substitute for the token.
172 * @param string (reference) $str The string to replace in
174 * @param bool $escapeSmarty
177 * The processed string
180 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
181 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
186 $value = self
::tokenEscapeSmarty($value);
188 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
193 * Get< the regex for token replacement
195 * @param string $token_type
196 * A string indicating the the type of token to be used in the expression.
199 * regular expression sutiable for using in preg_replace
202 private static function tokenRegex($token_type) {
203 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
207 * Escape the string so a malicious user cannot inject smarty code into the template
209 * @param string $string
210 * A string that needs to be escaped from smarty parsing.
216 private static function tokenEscapeSmarty($string) {
217 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
218 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
222 * Replace all the domain-level tokens in $str
225 * The string with tokens to be replaced.
226 * @param object $domain
229 * Replace tokens with HTML or plain text.
231 * @param null $knownTokens
232 * @param bool $escapeSmarty
235 * The processed string
238 public static function &replaceDomainTokens(
243 $escapeSmarty = FALSE
247 !$knownTokens ||
empty($knownTokens[$key])
252 $str = preg_replace_callback(
253 self
::tokenRegex($key),
254 function ($matches) use (&$domain, $html, $escapeSmarty) {
255 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
266 * @param bool $escapeSmarty
268 * @return mixed|null|string
270 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
271 // check if the token we were passed is valid
272 // we have to do this because this function is
273 // called only when we find a token in the string
275 $loc = &$domain->getLocationValues();
277 if (!in_array($token, self
::$_tokens['domain'])) {
278 $value = "{domain.$token}";
280 elseif ($token == 'address') {
281 static $addressCache = array();
283 $cache_key = $html ?
'address-html' : 'address-text';
284 if (array_key_exists($cache_key, $addressCache)) {
285 return $addressCache[$cache_key];
289 /* Construct the address token */
291 if (!empty($loc[$token])) {
293 $value = $loc[$token][1]['display'];
294 $value = str_replace("\n", '<br />', $value);
297 $value = $loc[$token][1]['display_text'];
299 $addressCache[$cache_key] = $value;
302 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
303 $value = $domain->$token;
305 elseif ($token == 'phone' ||
$token == 'email') {
306 /* Construct the phone and email tokens */
309 if (!empty($loc[$token])) {
310 foreach ($loc[$token] as $index => $entity) {
311 $value = $entity[$token];
318 $value = self
::tokenEscapeSmarty($value);
325 * Replace all the org-level tokens in $str
328 * The string with tokens to be replaced.
330 * Associative array of org properties.
332 * Replace tokens with HTML or plain text.
334 * @param bool $escapeSmarty
337 * The processed string
340 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
341 self
::$_tokens['org'] =
343 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
344 array('address', 'display_name', 'checksum', 'contact_id')
348 foreach (self
::$_tokens['org'] as $token) {
349 // print "Getting token value for $token<br/><br/>";
354 /* If the string doesn't contain this token, skip it. */
356 if (!self
::token_match('org', $token, $str)) {
360 /* Construct value from $token and $contact */
364 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
365 // only generate cv if we need it
367 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
369 foreach ($cv as $cvFieldID => $value) {
370 if ($cvFieldID == $cfID) {
371 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
376 elseif ($token == 'checksum') {
377 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
380 elseif ($token == 'address') {
381 /* Build the location values array */
384 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
385 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
386 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
387 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
388 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
390 /* Construct the address token */
392 $value = CRM_Utils_Address
::format($loc);
394 $value = str_replace("\n", '<br />', $value);
398 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
401 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
408 * Replace all mailing tokens in $str
411 * The string with tokens to be replaced.
412 * @param object $mailing
413 * The mailing BAO, or null for validation.
415 * Replace tokens with HTML or plain text.
417 * @param null $knownTokens
418 * @param bool $escapeSmarty
421 * The processed sstring
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
487 $value = CRM_Utils_System
::url('civicrm/mailing/send',
488 "reset=1&mid={$mailing->id}&continue=true",
489 TRUE, NULL, FALSE, TRUE
494 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
495 "reset=1&mid={$mailing->id}",
496 TRUE, NULL, FALSE, TRUE
501 $page = new CRM_Mailing_Page_View();
502 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
505 case 'approvalStatus':
506 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
510 $value = $mailing->approval_note
;
514 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
515 "reset=1&mid={$mailing->id}",
516 TRUE, NULL, FALSE, TRUE
521 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
525 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
529 $value = "{mailing.$token}";
534 $value = self
::tokenEscapeSmarty($value);
540 * Replace all action tokens in $str
543 * The string with tokens to be replaced.
544 * @param array $addresses
545 * Assoc. array of VERP event addresses.
547 * Assoc. array of action URLs.
549 * Replace tokens with HTML or plain text.
550 * @param array $knownTokens
551 * A list of tokens that are known to exist in the email body.
553 * @param bool $escapeSmarty
556 * The processed string
559 public static function &replaceActionTokens(
565 $escapeSmarty = FALSE
568 // here we intersect with the list of pre-configured valid tokens
569 // so that we remove anything we do not recognize
570 // I hope to move this step out of here soon and
571 // then we will just iterate on a list of tokens that are passed to us
572 if (!$knownTokens ||
empty($knownTokens[$key])) {
576 $str = preg_replace_callback(
577 self
::tokenRegex($key),
578 function ($matches) use (&$addresses, &$urls, $html, $escapeSmarty) {
579 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
591 * @param bool $escapeSmarty
593 * @return mixed|string
595 public static function getActionTokenReplacement(
600 $escapeSmarty = FALSE
602 /* If the token is an email action, use it. Otherwise, find the
605 if (!in_array($token, self
::$_tokens['action'])) {
606 $value = "{action.$token}";
609 $value = CRM_Utils_Array
::value($token, $addresses);
611 if ($value == NULL) {
612 $value = CRM_Utils_Array
::value($token, $urls);
615 if ($value && $html) {
617 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
618 $value = "mailto:$value";
621 elseif ($value && !$html) {
622 $value = str_replace('&', '&', $value);
627 $value = self
::tokenEscapeSmarty($value);
633 * Replace all the contact-level tokens in $str with information from
637 * The string with tokens to be replaced.
638 * @param array $contact
639 * Associative array of contact properties.
641 * Replace tokens with HTML or plain text.
642 * @param array $knownTokens
643 * A list of tokens that are known to exist in the email body.
644 * @param bool $returnBlankToken
645 * Return unevaluated token if value is null.
647 * @param bool $escapeSmarty
650 * The processed string
653 public static function &replaceContactTokens(
658 $returnBlankToken = FALSE,
659 $escapeSmarty = FALSE
662 if (self
::$_tokens[$key] == NULL) {
663 /* This should come from UF */
665 self
::$_tokens[$key] =
667 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
668 array('checksum', 'contact_id')
672 // here we intersect with the list of pre-configured valid tokens
673 // so that we remove anything we do not recognize
674 // I hope to move this step out of here soon and
675 // then we will just iterate on a list of tokens that are passed to us
676 if (!$knownTokens ||
empty($knownTokens[$key])) {
680 $str = preg_replace_callback(
681 self
::tokenRegex($key),
682 function ($matches) use (&$contact, $html, $returnBlankToken, $escapeSmarty) {
683 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
688 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
696 * @param bool $returnBlankToken
697 * @param bool $escapeSmarty
699 * @return bool|mixed|null|string
701 public static function getContactTokenReplacement(
705 $returnBlankToken = FALSE,
706 $escapeSmarty = FALSE
708 if (self
::$_tokens['contact'] == NULL) {
709 /* This should come from UF */
711 self
::$_tokens['contact'] =
713 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
714 array('checksum', 'contact_id')
718 /* Construct value from $token and $contact */
723 // Support legacy tokens
724 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
726 // check if the token we were passed is valid
727 // we have to do this because this function is
728 // called only when we find a token in the string
730 if (!in_array($token, self
::$_tokens['contact'])) {
733 elseif ($token == 'checksum') {
734 $hash = CRM_Utils_Array
::value('hash', $contact);
735 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
736 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
744 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
746 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
747 if (is_array($value)) {
750 // Convert pseudoconstants using metadata
751 elseif ($value && is_numeric($value)) {
752 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
753 if (!empty($allFields[$token]['pseudoconstant'])) {
754 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
760 $value = str_replace('&', '&', $value);
763 // if null then return actual token
764 if ($returnBlankToken && !$value) {
769 $value = "{contact.$token}";
773 && !($returnBlankToken && $noReplace)
774 ) { // $returnBlankToken means the caller wants to do further attempts at processing unreplaced tokens -- so don't escape them yet in this case.
775 $value = self
::tokenEscapeSmarty($value);
782 * Replace all the hook tokens in $str with information from
786 * The string with tokens to be replaced.
787 * @param array $contact
788 * Associative array of contact properties (including hook token values).
791 * Replace tokens with HTML or plain text.
793 * @param bool $escapeSmarty
796 * The processed string
799 public static function &replaceHookTokens(
804 $escapeSmarty = FALSE
806 foreach ($categories as $key) {
807 $str = preg_replace_callback(
808 self
::tokenRegex($key),
809 function ($matches) use (&$contact, $key, $html, $escapeSmarty) {
810 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
819 * Parse html through Smarty resolving any smarty functions
820 * @param string $tokenHtml
821 * @param array $entity
822 * @param string $entityType
824 * html parsed through smarty
826 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
827 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
828 $smarty = CRM_Core_Smarty
::singleton();
829 // also add the tokens to the template
830 $smarty->assign_by_ref($entityType, $entity);
831 $tokenHtml = $smarty->fetch("string:$tokenHtml");
841 * @param bool $escapeSmarty
843 * @return mixed|string
845 public static function getHookTokenReplacement(
850 $escapeSmarty = FALSE
852 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
854 if ($value && !$html) {
855 $value = str_replace('&', '&', $value);
859 $value = self
::tokenEscapeSmarty($value);
866 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
867 * for example {{token}} or \{token} will result in {token} in the final email
869 * this routine will remove the extra backslashes and braces
871 * @param $str ref to the string that will be scanned and modified
873 * this function works directly on the string that is passed
877 public static function unescapeTokens(&$str) {
878 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
882 * Replace unsubscribe tokens
885 * The string with tokens to be replaced.
886 * @param object $domain
888 * @param array $groups
889 * The groups (if any) being unsubscribed.
891 * Replace tokens with html or plain text.
892 * @param int $contact_id
894 * @param string hash The security hash of the unsub event
897 * The processed string
900 public static function &replaceUnsubscribeTokens(
908 if (self
::token_match('unsubscribe', 'group', $str)) {
909 if (!empty($groups)) {
910 $config = CRM_Core_Config
::singleton();
911 $base = CRM_Utils_System
::baseURL();
913 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
914 $dao = new CRM_Contact_DAO_Group();
916 while ($dao->fetch()) {
917 if (substr($dao->visibility
, 0, 6) == 'Public') {
918 $visibleGroups[] = $dao->id
;
921 $value = implode(', ', $groups);
922 self
::token_replace('unsubscribe', 'group', $value, $str);
929 * Replace resubscribe tokens
932 * The string with tokens to be replaced.
933 * @param object $domain
935 * @param array $groups
936 * The groups (if any) being resubscribed.
938 * Replace tokens with html or plain text.
939 * @param int $contact_id
941 * @param string hash The security hash of the resub event
944 * 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
975 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
976 if (self
::token_match('subscribe', 'group', $str)) {
977 self
::token_replace('subscribe', 'group', $group, $str);
979 if (self
::token_match('subscribe', 'url', $str)) {
980 self
::token_replace('subscribe', 'url', $url, $str);
986 * Replace subscription-invitation tokens
989 * The string with tokens to be replaced.
992 * The processed string
995 public static function &replaceSubscribeInviteTokens($str) {
996 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
997 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
999 TRUE, NULL, TRUE, TRUE
1001 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
1004 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
1005 foreach ($matches as $key => $value) {
1006 $gid = substr($value, 21, -1);
1007 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
1008 "reset=1&gid={$gid}",
1009 TRUE, NULL, TRUE, TRUE
1011 $url = str_replace('&', '&', $url);
1012 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
1016 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
1017 foreach ($matches as $key => $value) {
1018 $gid = substr($value, 18, -1);
1019 $config = CRM_Core_Config
::singleton();
1020 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
1021 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1022 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1023 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1030 * Replace welcome/confirmation tokens
1032 * @param string $str
1033 * The string with tokens to be replaced.
1034 * @param string $group
1035 * The name of the group being subscribed.
1037 * Replace tokens with html or plain text.
1040 * The processed string
1043 public static function &replaceWelcomeTokens($str, $group, $html) {
1044 if (self
::token_match('welcome', 'group', $str)) {
1045 self
::token_replace('welcome', 'group', $group, $str);
1051 * Find unprocessed tokens (call this last)
1053 * @param string $str
1054 * The string to search.
1057 * Array of tokens that weren't replaced
1060 public static function &unmatchedTokens(&$str) {
1061 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1062 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1067 * Find and replace tokens for each component
1069 * @param string $str
1070 * The string to search.
1071 * @param array $contact
1072 * Associative array of contact properties.
1073 * @param array $components
1074 * A list of tokens that are known to exist in the email body.
1076 * @param bool $escapeSmarty
1077 * @param bool $returnEmptyToken
1080 * The processed string
1083 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1084 if (!is_array($components) ||
empty($contact)) {
1088 foreach ($components as $name => $tokens) {
1089 if (!is_array($tokens) ||
empty($tokens)) {
1093 foreach ($tokens as $token) {
1094 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1095 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1097 elseif (!$returnEmptyToken) {
1098 //replacing empty token
1099 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1107 * Get array of string tokens
1109 * @param string $string
1110 * The input string to parse for tokens.
1113 * array of tokens mentioned in field
1117 public static function getTokens($string) {
1120 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1127 foreach ($matches[1] as $token) {
1128 list($type, $name) = preg_split('/\./', $token, 2);
1129 if ($name && $type) {
1130 if (!isset($tokens[$type])) {
1131 $tokens[$type] = array();
1133 $tokens[$type][] = $name;
1141 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1142 * and getTokens appears to be historical rather than intentional and should be reviewed
1145 * fields to pass in as return properties when populating token
1147 public static function getReturnProperties(&$string) {
1148 $returnProperties = array();
1150 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1156 foreach ($matches[1] as $token) {
1157 list($type, $name) = preg_split('/\./', $token, 2);
1159 $returnProperties["{$name}"] = 1;
1164 return $returnProperties;
1168 * Gives required details of contacts in an indexed array format so we
1169 * can iterate in a nice loop and do token evaluation
1171 * @param $contactIDs
1172 * @param array $returnProperties
1173 * Of required properties.
1174 * @param bool $skipOnHoldDon 't return on_hold contact info also.
1175 * Don't return on_hold contact info also.
1176 * @param bool $skipDeceasedDon 't return deceased contact info.
1177 * Don't return deceased contact info.
1178 * @param array $extraParams
1180 * @param array $tokens
1181 * The list of tokens we've extracted from the content.
1182 * @param null $className
1184 * The mailing list jobID - this is a legacy param.
1189 static function getTokenDetails(
1191 $returnProperties = NULL,
1193 $skipDeceased = TRUE,
1194 $extraParams = NULL,
1199 if (empty($contactIDs)) {
1200 // putting a fatal here so we can track if/when this happens
1201 CRM_Core_Error
::fatal();
1205 foreach ($contactIDs as $key => $contactID) {
1207 CRM_Core_Form
::CB_PREFIX
. $contactID,
1216 if ($skipDeceased) {
1217 $params[] = array('is_deceased', '=', 0, 0, 0);
1222 $params[] = array('on_hold', '=', 0, 0, 0);
1226 $params = array_merge($params, $extraParams);
1229 // if return properties are not passed then get all return properties
1230 if (empty($returnProperties)) {
1231 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1232 array('display_name', 'checksum', 'contact_id')
1234 foreach ($fields as $key => $val) {
1235 $returnProperties[$val] = 1;
1240 foreach ($returnProperties as $name => $dontCare) {
1241 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1247 //get the total number of contacts to fetch from database.
1248 $numberofContacts = count($contactIDs);
1249 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1251 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1253 $contactDetails = &$details[0];
1255 foreach ($contactIDs as $key => $contactID) {
1256 if (array_key_exists($contactID, $contactDetails)) {
1257 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1258 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1260 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1262 // communication Prefferance
1263 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1264 $contactDetails[$contactID]['preferred_communication_method']
1267 foreach ($contactPcm as $key => $val) {
1269 $result[$val] = $pcm[$val];
1272 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1275 foreach ($custom as $cfID) {
1276 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1277 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1283 //special case for greeting replacement
1289 if (!empty($contactDetails[$contactID][$val])) {
1290 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1296 // also call a hook and get token details
1297 CRM_Utils_Hook
::tokenValues($details[0],
1307 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1308 * specific tokens to be rendered
1310 * @param array $contactIDs
1311 * This should always be array(0) or its not anonymous - left to keep signature same.
1313 * @param string $returnProperties
1314 * @param bool $skipOnHold
1315 * @param bool $skipDeceased
1316 * @param string $extraParams
1317 * @param array $tokens
1318 * @param string $className
1319 * Sent as context to the hook.
1320 * @param string $jobID
1322 * contactDetails with hooks swapped out
1324 public function getAnonymousTokenDetails($contactIDs = array(
1327 $returnProperties = NULL,
1329 $skipDeceased = TRUE,
1330 $extraParams = NULL,
1334 $details = array(0 => array());
1335 // also call a hook and get token details
1336 CRM_Utils_Hook
::tokenValues($details[0],
1346 * Gives required details of contribuion in an indexed array format so we
1347 * can iterate in a nice loop and do token evaluation
1349 * @param array $contributionIDs
1350 * @param array $returnProperties
1351 * Of required properties.
1352 * @param array $extraParams
1354 * @param array $tokens
1355 * The list of tokens we've extracted from the content.
1356 * @param string $className
1361 static function getContributionTokenDetails(
1363 $returnProperties = NULL,
1364 $extraParams = NULL,
1368 //@todo - this function basically replications calling civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1369 if (empty($contributionIDs)) {
1370 // putting a fatal here so we can track if/when this happens
1371 CRM_Core_Error
::fatal();
1376 // no apiQuery helper yet, so do a loop and find contribution by id
1377 foreach ($contributionIDs as $contributionID) {
1379 $dao = new CRM_Contribute_DAO_Contribution();
1380 $dao->id
= $contributionID;
1382 if ($dao->find(TRUE)) {
1384 $details[$dao->id
] = array();
1385 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1387 // do the necessary transformation
1388 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1389 $piId = $details[$dao->id
]['payment_instrument_id'];
1390 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1391 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1393 if (!empty($details[$dao->id
]['campaign_id'])) {
1394 $campaignId = $details[$dao->id
]['campaign_id'];
1395 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1396 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1399 if (!empty($details[$dao->id
]['financial_type_id'])) {
1400 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1401 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1402 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1405 // TODO: call a hook to get token contribution details
1413 * Get Membership Token Details
1414 * @param array $membershipIDs
1415 * Array of membership IDS.
1417 public static function getMembershipTokenDetails($membershipIDs) {
1418 $memberships = civicrm_api3('membership', 'get', array(
1419 'options' => array('limit' => 200000),
1420 'membership_id' => array('IN' => (array) $membershipIDs)
1422 return $memberships['values'];
1426 * Replace greeting tokens exists in message/subject
1428 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1430 if (!$contactDetails && !$contactId) {
1434 // check if there are any tokens
1435 $greetingTokens = self
::getTokens($tokenString);
1437 if (!empty($greetingTokens)) {
1438 // first use the existing contact object for token replacement
1439 if (!empty($contactDetails)) {
1440 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1443 // check if there are any unevaluated tokens
1444 $greetingTokens = self
::getTokens($tokenString);
1446 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1447 // so retrieve it from database
1448 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1449 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1450 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1451 $contactParams = array('contact_id' => $contactId);
1453 $greetingDetails = self
::getTokenDetails($contactParams,
1454 $greetingsReturnProperties,
1460 // again replace tokens
1461 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1470 // check if there are still any unevaluated tokens
1471 $remainingTokens = self
::getTokens($tokenString);
1473 // contact related $greetingTokens not empty, there are customized or hook tokens to replace
1474 if (!empty($remainingTokens['contact'])) {
1475 // Fill the return properties array
1476 $greetingTokens = $remainingTokens['contact'];
1477 reset($greetingTokens);
1478 $greetingsReturnProperties = array();
1479 while (list($key) = each($greetingTokens)) {
1480 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1481 $props = array_fill_keys(array_keys($props), 1);
1482 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1484 $contactParams = array('contact_id' => $contactId);
1485 $greetingDetails = self
::getTokenDetails($contactParams,
1486 $greetingsReturnProperties,
1491 // Prepare variables for calling replaceHookTokens
1492 $categories = array_keys($greetingTokens);
1493 list($contact) = $greetingDetails;
1494 // Replace tokens defined in Hooks.
1495 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1505 public static function flattenTokens(&$tokens) {
1506 $flattenTokens = array();
1513 if (!isset($tokens[$prop])) {
1516 foreach ($tokens[$prop] as $type => $names) {
1517 if (!isset($flattenTokens[$type])) {
1518 $flattenTokens[$type] = array();
1520 foreach ($names as $name) {
1521 $flattenTokens[$type][$name] = 1;
1526 return $flattenTokens;
1530 * Replace all user tokens in $str
1532 * @param string $str
1533 * The string with tokens to be replaced.
1535 * @param null $knownTokens
1536 * @param bool $escapeSmarty
1539 * The processed string
1542 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1544 if (!$knownTokens ||
1545 !isset($knownTokens[$key])
1550 $str = preg_replace_callback(
1551 self
::tokenRegex($key),
1552 function ($matches) use ($escapeSmarty) {
1553 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1562 * @param bool $escapeSmarty
1566 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1569 list($objectName, $objectValue) = explode('-', $token, 2);
1571 switch ($objectName) {
1573 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1577 $value = CRM_Core_Permission
::roleEmails($objectValue);
1581 if ($escapeSmarty) {
1582 $value = self
::tokenEscapeSmarty($value);
1590 protected static function _buildContributionTokens() {
1591 $key = 'contribution';
1592 if (self
::$_tokens[$key] == NULL) {
1593 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1594 array('campaign', 'financial_type')
1600 * Store membership tokens on the static _tokens array
1602 protected static function _buildMembershipTokens() {
1603 $key = 'membership';
1604 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1605 $membershipTokens = array();
1606 $tokens = CRM_Core_SelectValues
::membershipTokens();
1607 foreach ($tokens as $token => $dontCare) {
1608 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1610 self
::$_tokens[$key] = $membershipTokens;
1615 * Replace tokens for an entity
1616 * @param string $entity
1617 * @param array $entityArray
1618 * (e.g. in format from api).
1619 * @param string $str
1620 * String to replace in.
1621 * @param array $knownTokens
1622 * Array of tokens present.
1623 * @param bool $escapeSmarty
1625 * string with replacements made
1627 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1628 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1632 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1633 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1634 foreach ($knownTokens[$entity] as $token) {
1635 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1636 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1638 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1643 * Replace Contribution tokens in html
1645 * @param string $str
1646 * @param array $contribution
1647 * @param bool|string $html
1648 * @param string $knownTokens
1649 * @param bool|string $escapeSmarty
1651 * @return unknown|Ambigous <string, mixed>|mixed
1653 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1654 $key = 'contribution';
1655 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1656 return $str; //early return
1658 self
::_buildContributionTokens();
1660 // here we intersect with the list of pre-configured valid tokens
1661 // so that we remove anything we do not recognize
1662 // I hope to move this step out of here soon and
1663 // then we will just iterate on a list of tokens that are passed to us
1665 $str = preg_replace_callback(
1666 self
::tokenRegex($key),
1667 function ($matches) use (&$contribution, $html, $escapeSmarty) {
1668 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1673 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1678 * We have a situation where we are rendering more than one token in each field because we are combining
1679 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1681 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1682 * it applies (other tokens are OK including date fields)
1684 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1685 * does - but the fields is already being formatted through a date function
1687 * @param string $separator
1688 * @param string $str
1689 * @param array $contribution
1690 * @param bool|string $html
1691 * @param string $knownTokens
1692 * @param bool|string $escapeSmarty
1694 * @return \Ambigous|mixed|string|\unknown
1696 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1697 if (empty($knownTokens['contribution'])) {
1701 if (in_array('receive_date', $knownTokens['contribution'])) {
1702 $formattedDates = array();
1703 $dates = explode($separator, $contribution['receive_date']);
1704 foreach ($dates as $date) {
1705 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1707 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1708 unset($knownTokens['contribution']['receive_date']);
1710 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1714 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1715 * - this is used by the pdfLetter task from membership search
1716 * @param string $token
1717 * @param array $membership
1718 * An api result array for a single membership.
1719 * @param bool $escapeSmarty
1723 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1724 $entity = 'membership';
1725 self
::_buildMembershipTokens();
1728 $value = $membership['membership_name'];
1732 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1733 $value = $statuses[$membership['status_id']];
1738 $value = civicrm_api3('membership_type', 'getvalue', array(
1739 'id' => $membership['membership_type_id'],
1740 'return' => 'minimum_fee'
1743 catch (CiviCRM_API3_Exception
$e) {
1744 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1745 // api handles NULL (4.4)
1751 if (in_array($token, self
::$_tokens[$entity])) {
1752 $value = $membership[$token];
1756 $value = "{$entity}.{$token}";
1761 if ($escapeSmarty) {
1762 $value = self
::tokenEscapeSmarty($value);
1769 * @param $contribution
1771 * @param bool $escapeSmarty
1773 * @return mixed|string
1775 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1776 self
::_buildContributionTokens();
1779 case 'total_amount':
1782 case 'non_deductible_amount':
1783 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1786 case 'receive_date':
1787 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1788 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1792 if (!in_array($token, self
::$_tokens['contribution'])) {
1793 $value = "{contribution.$token}";
1796 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1801 if ($escapeSmarty) {
1802 $value = self
::tokenEscapeSmarty($value);
1809 * legacy_token => new_token
1811 public static function legacyContactTokens() {
1813 'individual_prefix' => 'prefix_id',
1814 'individual_suffix' => 'suffix_id',
1815 'gender' => 'gender_id',
1816 'communication_style' => 'communication_style_id',
1821 * Formats a token list for the select2 widget
1825 public static function formatTokensForDisplay($tokens) {
1826 $sorted = $output = array();
1828 // Sort in ascending order by ignoring word case
1829 natcasesort($tokens);
1831 // Attempt to place tokens into optgroups
1832 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1833 foreach ($tokens as $k => $v) {
1834 // Check to see if this token is already in a group e.g. for custom fields
1835 $split = explode(' :: ', $v);
1836 if (!empty($split[1])) {
1837 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1841 $split = explode('.', trim($k, '{}'));
1842 if (isset($split[1])) {
1843 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1846 $entity = 'Contact';
1848 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1853 foreach ($sorted as $k => $v) {
1854 $output[] = array('text' => $k, 'children' => $v);