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.
100 * true if all required tokens are found,
101 * else an array of the missing tokens
104 public static function requiredTokens(&$str) {
105 if (self
::$_requiredTokens == NULL) {
106 self
::$_requiredTokens = array(
107 'domain.address' => ts("Domain address - displays your organization's postal address."),
108 'action.optOutUrl or action.unsubscribeUrl' => array(
109 'action.optOut' => ts("'Opt out via email' - displays an email address for recipients to opt out of receiving emails from your organization."),
110 '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."),
111 'action.unsubscribe' => ts("'Unsubscribe via email' - displays an email address for recipients to unsubscribe from the specific mailing list used to send this message."),
112 '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."),
118 foreach (self
::$_requiredTokens as $token => $value) {
119 if (!is_array($value)) {
120 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
121 $missing[$token] = $value;
127 foreach ($value as $t => $d) {
129 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
134 $missing[$token] = $desc;
139 if (empty($missing)) {
146 * Wrapper for token matching
148 * @param string $type
149 * The token type (domain,mailing,contact,action).
151 * The token variable.
153 * The string to search.
159 public static function token_match($type, $var, &$str) {
160 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
161 return preg_match("/(^|[^\{])$token/", $str);
165 * Wrapper for token replacing
167 * @param string $type
170 * The token variable.
171 * @param string $value
172 * The value to substitute for the token.
173 * @param string (reference) $str The string to replace in
175 * @param bool $escapeSmarty
178 * The processed string
181 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
182 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
187 $value = self
::tokenEscapeSmarty($value);
189 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
194 * Get< the regex for token replacement
196 * @param string $token_type
197 * A string indicating the the type of token to be used in the expression.
200 * regular expression sutiable for using in preg_replace
203 private static function tokenRegex($token_type) {
204 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
208 * Escape the string so a malicious user cannot inject smarty code into the template
210 * @param string $string
211 * A string that needs to be escaped from smarty parsing.
217 private static function tokenEscapeSmarty($string) {
218 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
219 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
223 * Replace all the domain-level tokens in $str
226 * The string with tokens to be replaced.
227 * @param object $domain
230 * Replace tokens with HTML or plain text.
232 * @param null $knownTokens
233 * @param bool $escapeSmarty
236 * The processed string
239 public static function &replaceDomainTokens(
244 $escapeSmarty = FALSE
248 !$knownTokens ||
empty($knownTokens[$key])
253 $str = preg_replace_callback(
254 self
::tokenRegex($key),
255 function ($matches) use (&$domain, $html, $escapeSmarty) {
256 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
267 * @param bool $escapeSmarty
269 * @return mixed|null|string
271 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
272 // check if the token we were passed is valid
273 // we have to do this because this function is
274 // called only when we find a token in the string
276 $loc = &$domain->getLocationValues();
278 if (!in_array($token, self
::$_tokens['domain'])) {
279 $value = "{domain.$token}";
281 elseif ($token == 'address') {
282 static $addressCache = array();
284 $cache_key = $html ?
'address-html' : 'address-text';
285 if (array_key_exists($cache_key, $addressCache)) {
286 return $addressCache[$cache_key];
290 /* Construct the address token */
292 if (!empty($loc[$token])) {
294 $value = $loc[$token][1]['display'];
295 $value = str_replace("\n", '<br />', $value);
298 $value = $loc[$token][1]['display_text'];
300 $addressCache[$cache_key] = $value;
303 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
304 $value = $domain->$token;
306 elseif ($token == 'phone' ||
$token == 'email') {
307 /* Construct the phone and email tokens */
310 if (!empty($loc[$token])) {
311 foreach ($loc[$token] as $index => $entity) {
312 $value = $entity[$token];
319 $value = self
::tokenEscapeSmarty($value);
326 * Replace all the org-level tokens in $str
329 * The string with tokens to be replaced.
331 * Associative array of org properties.
333 * Replace tokens with HTML or plain text.
335 * @param bool $escapeSmarty
338 * 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 sstring
425 public static function &replaceMailingTokens(
430 $escapeSmarty = FALSE
433 if (!$knownTokens ||
!isset($knownTokens[$key])) {
437 $str = preg_replace_callback(
438 self
::tokenRegex($key),
439 function ($matches) use (&$mailing, $escapeSmarty) {
440 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
450 * @param bool $escapeSmarty
454 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
460 $value = $mailing ?
$mailing->id
: 'undefined';
464 $value = $mailing ?
$mailing->name
: 'Mailing Name';
468 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
469 $value = implode(', ', $groups);
473 $value = $mailing->subject
;
477 $mailingKey = $mailing->id
;
478 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
481 $value = CRM_Utils_System
::url('civicrm/mailing/view',
482 "reset=1&id={$mailingKey}",
483 TRUE, NULL, FALSE, TRUE
488 $value = CRM_Utils_System
::url('civicrm/mailing/send',
489 "reset=1&mid={$mailing->id}&continue=true",
490 TRUE, NULL, FALSE, TRUE
495 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
496 "reset=1&mid={$mailing->id}",
497 TRUE, NULL, FALSE, TRUE
502 $page = new CRM_Mailing_Page_View();
503 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
506 case 'approvalStatus':
507 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
511 $value = $mailing->approval_note
;
515 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
516 "reset=1&mid={$mailing->id}",
517 TRUE, NULL, FALSE, TRUE
522 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
526 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
530 $value = "{mailing.$token}";
535 $value = self
::tokenEscapeSmarty($value);
541 * Replace all action tokens in $str
544 * The string with tokens to be replaced.
545 * @param array $addresses
546 * Assoc. array of VERP event addresses.
548 * Assoc. array of action URLs.
550 * Replace tokens with HTML or plain text.
551 * @param array $knownTokens
552 * A list of tokens that are known to exist in the email body.
554 * @param bool $escapeSmarty
557 * 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
654 public static function &replaceContactTokens(
659 $returnBlankToken = FALSE,
660 $escapeSmarty = FALSE
663 if (self
::$_tokens[$key] == NULL) {
664 /* This should come from UF */
666 self
::$_tokens[$key] =
668 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
669 array('checksum', 'contact_id')
673 // here we intersect with the list of pre-configured valid tokens
674 // so that we remove anything we do not recognize
675 // I hope to move this step out of here soon and
676 // then we will just iterate on a list of tokens that are passed to us
677 if (!$knownTokens ||
empty($knownTokens[$key])) {
681 $str = preg_replace_callback(
682 self
::tokenRegex($key),
683 function ($matches) use (&$contact, $html, $returnBlankToken, $escapeSmarty) {
684 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
689 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
697 * @param bool $returnBlankToken
698 * @param bool $escapeSmarty
700 * @return bool|mixed|null|string
702 public static function getContactTokenReplacement(
706 $returnBlankToken = FALSE,
707 $escapeSmarty = FALSE
709 if (self
::$_tokens['contact'] == NULL) {
710 /* This should come from UF */
712 self
::$_tokens['contact'] =
714 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
715 array('checksum', 'contact_id')
719 /* Construct value from $token and $contact */
724 // Support legacy tokens
725 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
727 // check if the token we were passed is valid
728 // we have to do this because this function is
729 // called only when we find a token in the string
731 if (!in_array($token, self
::$_tokens['contact'])) {
734 elseif ($token == 'checksum') {
735 $hash = CRM_Utils_Array
::value('hash', $contact);
736 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
737 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
745 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
747 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
748 if (is_array($value)) {
751 // Convert pseudoconstants using metadata
752 elseif ($value && is_numeric($value)) {
753 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
754 if (!empty($allFields[$token]['pseudoconstant'])) {
755 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
761 $value = str_replace('&', '&', $value);
764 // if null then return actual token
765 if ($returnBlankToken && !$value) {
770 $value = "{contact.$token}";
774 && !($returnBlankToken && $noReplace)
775 ) { // $returnBlankToken means the caller wants to do further attempts at processing unreplaced tokens -- so don't escape them yet in this case.
776 $value = self
::tokenEscapeSmarty($value);
783 * Replace all the hook tokens in $str with information from
787 * The string with tokens to be replaced.
788 * @param array $contact
789 * Associative array of contact properties (including hook token values).
792 * Replace tokens with HTML or plain text.
794 * @param bool $escapeSmarty
797 * 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
878 public static function unescapeTokens(&$str) {
879 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
883 * Replace unsubscribe tokens
886 * The string with tokens to be replaced.
887 * @param object $domain
889 * @param array $groups
890 * The groups (if any) being unsubscribed.
892 * Replace tokens with html or plain text.
893 * @param int $contact_id
895 * @param string hash The security hash of the unsub event
898 * The processed string
901 public static function &replaceUnsubscribeTokens(
909 if (self
::token_match('unsubscribe', 'group', $str)) {
910 if (!empty($groups)) {
911 $config = CRM_Core_Config
::singleton();
912 $base = CRM_Utils_System
::baseURL();
914 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
915 $dao = new CRM_Contact_DAO_Group();
917 while ($dao->fetch()) {
918 if (substr($dao->visibility
, 0, 6) == 'Public') {
919 $visibleGroups[] = $dao->id
;
922 $value = implode(', ', $groups);
923 self
::token_replace('unsubscribe', 'group', $value, $str);
930 * Replace resubscribe tokens
933 * The string with tokens to be replaced.
934 * @param object $domain
936 * @param array $groups
937 * The groups (if any) being resubscribed.
939 * Replace tokens with html or plain text.
940 * @param int $contact_id
942 * @param string hash The security hash of the resub event
945 * The processed string
948 public static function &replaceResubscribeTokens(
949 $str, &$domain, &$groups, $html,
952 if (self
::token_match('resubscribe', 'group', $str)) {
953 if (!empty($groups)) {
954 $value = implode(', ', $groups);
955 self
::token_replace('resubscribe', 'group', $value, $str);
962 * Replace subscription-confirmation-request tokens
965 * The string with tokens to be replaced.
966 * @param string $group
967 * The name of the group being subscribed.
970 * Replace tokens with html or plain text.
973 * The processed string
976 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
977 if (self
::token_match('subscribe', 'group', $str)) {
978 self
::token_replace('subscribe', 'group', $group, $str);
980 if (self
::token_match('subscribe', 'url', $str)) {
981 self
::token_replace('subscribe', 'url', $url, $str);
987 * Replace subscription-invitation tokens
990 * The string with tokens to be replaced.
993 * The processed string
996 public static function &replaceSubscribeInviteTokens($str) {
997 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
998 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
1000 TRUE, NULL, TRUE, TRUE
1002 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
1005 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
1006 foreach ($matches as $key => $value) {
1007 $gid = substr($value, 21, -1);
1008 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
1009 "reset=1&gid={$gid}",
1010 TRUE, NULL, TRUE, TRUE
1012 $url = str_replace('&', '&', $url);
1013 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
1017 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
1018 foreach ($matches as $key => $value) {
1019 $gid = substr($value, 18, -1);
1020 $config = CRM_Core_Config
::singleton();
1021 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
1022 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1023 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1024 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1031 * Replace welcome/confirmation tokens
1033 * @param string $str
1034 * The string with tokens to be replaced.
1035 * @param string $group
1036 * The name of the group being subscribed.
1038 * Replace tokens with html or plain text.
1041 * The processed string
1044 public static function &replaceWelcomeTokens($str, $group, $html) {
1045 if (self
::token_match('welcome', 'group', $str)) {
1046 self
::token_replace('welcome', 'group', $group, $str);
1052 * Find unprocessed tokens (call this last)
1054 * @param string $str
1055 * The string to search.
1058 * Array of tokens that weren't replaced
1061 public static function &unmatchedTokens(&$str) {
1062 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1063 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1068 * Find and replace tokens for each component
1070 * @param string $str
1071 * The string to search.
1072 * @param array $contact
1073 * Associative array of contact properties.
1074 * @param array $components
1075 * A list of tokens that are known to exist in the email body.
1077 * @param bool $escapeSmarty
1078 * @param bool $returnEmptyToken
1081 * The processed string
1084 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1085 if (!is_array($components) ||
empty($contact)) {
1089 foreach ($components as $name => $tokens) {
1090 if (!is_array($tokens) ||
empty($tokens)) {
1094 foreach ($tokens as $token) {
1095 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1096 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1098 elseif (!$returnEmptyToken) {
1099 //replacing empty token
1100 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1108 * Get array of string tokens
1110 * @param string $string
1111 * The input string to parse for tokens.
1114 * array of tokens mentioned in field
1118 public static function getTokens($string) {
1121 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1128 foreach ($matches[1] as $token) {
1129 list($type, $name) = preg_split('/\./', $token, 2);
1130 if ($name && $type) {
1131 if (!isset($tokens[$type])) {
1132 $tokens[$type] = array();
1134 $tokens[$type][] = $name;
1142 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1143 * and getTokens appears to be historical rather than intentional and should be reviewed
1146 * fields to pass in as return properties when populating token
1148 public static function getReturnProperties(&$string) {
1149 $returnProperties = array();
1151 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1157 foreach ($matches[1] as $token) {
1158 list($type, $name) = preg_split('/\./', $token, 2);
1160 $returnProperties["{$name}"] = 1;
1165 return $returnProperties;
1169 * Gives required details of contacts in an indexed array format so we
1170 * can iterate in a nice loop and do token evaluation
1172 * @param $contactIDs
1173 * @param array $returnProperties
1174 * Of required properties.
1175 * @param bool $skipOnHoldDon 't return on_hold contact info also.
1176 * Don't return on_hold contact info also.
1177 * @param bool $skipDeceasedDon 't return deceased contact info.
1178 * Don't return deceased contact info.
1179 * @param array $extraParams
1181 * @param array $tokens
1182 * The list of tokens we've extracted from the content.
1183 * @param null $className
1185 * The mailing list jobID - this is a legacy param.
1190 static function getTokenDetails(
1192 $returnProperties = NULL,
1194 $skipDeceased = TRUE,
1195 $extraParams = NULL,
1200 if (empty($contactIDs)) {
1201 // putting a fatal here so we can track if/when this happens
1202 CRM_Core_Error
::fatal();
1206 foreach ($contactIDs as $key => $contactID) {
1208 CRM_Core_Form
::CB_PREFIX
. $contactID,
1217 if ($skipDeceased) {
1218 $params[] = array('is_deceased', '=', 0, 0, 0);
1223 $params[] = array('on_hold', '=', 0, 0, 0);
1227 $params = array_merge($params, $extraParams);
1230 // if return properties are not passed then get all return properties
1231 if (empty($returnProperties)) {
1232 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1233 array('display_name', 'checksum', 'contact_id')
1235 foreach ($fields as $key => $val) {
1236 $returnProperties[$val] = 1;
1241 foreach ($returnProperties as $name => $dontCare) {
1242 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1248 //get the total number of contacts to fetch from database.
1249 $numberofContacts = count($contactIDs);
1250 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1252 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1254 $contactDetails = &$details[0];
1256 foreach ($contactIDs as $key => $contactID) {
1257 if (array_key_exists($contactID, $contactDetails)) {
1258 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1259 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1261 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1263 // communication Prefferance
1264 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1265 $contactDetails[$contactID]['preferred_communication_method']
1268 foreach ($contactPcm as $key => $val) {
1270 $result[$val] = $pcm[$val];
1273 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1276 foreach ($custom as $cfID) {
1277 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1278 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1284 //special case for greeting replacement
1290 if (!empty($contactDetails[$contactID][$val])) {
1291 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1297 // also call a hook and get token details
1298 CRM_Utils_Hook
::tokenValues($details[0],
1308 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1309 * specific tokens to be rendered
1311 * @param array $contactIDs
1312 * This should always be array(0) or its not anonymous - left to keep signature same.
1314 * @param string $returnProperties
1315 * @param bool $skipOnHold
1316 * @param bool $skipDeceased
1317 * @param string $extraParams
1318 * @param array $tokens
1319 * @param string $className
1320 * Sent as context to the hook.
1321 * @param string $jobID
1323 * contactDetails with hooks swapped out
1325 public function getAnonymousTokenDetails($contactIDs = array(
1328 $returnProperties = NULL,
1330 $skipDeceased = TRUE,
1331 $extraParams = NULL,
1335 $details = array(0 => array());
1336 // also call a hook and get token details
1337 CRM_Utils_Hook
::tokenValues($details[0],
1347 * Gives required details of contribuion in an indexed array format so we
1348 * can iterate in a nice loop and do token evaluation
1350 * @param array $contributionIDs
1351 * @param array $returnProperties
1352 * Of required properties.
1353 * @param array $extraParams
1355 * @param array $tokens
1356 * The list of tokens we've extracted from the content.
1357 * @param string $className
1362 static function getContributionTokenDetails(
1364 $returnProperties = NULL,
1365 $extraParams = NULL,
1369 //@todo - this function basically replications calling civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1370 if (empty($contributionIDs)) {
1371 // putting a fatal here so we can track if/when this happens
1372 CRM_Core_Error
::fatal();
1377 // no apiQuery helper yet, so do a loop and find contribution by id
1378 foreach ($contributionIDs as $contributionID) {
1380 $dao = new CRM_Contribute_DAO_Contribution();
1381 $dao->id
= $contributionID;
1383 if ($dao->find(TRUE)) {
1385 $details[$dao->id
] = array();
1386 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1388 // do the necessary transformation
1389 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1390 $piId = $details[$dao->id
]['payment_instrument_id'];
1391 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1392 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1394 if (!empty($details[$dao->id
]['campaign_id'])) {
1395 $campaignId = $details[$dao->id
]['campaign_id'];
1396 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1397 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1400 if (!empty($details[$dao->id
]['financial_type_id'])) {
1401 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1402 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1403 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1406 // TODO: call a hook to get token contribution details
1414 * Get Membership Token Details
1415 * @param array $membershipIDs
1416 * Array of membership IDS.
1418 public static function getMembershipTokenDetails($membershipIDs) {
1419 $memberships = civicrm_api3('membership', 'get', array(
1420 'options' => array('limit' => 200000),
1421 'membership_id' => array('IN' => (array) $membershipIDs)
1423 return $memberships['values'];
1427 * Replace greeting tokens exists in message/subject
1429 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1431 if (!$contactDetails && !$contactId) {
1435 // check if there are any tokens
1436 $greetingTokens = self
::getTokens($tokenString);
1438 if (!empty($greetingTokens)) {
1439 // first use the existing contact object for token replacement
1440 if (!empty($contactDetails)) {
1441 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1444 // check if there are any unevaluated tokens
1445 $greetingTokens = self
::getTokens($tokenString);
1447 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1448 // so retrieve it from database
1449 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1450 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1451 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1452 $contactParams = array('contact_id' => $contactId);
1454 $greetingDetails = self
::getTokenDetails($contactParams,
1455 $greetingsReturnProperties,
1461 // again replace tokens
1462 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1471 // check if there are still any unevaluated tokens
1472 $remainingTokens = self
::getTokens($tokenString);
1474 // contact related $greetingTokens not empty, there are customized or hook tokens to replace
1475 if (!empty($remainingTokens['contact'])) {
1476 // Fill the return properties array
1477 $greetingTokens = $remainingTokens['contact'];
1478 reset($greetingTokens);
1479 $greetingsReturnProperties = array();
1480 while (list($key) = each($greetingTokens)) {
1481 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1482 $props = array_fill_keys(array_keys($props), 1);
1483 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1485 $contactParams = array('contact_id' => $contactId);
1486 $greetingDetails = self
::getTokenDetails($contactParams,
1487 $greetingsReturnProperties,
1492 // Prepare variables for calling replaceHookTokens
1493 $categories = array_keys($greetingTokens);
1494 list($contact) = $greetingDetails;
1495 // Replace tokens defined in Hooks.
1496 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1506 public static function flattenTokens(&$tokens) {
1507 $flattenTokens = array();
1514 if (!isset($tokens[$prop])) {
1517 foreach ($tokens[$prop] as $type => $names) {
1518 if (!isset($flattenTokens[$type])) {
1519 $flattenTokens[$type] = array();
1521 foreach ($names as $name) {
1522 $flattenTokens[$type][$name] = 1;
1527 return $flattenTokens;
1531 * Replace all user tokens in $str
1533 * @param string $str
1534 * The string with tokens to be replaced.
1536 * @param null $knownTokens
1537 * @param bool $escapeSmarty
1540 * The processed string
1543 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1545 if (!$knownTokens ||
1546 !isset($knownTokens[$key])
1551 $str = preg_replace_callback(
1552 self
::tokenRegex($key),
1553 function ($matches) use ($escapeSmarty) {
1554 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1563 * @param bool $escapeSmarty
1567 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1570 list($objectName, $objectValue) = explode('-', $token, 2);
1572 switch ($objectName) {
1574 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1578 $value = CRM_Core_Permission
::roleEmails($objectValue);
1582 if ($escapeSmarty) {
1583 $value = self
::tokenEscapeSmarty($value);
1591 protected static function _buildContributionTokens() {
1592 $key = 'contribution';
1593 if (self
::$_tokens[$key] == NULL) {
1594 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1595 array('campaign', 'financial_type')
1601 * Store membership tokens on the static _tokens array
1603 protected static function _buildMembershipTokens() {
1604 $key = 'membership';
1605 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1606 $membershipTokens = array();
1607 $tokens = CRM_Core_SelectValues
::membershipTokens();
1608 foreach ($tokens as $token => $dontCare) {
1609 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1611 self
::$_tokens[$key] = $membershipTokens;
1616 * Replace tokens for an entity
1617 * @param string $entity
1618 * @param array $entityArray
1619 * (e.g. in format from api).
1620 * @param string $str
1621 * String to replace in.
1622 * @param array $knownTokens
1623 * Array of tokens present.
1624 * @param bool $escapeSmarty
1626 * string with replacements made
1628 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1629 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1633 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1634 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1635 foreach ($knownTokens[$entity] as $token) {
1636 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1637 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1639 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1644 * Replace Contribution tokens in html
1646 * @param string $str
1647 * @param array $contribution
1648 * @param bool|string $html
1649 * @param string $knownTokens
1650 * @param bool|string $escapeSmarty
1654 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1655 $key = 'contribution';
1656 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1657 return $str; //early return
1659 self
::_buildContributionTokens();
1661 // here we intersect with the list of pre-configured valid tokens
1662 // so that we remove anything we do not recognize
1663 // I hope to move this step out of here soon and
1664 // then we will just iterate on a list of tokens that are passed to us
1666 $str = preg_replace_callback(
1667 self
::tokenRegex($key),
1668 function ($matches) use (&$contribution, $html, $escapeSmarty) {
1669 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1674 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1679 * We have a situation where we are rendering more than one token in each field because we are combining
1680 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1682 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1683 * it applies (other tokens are OK including date fields)
1685 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1686 * does - but the fields is already being formatted through a date function
1688 * @param string $separator
1689 * @param string $str
1690 * @param array $contribution
1691 * @param bool|string $html
1692 * @param string $knownTokens
1693 * @param bool|string $escapeSmarty
1695 * @return \Ambigous|mixed|string|\unknown
1697 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1698 if (empty($knownTokens['contribution'])) {
1702 if (in_array('receive_date', $knownTokens['contribution'])) {
1703 $formattedDates = array();
1704 $dates = explode($separator, $contribution['receive_date']);
1705 foreach ($dates as $date) {
1706 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1708 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1709 unset($knownTokens['contribution']['receive_date']);
1711 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1715 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1716 * - this is used by the pdfLetter task from membership search
1717 * @param string $token
1718 * @param array $membership
1719 * An api result array for a single membership.
1720 * @param bool $escapeSmarty
1724 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1725 $entity = 'membership';
1726 self
::_buildMembershipTokens();
1729 $value = $membership['membership_name'];
1733 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1734 $value = $statuses[$membership['status_id']];
1739 $value = civicrm_api3('membership_type', 'getvalue', array(
1740 'id' => $membership['membership_type_id'],
1741 'return' => 'minimum_fee'
1744 catch (CiviCRM_API3_Exception
$e) {
1745 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1746 // api handles NULL (4.4)
1752 if (in_array($token, self
::$_tokens[$entity])) {
1753 $value = $membership[$token];
1757 $value = "{$entity}.{$token}";
1762 if ($escapeSmarty) {
1763 $value = self
::tokenEscapeSmarty($value);
1770 * @param $contribution
1772 * @param bool $escapeSmarty
1774 * @return mixed|string
1776 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1777 self
::_buildContributionTokens();
1780 case 'total_amount':
1783 case 'non_deductible_amount':
1784 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1787 case 'receive_date':
1788 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1789 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1793 if (!in_array($token, self
::$_tokens['contribution'])) {
1794 $value = "{contribution.$token}";
1797 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1802 if ($escapeSmarty) {
1803 $value = self
::tokenEscapeSmarty($value);
1810 * legacy_token => new_token
1812 public static function legacyContactTokens() {
1814 'individual_prefix' => 'prefix_id',
1815 'individual_suffix' => 'suffix_id',
1816 'gender' => 'gender_id',
1817 'communication_style' => 'communication_style_id',
1822 * Formats a token list for the select2 widget
1826 public static function formatTokensForDisplay($tokens) {
1827 $sorted = $output = array();
1829 // Sort in ascending order by ignoring word case
1830 natcasesort($tokens);
1832 // Attempt to place tokens into optgroups
1833 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1834 foreach ($tokens as $k => $v) {
1835 // Check to see if this token is already in a group e.g. for custom fields
1836 $split = explode(' :: ', $v);
1837 if (!empty($split[1])) {
1838 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1842 $split = explode('.', trim($k, '{}'));
1843 if (isset($split[1])) {
1844 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1847 $entity = 'Contact';
1849 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1854 foreach ($sorted as $k => $v) {
1855 $output[] = array('text' => $k, 'children' => $v);