3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
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
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'),
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 $requiredTokens = self
::getRequiredTokens();
126 foreach ($requiredTokens as $token => $value) {
127 if (!is_array($value)) {
128 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
129 $missing[$token] = $value;
135 foreach ($value as $t => $d) {
137 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
142 $missing[$token] = $desc;
147 if (empty($missing)) {
154 * Wrapper for token matching.
156 * @param string $type
157 * The token type (domain,mailing,contact,action).
159 * The token variable.
161 * The string to search.
166 public static function token_match($type, $var, &$str) {
167 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
168 return preg_match("/(^|[^\{])$token/", $str);
172 * Wrapper for token replacing.
174 * @param string $type
177 * The token variable.
178 * @param string $value
179 * The value to substitute for the token.
180 * @param string (reference) $str The string to replace in
182 * @param bool $escapeSmarty
185 * The processed string
187 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
188 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
193 $value = self
::tokenEscapeSmarty($value);
195 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
200 * Get< the regex for token replacement
202 * @param string $token_type
203 * A string indicating the the type of token to be used in the expression.
206 * regular expression sutiable for using in preg_replace
208 private static function tokenRegex($token_type) {
209 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
213 * Escape the string so a malicious user cannot inject smarty code into the template.
215 * @param string $string
216 * A string that needs to be escaped from smarty parsing.
221 private static function tokenEscapeSmarty($string) {
222 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
223 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
227 * Replace all the domain-level tokens in $str
230 * The string with tokens to be replaced.
231 * @param object $domain
234 * Replace tokens with HTML or plain text.
236 * @param null $knownTokens
237 * @param bool $escapeSmarty
240 * The processed string
242 public static function &replaceDomainTokens(
247 $escapeSmarty = FALSE
251 !$knownTokens ||
empty($knownTokens[$key])
256 $str = preg_replace_callback(
257 self
::tokenRegex($key),
258 function ($matches) use (&$domain, $html, $escapeSmarty) {
259 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
270 * @param bool $escapeSmarty
272 * @return mixed|null|string
274 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
275 // check if the token we were passed is valid
276 // we have to do this because this function is
277 // called only when we find a token in the string
279 $loc = &$domain->getLocationValues();
281 if (!in_array($token, self
::$_tokens['domain'])) {
282 $value = "{domain.$token}";
284 elseif ($token == 'address') {
285 static $addressCache = array();
287 $cache_key = $html ?
'address-html' : 'address-text';
288 if (array_key_exists($cache_key, $addressCache)) {
289 return $addressCache[$cache_key];
293 /* Construct the address token */
295 if (!empty($loc[$token])) {
297 $value = $loc[$token][1]['display'];
298 $value = str_replace("\n", '<br />', $value);
301 $value = $loc[$token][1]['display_text'];
303 $addressCache[$cache_key] = $value;
306 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
307 $value = $domain->$token;
309 elseif ($token == 'phone' ||
$token == 'email') {
310 /* Construct the phone and email tokens */
313 if (!empty($loc[$token])) {
314 foreach ($loc[$token] as $index => $entity) {
315 $value = $entity[$token];
322 $value = self
::tokenEscapeSmarty($value);
329 * Replace all the org-level tokens in $str
332 * The string with tokens to be replaced.
334 * Associative array of org properties.
336 * Replace tokens with HTML or plain text.
338 * @param bool $escapeSmarty
341 * The processed string
343 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
344 self
::$_tokens['org']
346 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
347 array('address', 'display_name', 'checksum', 'contact_id')
351 foreach (self
::$_tokens['org'] as $token) {
352 // print "Getting token value for $token<br/><br/>";
357 /* If the string doesn't contain this token, skip it. */
359 if (!self
::token_match('org', $token, $str)) {
363 /* Construct value from $token and $contact */
367 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
368 // only generate cv if we need it
370 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
372 foreach ($cv as $cvFieldID => $value) {
373 if ($cvFieldID == $cfID) {
374 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
379 elseif ($token == 'checksum') {
380 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
383 elseif ($token == 'address') {
384 /* Build the location values array */
387 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
388 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
389 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
390 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
391 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
393 /* Construct the address token */
395 $value = CRM_Utils_Address
::format($loc);
397 $value = str_replace("\n", '<br />', $value);
401 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
404 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
411 * Replace all mailing tokens in $str
414 * The string with tokens to be replaced.
415 * @param object $mailing
416 * The mailing BAO, or null for validation.
418 * Replace tokens with HTML or plain text.
420 * @param null $knownTokens
421 * @param bool $escapeSmarty
424 * The processed sstring
426 public static function &replaceMailingTokens(
431 $escapeSmarty = FALSE
434 if (!$knownTokens ||
!isset($knownTokens[$key])) {
438 $str = preg_replace_callback(
439 self
::tokenRegex($key),
440 function ($matches) use (&$mailing, $escapeSmarty) {
441 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
451 * @param bool $escapeSmarty
455 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
461 $value = $mailing ?
$mailing->id
: 'undefined';
465 $value = $mailing ?
$mailing->name
: 'Mailing Name';
469 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
470 $value = implode(', ', $groups);
474 $value = $mailing->subject
;
478 $mailingKey = $mailing->id
;
479 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
482 $value = CRM_Utils_System
::url('civicrm/mailing/view',
483 "reset=1&id={$mailingKey}",
484 TRUE, NULL, FALSE, TRUE
489 $value = CRM_Utils_System
::url('civicrm/mailing/send',
490 "reset=1&mid={$mailing->id}&continue=true",
491 TRUE, NULL, FALSE, TRUE
496 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
497 "reset=1&mid={$mailing->id}",
498 TRUE, NULL, FALSE, TRUE
503 $page = new CRM_Mailing_Page_View();
504 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
507 case 'approvalStatus':
508 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
512 $value = $mailing->approval_note
;
516 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
517 "reset=1&mid={$mailing->id}",
518 TRUE, NULL, FALSE, TRUE
523 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
527 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
531 $value = "{mailing.$token}";
536 $value = self
::tokenEscapeSmarty($value);
542 * Replace all action tokens in $str
545 * The string with tokens to be replaced.
546 * @param array $addresses
547 * Assoc. array of VERP event addresses.
549 * Assoc. array of action URLs.
551 * Replace tokens with HTML or plain text.
552 * @param array $knownTokens
553 * A list of tokens that are known to exist in the email body.
555 * @param bool $escapeSmarty
558 * The processed string
560 public static function &replaceActionTokens(
566 $escapeSmarty = FALSE
569 // here we intersect with the list of pre-configured valid tokens
570 // so that we remove anything we do not recognize
571 // I hope to move this step out of here soon and
572 // then we will just iterate on a list of tokens that are passed to us
573 if (!$knownTokens ||
empty($knownTokens[$key])) {
577 $str = preg_replace_callback(
578 self
::tokenRegex($key),
579 function ($matches) use (&$addresses, &$urls, $html, $escapeSmarty) {
580 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
592 * @param bool $escapeSmarty
594 * @return mixed|string
596 public static function getActionTokenReplacement(
601 $escapeSmarty = FALSE
603 /* If the token is an email action, use it. Otherwise, find the
606 if (!in_array($token, self
::$_tokens['action'])) {
607 $value = "{action.$token}";
610 $value = CRM_Utils_Array
::value($token, $addresses);
612 if ($value == NULL) {
613 $value = CRM_Utils_Array
::value($token, $urls);
616 if ($value && $html) {
618 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
619 $value = "mailto:$value";
622 elseif ($value && !$html) {
623 $value = str_replace('&', '&', $value);
628 $value = self
::tokenEscapeSmarty($value);
634 * Replace all the contact-level tokens in $str with information from
638 * The string with tokens to be replaced.
639 * @param array $contact
640 * Associative array of contact properties.
642 * Replace tokens with HTML or plain text.
643 * @param array $knownTokens
644 * A list of tokens that are known to exist in the email body.
645 * @param bool $returnBlankToken
646 * Return unevaluated token if value is null.
648 * @param bool $escapeSmarty
651 * 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 */
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)
775 // $returnBlankToken means the caller wants to do further attempts at
776 // processing unreplaced tokens -- so don't escape them yet in this case.
777 $value = self
::tokenEscapeSmarty($value);
784 * Replace all the hook tokens in $str with information from
788 * The string with tokens to be replaced.
789 * @param array $contact
790 * Associative array of contact properties (including hook token values).
793 * Replace tokens with HTML or plain text.
795 * @param bool $escapeSmarty
798 * The processed string
800 public static function &replaceHookTokens(
805 $escapeSmarty = FALSE
807 foreach ($categories as $key) {
808 $str = preg_replace_callback(
809 self
::tokenRegex($key),
810 function ($matches) use (&$contact, $key, $html, $escapeSmarty) {
811 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
820 * Parse html through Smarty resolving any smarty functions.
821 * @param string $tokenHtml
822 * @param array $entity
823 * @param string $entityType
825 * html parsed through smarty
827 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
828 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
829 $smarty = CRM_Core_Smarty
::singleton();
830 // also add the tokens to the template
831 $smarty->assign_by_ref($entityType, $entity);
832 $tokenHtml = $smarty->fetch("string:$tokenHtml");
842 * @param bool $escapeSmarty
844 * @return mixed|string
846 public static function getHookTokenReplacement(
851 $escapeSmarty = FALSE
853 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
855 if ($value && !$html) {
856 $value = str_replace('&', '&', $value);
860 $value = self
::tokenEscapeSmarty($value);
867 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
868 * for example {{token}} or \{token} will result in {token} in the final email
870 * this routine will remove the extra backslashes and braces
872 * @param $str ref to the string that will be scanned and modified
874 * this function works directly on the string that is passed
876 public static function unescapeTokens(&$str) {
877 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
881 * Replace unsubscribe tokens.
884 * The string with tokens to be replaced.
885 * @param object $domain
887 * @param array $groups
888 * The groups (if any) being unsubscribed.
890 * Replace tokens with html or plain text.
891 * @param int $contact_id
893 * @param string $hash The security hash of the unsub event
896 * The processed string
898 public static function &replaceUnsubscribeTokens(
906 if (self
::token_match('unsubscribe', 'group', $str)) {
907 if (!empty($groups)) {
908 $config = CRM_Core_Config
::singleton();
909 $base = CRM_Utils_System
::baseURL();
911 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
912 $dao = new CRM_Contact_DAO_Group();
914 while ($dao->fetch()) {
915 if (substr($dao->visibility
, 0, 6) == 'Public') {
916 $visibleGroups[] = $dao->id
;
919 $value = implode(', ', $groups);
920 self
::token_replace('unsubscribe', 'group', $value, $str);
927 * Replace resubscribe tokens.
930 * The string with tokens to be replaced.
931 * @param object $domain
933 * @param array $groups
934 * The groups (if any) being resubscribed.
936 * Replace tokens with html or plain text.
937 * @param int $contact_id
939 * @param string $hash The security hash of the resub event
942 * The processed string
944 public static function &replaceResubscribeTokens(
945 $str, &$domain, &$groups, $html,
948 if (self
::token_match('resubscribe', 'group', $str)) {
949 if (!empty($groups)) {
950 $value = implode(', ', $groups);
951 self
::token_replace('resubscribe', 'group', $value, $str);
958 * Replace subscription-confirmation-request tokens
961 * The string with tokens to be replaced.
962 * @param string $group
963 * The name of the group being subscribed.
966 * Replace tokens with html or plain text.
969 * The processed string
971 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
972 if (self
::token_match('subscribe', 'group', $str)) {
973 self
::token_replace('subscribe', 'group', $group, $str);
975 if (self
::token_match('subscribe', 'url', $str)) {
976 self
::token_replace('subscribe', 'url', $url, $str);
982 * Replace subscription-invitation tokens
985 * The string with tokens to be replaced.
988 * The processed string
990 public static function &replaceSubscribeInviteTokens($str) {
991 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
992 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
994 TRUE, NULL, TRUE, TRUE
996 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
999 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
1000 foreach ($matches as $key => $value) {
1001 $gid = substr($value, 21, -1);
1002 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
1003 "reset=1&gid={$gid}",
1004 TRUE, NULL, TRUE, TRUE
1006 $url = str_replace('&', '&', $url);
1007 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
1011 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
1012 foreach ($matches as $key => $value) {
1013 $gid = substr($value, 18, -1);
1014 $config = CRM_Core_Config
::singleton();
1015 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
1016 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1017 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1018 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1025 * Replace welcome/confirmation tokens
1027 * @param string $str
1028 * The string with tokens to be replaced.
1029 * @param string $group
1030 * The name of the group being subscribed.
1032 * Replace tokens with html or plain text.
1035 * The processed string
1037 public static function &replaceWelcomeTokens($str, $group, $html) {
1038 if (self
::token_match('welcome', 'group', $str)) {
1039 self
::token_replace('welcome', 'group', $group, $str);
1045 * Find unprocessed tokens (call this last)
1047 * @param string $str
1048 * The string to search.
1051 * Array of tokens that weren't replaced
1053 public static function &unmatchedTokens(&$str) {
1054 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1055 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1060 * Find and replace tokens for each component.
1062 * @param string $str
1063 * The string to search.
1064 * @param array $contact
1065 * Associative array of contact properties.
1066 * @param array $components
1067 * A list of tokens that are known to exist in the email body.
1069 * @param bool $escapeSmarty
1070 * @param bool $returnEmptyToken
1073 * The processed string
1075 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1076 if (!is_array($components) ||
empty($contact)) {
1080 foreach ($components as $name => $tokens) {
1081 if (!is_array($tokens) ||
empty($tokens)) {
1085 foreach ($tokens as $token) {
1086 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1087 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1089 elseif (!$returnEmptyToken) {
1090 //replacing empty token
1091 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1099 * Get array of string tokens.
1101 * @param string $string
1102 * The input string to parse for tokens.
1105 * array of tokens mentioned in field
1107 public static function getTokens($string) {
1110 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1117 foreach ($matches[1] as $token) {
1118 list($type, $name) = preg_split('/\./', $token, 2);
1119 if ($name && $type) {
1120 if (!isset($tokens[$type])) {
1121 $tokens[$type] = array();
1123 $tokens[$type][] = $name;
1131 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1132 * and getTokens appears to be historical rather than intentional and should be reviewed
1135 * fields to pass in as return properties when populating token
1137 public static function getReturnProperties(&$string) {
1138 $returnProperties = array();
1140 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1146 foreach ($matches[1] as $token) {
1147 list($type, $name) = preg_split('/\./', $token, 2);
1149 $returnProperties["{$name}"] = 1;
1154 return $returnProperties;
1158 * Gives required details of contacts in an indexed array format so we
1159 * can iterate in a nice loop and do token evaluation
1161 * @param $contactIDs
1162 * @param array $returnProperties
1163 * Of required properties.
1164 * @param bool $skipOnHold Don't return on_hold contact info also.
1165 * Don't return on_hold contact info also.
1166 * @param bool $skipDeceased Don't return deceased contact info.
1167 * Don't return deceased contact info.
1168 * @param array $extraParams
1170 * @param array $tokens
1171 * The list of tokens we've extracted from the content.
1172 * @param null $className
1174 * The mailing list jobID - this is a legacy param.
1178 public static function getTokenDetails(
1180 $returnProperties = NULL,
1182 $skipDeceased = TRUE,
1183 $extraParams = NULL,
1188 if (empty($contactIDs)) {
1189 // putting a fatal here so we can track if/when this happens
1190 CRM_Core_Error
::fatal();
1194 foreach ($contactIDs as $key => $contactID) {
1196 CRM_Core_Form
::CB_PREFIX
. $contactID,
1205 if ($skipDeceased) {
1206 $params[] = array('is_deceased', '=', 0, 0, 0);
1211 $params[] = array('on_hold', '=', 0, 0, 0);
1215 $params = array_merge($params, $extraParams);
1218 // if return properties are not passed then get all return properties
1219 if (empty($returnProperties)) {
1220 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1221 array('display_name', 'checksum', 'contact_id')
1223 foreach ($fields as $key => $val) {
1224 $returnProperties[$val] = 1;
1229 foreach ($returnProperties as $name => $dontCare) {
1230 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1236 //get the total number of contacts to fetch from database.
1237 $numberofContacts = count($contactIDs);
1238 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1240 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1242 $contactDetails = &$details[0];
1244 foreach ($contactIDs as $key => $contactID) {
1245 if (array_key_exists($contactID, $contactDetails)) {
1246 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1247 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1249 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1251 // communication Prefferance
1252 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1253 $contactDetails[$contactID]['preferred_communication_method']
1256 foreach ($contactPcm as $key => $val) {
1258 $result[$val] = $pcm[$val];
1261 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1264 foreach ($custom as $cfID) {
1265 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1266 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1272 //special case for greeting replacement
1278 if (!empty($contactDetails[$contactID][$val])) {
1279 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1285 // also call a hook and get token details
1286 CRM_Utils_Hook
::tokenValues($details[0],
1296 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1297 * specific tokens to be rendered
1299 * @param array $contactIDs
1300 * This should always be array(0) or its not anonymous - left to keep signature same.
1302 * @param string $returnProperties
1303 * @param bool $skipOnHold
1304 * @param bool $skipDeceased
1305 * @param string $extraParams
1306 * @param array $tokens
1307 * @param string $className
1308 * Sent as context to the hook.
1309 * @param string $jobID
1311 * contactDetails with hooks swapped out
1313 public function getAnonymousTokenDetails($contactIDs = array(
1316 $returnProperties = NULL,
1318 $skipDeceased = TRUE,
1319 $extraParams = NULL,
1323 $details = array(0 => array());
1324 // also call a hook and get token details
1325 CRM_Utils_Hook
::tokenValues($details[0],
1335 * Gives required details of contribuion in an indexed array format so we
1336 * can iterate in a nice loop and do token evaluation
1338 * @param array $contributionIDs
1339 * @param array $returnProperties
1340 * Of required properties.
1341 * @param array $extraParams
1343 * @param array $tokens
1344 * The list of tokens we've extracted from the content.
1345 * @param string $className
1349 public static function getContributionTokenDetails(
1351 $returnProperties = NULL,
1352 $extraParams = NULL,
1356 //@todo - this function basically replicates calling
1357 //civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1358 if (empty($contributionIDs)) {
1359 // putting a fatal here so we can track if/when this happens
1360 CRM_Core_Error
::fatal();
1365 // no apiQuery helper yet, so do a loop and find contribution by id
1366 foreach ($contributionIDs as $contributionID) {
1368 $dao = new CRM_Contribute_DAO_Contribution();
1369 $dao->id
= $contributionID;
1371 if ($dao->find(TRUE)) {
1373 $details[$dao->id
] = array();
1374 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1376 // do the necessary transformation
1377 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1378 $piId = $details[$dao->id
]['payment_instrument_id'];
1379 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1380 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1382 if (!empty($details[$dao->id
]['campaign_id'])) {
1383 $campaignId = $details[$dao->id
]['campaign_id'];
1384 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1385 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1388 if (!empty($details[$dao->id
]['financial_type_id'])) {
1389 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1390 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1391 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1394 // TODO: call a hook to get token contribution details
1402 * Get Membership Token Details.
1403 * @param array $membershipIDs
1404 * Array of membership IDS.
1406 public static function getMembershipTokenDetails($membershipIDs) {
1407 $memberships = civicrm_api3('membership', 'get', array(
1408 'options' => array('limit' => 200000),
1409 'membership_id' => array('IN' => (array) $membershipIDs),
1411 return $memberships['values'];
1415 * Replace greeting tokens exists in message/subject
1417 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1419 if (!$contactDetails && !$contactId) {
1423 // check if there are any tokens
1424 $greetingTokens = self
::getTokens($tokenString);
1426 if (!empty($greetingTokens)) {
1427 // first use the existing contact object for token replacement
1428 if (!empty($contactDetails)) {
1429 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1432 // check if there are any unevaluated tokens
1433 $greetingTokens = self
::getTokens($tokenString);
1435 // $greetingTokens not empty, means there are few tokens which are not
1436 // evaluated, like custom data etc
1437 // so retrieve it from database
1438 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1439 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1440 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1441 $contactParams = array('contact_id' => $contactId);
1443 $greetingDetails = self
::getTokenDetails($contactParams,
1444 $greetingsReturnProperties,
1450 // again replace tokens
1451 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1460 // check if there are still any unevaluated tokens
1461 $remainingTokens = self
::getTokens($tokenString);
1463 // contact related $greetingTokens not empty, there are customized or hook tokens to replace
1464 if (!empty($remainingTokens['contact'])) {
1465 // Fill the return properties array
1466 $greetingTokens = $remainingTokens['contact'];
1467 reset($greetingTokens);
1468 $greetingsReturnProperties = array();
1469 while (list($key) = each($greetingTokens)) {
1470 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1471 $props = array_fill_keys(array_keys($props), 1);
1472 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1474 $contactParams = array('contact_id' => $contactId);
1475 $greetingDetails = self
::getTokenDetails($contactParams,
1476 $greetingsReturnProperties,
1481 // Prepare variables for calling replaceHookTokens
1482 $categories = array_keys($greetingTokens);
1483 list($contact) = $greetingDetails;
1484 // Replace tokens defined in Hooks.
1485 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1495 public static function flattenTokens(&$tokens) {
1496 $flattenTokens = array();
1503 if (!isset($tokens[$prop])) {
1506 foreach ($tokens[$prop] as $type => $names) {
1507 if (!isset($flattenTokens[$type])) {
1508 $flattenTokens[$type] = array();
1510 foreach ($names as $name) {
1511 $flattenTokens[$type][$name] = 1;
1516 return $flattenTokens;
1520 * Replace all user tokens in $str
1522 * @param string $str
1523 * The string with tokens to be replaced.
1525 * @param null $knownTokens
1526 * @param bool $escapeSmarty
1529 * The processed string
1531 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1533 if (!$knownTokens ||
1534 !isset($knownTokens[$key])
1539 $str = preg_replace_callback(
1540 self
::tokenRegex($key),
1541 function ($matches) use ($escapeSmarty) {
1542 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1551 * @param bool $escapeSmarty
1555 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1558 list($objectName, $objectValue) = explode('-', $token, 2);
1560 switch ($objectName) {
1562 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1566 $value = CRM_Core_Permission
::roleEmails($objectValue);
1570 if ($escapeSmarty) {
1571 $value = self
::tokenEscapeSmarty($value);
1579 protected static function _buildContributionTokens() {
1580 $key = 'contribution';
1581 if (self
::$_tokens[$key] == NULL) {
1582 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1583 array('campaign', 'financial_type')
1589 * Store membership tokens on the static _tokens array.
1591 protected static function _buildMembershipTokens() {
1592 $key = 'membership';
1593 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1594 $membershipTokens = array();
1595 $tokens = CRM_Core_SelectValues
::membershipTokens();
1596 foreach ($tokens as $token => $dontCare) {
1597 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1599 self
::$_tokens[$key] = $membershipTokens;
1604 * Replace tokens for an entity.
1605 * @param string $entity
1606 * @param array $entityArray
1607 * (e.g. in format from api).
1608 * @param string $str
1609 * String to replace in.
1610 * @param array $knownTokens
1611 * Array of tokens present.
1612 * @param bool $escapeSmarty
1614 * string with replacements made
1616 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1617 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1621 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1622 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1623 foreach ($knownTokens[$entity] as $token) {
1624 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1625 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1627 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1632 * Replace Contribution tokens in html.
1634 * @param string $str
1635 * @param array $contribution
1636 * @param bool|string $html
1637 * @param string $knownTokens
1638 * @param bool|string $escapeSmarty
1642 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1643 $key = 'contribution';
1644 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1645 return $str; //early return
1647 self
::_buildContributionTokens();
1649 // here we intersect with the list of pre-configured valid tokens
1650 // so that we remove anything we do not recognize
1651 // I hope to move this step out of here soon and
1652 // then we will just iterate on a list of tokens that are passed to us
1654 $str = preg_replace_callback(
1655 self
::tokenRegex($key),
1656 function ($matches) use (&$contribution, $html, $escapeSmarty) {
1657 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1662 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1667 * We have a situation where we are rendering more than one token in each field because we are combining
1668 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1670 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1671 * it applies (other tokens are OK including date fields)
1673 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1674 * does - but the fields is already being formatted through a date function
1676 * @param string $separator
1677 * @param string $str
1678 * @param array $contribution
1679 * @param bool|string $html
1680 * @param string $knownTokens
1681 * @param bool|string $escapeSmarty
1683 * @return \Ambigous|mixed|string|\unknown
1685 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1686 if (empty($knownTokens['contribution'])) {
1690 if (in_array('receive_date', $knownTokens['contribution'])) {
1691 $formattedDates = array();
1692 $dates = explode($separator, $contribution['receive_date']);
1693 foreach ($dates as $date) {
1694 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1696 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1697 unset($knownTokens['contribution']['receive_date']);
1699 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1703 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1704 * - this is used by the pdfLetter task from membership search
1705 * @param string $token
1706 * @param array $membership
1707 * An api result array for a single membership.
1708 * @param bool $escapeSmarty
1712 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1713 $entity = 'membership';
1714 self
::_buildMembershipTokens();
1717 $value = $membership['membership_name'];
1721 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1722 $value = $statuses[$membership['status_id']];
1727 $value = civicrm_api3('membership_type', 'getvalue', array(
1728 'id' => $membership['membership_type_id'],
1729 'return' => 'minimum_fee',
1732 catch (CiviCRM_API3_Exception
$e) {
1733 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1734 // api handles NULL (4.4)
1740 if (in_array($token, self
::$_tokens[$entity])) {
1741 $value = $membership[$token];
1745 $value = "{$entity}.{$token}";
1750 if ($escapeSmarty) {
1751 $value = self
::tokenEscapeSmarty($value);
1758 * @param $contribution
1760 * @param bool $escapeSmarty
1762 * @return mixed|string
1764 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1765 self
::_buildContributionTokens();
1768 case 'total_amount':
1771 case 'non_deductible_amount':
1772 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1775 case 'receive_date':
1776 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1777 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1781 if (!in_array($token, self
::$_tokens['contribution'])) {
1782 $value = "{contribution.$token}";
1785 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1790 if ($escapeSmarty) {
1791 $value = self
::tokenEscapeSmarty($value);
1798 * legacy_token => new_token
1800 public static function legacyContactTokens() {
1802 'individual_prefix' => 'prefix_id',
1803 'individual_suffix' => 'suffix_id',
1804 'gender' => 'gender_id',
1805 'communication_style' => 'communication_style_id',
1810 * Formats a token list for the select2 widget
1815 public static function formatTokensForDisplay($tokens) {
1816 $sorted = $output = array();
1818 // Sort in ascending order by ignoring word case
1819 natcasesort($tokens);
1821 // Attempt to place tokens into optgroups
1822 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1823 foreach ($tokens as $k => $v) {
1824 // Check to see if this token is already in a group e.g. for custom fields
1825 $split = explode(' :: ', $v);
1826 if (!empty($split[1])) {
1827 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1831 $split = explode('.', trim($k, '{}'));
1832 if (isset($split[1])) {
1833 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1836 $entity = 'Contact';
1838 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1843 foreach ($sorted as $k => $v) {
1844 $output[] = array('text' => $k, 'children' => $v);