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.
154 * @return boolean Was there a match
157 public static function token_match($type, $var, &$str) {
158 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
159 return preg_match("/(^|[^\{])$token/", $str);
163 * Wrapper for token replacing
165 * @param string $type
168 * The token variable.
169 * @param string $value
170 * The value to substitute for the token.
171 * @param string (reference) $str The string to replace in
173 * @param bool $escapeSmarty
175 * @return string The processed string
178 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
179 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
184 $value = self
::tokenEscapeSmarty($value);
186 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
191 * Get< the regex for token replacement
193 * @param string $token_type
194 * A string indicating the the type of token to be used in the expression.
196 * @return string regular expression sutiable for using in preg_replace
199 private static function tokenRegex($token_type) {
200 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
204 * Escape the string so a malicious user cannot inject smarty code into the template
206 * @param string $string
207 * A string that needs to be escaped from smarty parsing.
209 * @return string the escaped string
212 private static function tokenEscapeSmarty($string) {
213 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
214 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
218 * Replace all the domain-level tokens in $str
221 * The string with tokens to be replaced.
222 * @param object $domain
225 * Replace tokens with HTML or plain text.
227 * @param null $knownTokens
228 * @param bool $escapeSmarty
230 * @return string The processed string
233 public static function &replaceDomainTokens(
238 $escapeSmarty = FALSE
242 !$knownTokens ||
empty($knownTokens[$key])) {
246 $str = preg_replace_callback(
247 self
::tokenRegex($key),
248 function ($matches) use(&$domain, $html, $escapeSmarty) {
249 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
260 * @param bool $escapeSmarty
262 * @return mixed|null|string
264 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
265 // check if the token we were passed is valid
266 // we have to do this because this function is
267 // called only when we find a token in the string
269 $loc = &$domain->getLocationValues();
271 if (!in_array($token, self
::$_tokens['domain'])) {
272 $value = "{domain.$token}";
274 elseif ($token == 'address') {
275 static $addressCache = array();
277 $cache_key = $html ?
'address-html' : 'address-text';
278 if (array_key_exists($cache_key, $addressCache)) {
279 return $addressCache[$cache_key];
283 /* Construct the address token */
285 if (!empty($loc[$token])) {
287 $value = $loc[$token][1]['display'];
288 $value = str_replace("\n", '<br />', $value);
291 $value = $loc[$token][1]['display_text'];
293 $addressCache[$cache_key] = $value;
296 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
297 $value = $domain->$token;
299 elseif ($token == 'phone' ||
$token == 'email') {
300 /* Construct the phone and email tokens */
303 if (!empty($loc[$token])) {
304 foreach ($loc[$token] as $index => $entity) {
305 $value = $entity[$token];
312 $value = self
::tokenEscapeSmarty($value);
319 * Replace all the org-level tokens in $str
322 * The string with tokens to be replaced.
324 * Associative array of org properties.
326 * Replace tokens with HTML or plain text.
328 * @param bool $escapeSmarty
330 * @return string The processed string
333 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
334 self
::$_tokens['org'] =
336 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
337 array('address', 'display_name', 'checksum', 'contact_id')
341 foreach (self
::$_tokens['org'] as $token) {
342 // print "Getting token value for $token<br/><br/>";
347 /* If the string doesn't contain this token, skip it. */
349 if (!self
::token_match('org', $token, $str)) {
353 /* Construct value from $token and $contact */
357 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
358 // only generate cv if we need it
360 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
362 foreach ($cv as $cvFieldID => $value) {
363 if ($cvFieldID == $cfID) {
364 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
369 elseif ($token == 'checksum') {
370 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
373 elseif ($token == 'address') {
374 /* Build the location values array */
377 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
378 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
379 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
380 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
381 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
383 /* Construct the address token */
385 $value = CRM_Utils_Address
::format($loc);
387 $value = str_replace("\n", '<br />', $value);
391 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
394 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
401 * Replace all mailing tokens in $str
404 * The string with tokens to be replaced.
405 * @param object $mailing
406 * The mailing BAO, or null for validation.
408 * Replace tokens with HTML or plain text.
410 * @param null $knownTokens
411 * @param bool $escapeSmarty
413 * @return string The processed sstring
416 public static function &replaceMailingTokens(
421 $escapeSmarty = FALSE
424 if (!$knownTokens ||
!isset($knownTokens[$key])) {
428 $str = preg_replace_callback(
429 self
::tokenRegex($key),
430 function ($matches) use(&$mailing, $escapeSmarty) {
431 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
441 * @param bool $escapeSmarty
445 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
451 $value = $mailing ?
$mailing->id
: 'undefined';
455 $value = $mailing ?
$mailing->name
: 'Mailing Name';
459 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
460 $value = implode(', ', $groups);
464 $value = $mailing->subject
;
468 $mailingKey = $mailing->id
;
469 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
472 $value = CRM_Utils_System
::url('civicrm/mailing/view',
473 "reset=1&id={$mailingKey}",
474 TRUE, NULL, FALSE, TRUE
479 $value = CRM_Utils_System
::url('civicrm/mailing/send',
480 "reset=1&mid={$mailing->id}&continue=true",
481 TRUE, NULL, FALSE, TRUE
486 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
487 "reset=1&mid={$mailing->id}",
488 TRUE, NULL, FALSE, TRUE
493 $page = new CRM_Mailing_Page_View();
494 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
497 case 'approvalStatus':
498 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
502 $value = $mailing->approval_note
;
506 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
507 "reset=1&mid={$mailing->id}",
508 TRUE, NULL, FALSE, TRUE
513 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
517 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
521 $value = "{mailing.$token}";
526 $value = self
::tokenEscapeSmarty($value);
532 * Replace all action tokens in $str
535 * The string with tokens to be replaced.
536 * @param array $addresses
537 * Assoc. array of VERP event addresses.
539 * Assoc. array of action URLs.
541 * Replace tokens with HTML or plain text.
542 * @param array $knownTokens
543 * A list of tokens that are known to exist in the email body.
545 * @param bool $escapeSmarty
547 * @return string The processed string
550 public static function &replaceActionTokens(
556 $escapeSmarty = FALSE
559 // here we intersect with the list of pre-configured valid tokens
560 // so that we remove anything we do not recognize
561 // I hope to move this step out of here soon and
562 // then we will just iterate on a list of tokens that are passed to us
563 if (!$knownTokens ||
empty($knownTokens[$key])) {
567 $str = preg_replace_callback(
568 self
::tokenRegex($key),
569 function ($matches) use(&$addresses, &$urls, $html, $escapeSmarty) {
570 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
582 * @param bool $escapeSmarty
584 * @return mixed|string
586 public static function getActionTokenReplacement(
591 $escapeSmarty = FALSE
593 /* If the token is an email action, use it. Otherwise, find the
596 if (!in_array($token, self
::$_tokens['action'])) {
597 $value = "{action.$token}";
600 $value = CRM_Utils_Array
::value($token, $addresses);
602 if ($value == NULL) {
603 $value = CRM_Utils_Array
::value($token, $urls);
606 if ($value && $html) {
608 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
609 $value = "mailto:$value";
612 elseif ($value && !$html) {
613 $value = str_replace('&', '&', $value);
618 $value = self
::tokenEscapeSmarty($value);
624 * Replace all the contact-level tokens in $str with information from
628 * The string with tokens to be replaced.
629 * @param array $contact
630 * Associative array of contact properties.
632 * Replace tokens with HTML or plain text.
633 * @param array $knownTokens
634 * A list of tokens that are known to exist in the email body.
635 * @param bool $returnBlankToken
636 * Return unevaluated token if value is null.
638 * @param bool $escapeSmarty
640 * @return string The processed string
643 public static function &replaceContactTokens(
648 $returnBlankToken = FALSE,
649 $escapeSmarty = FALSE
652 if (self
::$_tokens[$key] == NULL) {
653 /* This should come from UF */
655 self
::$_tokens[$key] =
657 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
658 array('checksum', 'contact_id')
662 // here we intersect with the list of pre-configured valid tokens
663 // so that we remove anything we do not recognize
664 // I hope to move this step out of here soon and
665 // then we will just iterate on a list of tokens that are passed to us
666 if (!$knownTokens ||
empty($knownTokens[$key])) {
670 $str = preg_replace_callback(
671 self
::tokenRegex($key),
672 function ($matches) use(&$contact, $html, $returnBlankToken, $escapeSmarty) {
673 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
678 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
686 * @param bool $returnBlankToken
687 * @param bool $escapeSmarty
689 * @return bool|mixed|null|string
691 public static function getContactTokenReplacement(
695 $returnBlankToken = FALSE,
696 $escapeSmarty = FALSE
698 if (self
::$_tokens['contact'] == NULL) {
699 /* This should come from UF */
701 self
::$_tokens['contact'] =
703 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
704 array('checksum', 'contact_id')
708 /* Construct value from $token and $contact */
713 // Support legacy tokens
714 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
716 // check if the token we were passed is valid
717 // we have to do this because this function is
718 // called only when we find a token in the string
720 if (!in_array($token, self
::$_tokens['contact'])) {
723 elseif ($token == 'checksum') {
724 $hash = CRM_Utils_Array
::value('hash', $contact);
725 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
726 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
734 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
736 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
737 if (is_array($value)) {
740 // Convert pseudoconstants using metadata
741 elseif ($value && is_numeric($value)) {
742 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
743 if (!empty($allFields[$token]['pseudoconstant'])) {
744 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
750 $value = str_replace('&', '&', $value);
753 // if null then return actual token
754 if ($returnBlankToken && !$value) {
759 $value = "{contact.$token}";
763 && !($returnBlankToken && $noReplace)) { // $returnBlankToken means the caller wants to do further attempts at processing unreplaced tokens -- so don't escape them yet in this case.
764 $value = self
::tokenEscapeSmarty($value);
771 * Replace all the hook tokens in $str with information from
775 * The string with tokens to be replaced.
776 * @param array $contact
777 * Associative array of contact properties (including hook token values).
780 * Replace tokens with HTML or plain text.
782 * @param bool $escapeSmarty
784 * @return string The processed string
787 public static function &replaceHookTokens(
792 $escapeSmarty = FALSE
794 foreach ($categories as $key) {
795 $str = preg_replace_callback(
796 self
::tokenRegex($key),
797 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
798 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
807 * Parse html through Smarty resolving any smarty functions
808 * @param string $tokenHtml
809 * @param array $entity
810 * @param string $entityType
811 * @return string html parsed through smarty
813 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
814 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
815 $smarty = CRM_Core_Smarty
::singleton();
816 // also add the tokens to the template
817 $smarty->assign_by_ref($entityType, $entity);
818 $tokenHtml = $smarty->fetch("string:$tokenHtml");
828 * @param bool $escapeSmarty
830 * @return mixed|string
832 public static function getHookTokenReplacement(
837 $escapeSmarty = FALSE
839 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
841 if ($value && !$html) {
842 $value = str_replace('&', '&', $value);
846 $value = self
::tokenEscapeSmarty($value);
853 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
854 * for example {{token}} or \{token} will result in {token} in the final email
856 * this routine will remove the extra backslashes and braces
858 * @param $str ref to the string that will be scanned and modified
859 * @return void this function works directly on the string that is passed
863 public static function unescapeTokens(&$str) {
864 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
868 * Replace unsubscribe tokens
871 * The string with tokens to be replaced.
872 * @param object $domain
874 * @param array $groups
875 * The groups (if any) being unsubscribed.
877 * Replace tokens with html or plain text.
878 * @param int $contact_id
880 * @param string hash The security hash of the unsub event
882 * @return string The processed string
885 public static function &replaceUnsubscribeTokens(
893 if (self
::token_match('unsubscribe', 'group', $str)) {
894 if (!empty($groups)) {
895 $config = CRM_Core_Config
::singleton();
896 $base = CRM_Utils_System
::baseURL();
898 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
899 $dao = new CRM_Contact_DAO_Group();
901 while ($dao->fetch()) {
902 if (substr($dao->visibility
, 0, 6) == 'Public') {
903 $visibleGroups[] = $dao->id
;
906 $value = implode(', ', $groups);
907 self
::token_replace('unsubscribe', 'group', $value, $str);
914 * Replace resubscribe tokens
917 * The string with tokens to be replaced.
918 * @param object $domain
920 * @param array $groups
921 * The groups (if any) being resubscribed.
923 * Replace tokens with html or plain text.
924 * @param int $contact_id
926 * @param string hash The security hash of the resub event
928 * @return string The processed string
931 public static function &replaceResubscribeTokens(
932 $str, &$domain, &$groups, $html,
935 if (self
::token_match('resubscribe', 'group', $str)) {
936 if (!empty($groups)) {
937 $value = implode(', ', $groups);
938 self
::token_replace('resubscribe', 'group', $value, $str);
945 * Replace subscription-confirmation-request tokens
948 * The string with tokens to be replaced.
949 * @param string $group
950 * The name of the group being subscribed.
953 * Replace tokens with html or plain text.
955 * @return string The processed string
958 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
959 if (self
::token_match('subscribe', 'group', $str)) {
960 self
::token_replace('subscribe', 'group', $group, $str);
962 if (self
::token_match('subscribe', 'url', $str)) {
963 self
::token_replace('subscribe', 'url', $url, $str);
969 * Replace subscription-invitation tokens
972 * The string with tokens to be replaced.
974 * @return string The processed string
977 public static function &replaceSubscribeInviteTokens($str) {
978 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
979 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
981 TRUE, NULL, TRUE, TRUE
983 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
986 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
987 foreach ($matches as $key => $value) {
988 $gid = substr($value, 21, -1);
989 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
990 "reset=1&gid={$gid}",
991 TRUE, NULL, TRUE, TRUE
993 $url = str_replace('&', '&', $url);
994 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
998 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
999 foreach ($matches as $key => $value) {
1000 $gid = substr($value, 18, -1);
1001 $config = CRM_Core_Config
::singleton();
1002 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
1003 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1004 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1005 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1012 * Replace welcome/confirmation tokens
1014 * @param string $str
1015 * The string with tokens to be replaced.
1016 * @param string $group
1017 * The name of the group being subscribed.
1019 * Replace tokens with html or plain text.
1021 * @return string The processed string
1024 public static function &replaceWelcomeTokens($str, $group, $html) {
1025 if (self
::token_match('welcome', 'group', $str)) {
1026 self
::token_replace('welcome', 'group', $group, $str);
1032 * Find unprocessed tokens (call this last)
1034 * @param string $str
1035 * The string to search.
1037 * @return array Array of tokens that weren't replaced
1040 public static function &unmatchedTokens(&$str) {
1041 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1042 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1047 * Find and replace tokens for each component
1049 * @param string $str
1050 * The string to search.
1051 * @param array $contact
1052 * Associative array of contact properties.
1053 * @param array $components
1054 * A list of tokens that are known to exist in the email body.
1056 * @param bool $escapeSmarty
1057 * @param bool $returnEmptyToken
1059 * @return string The processed string
1062 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1063 if (!is_array($components) ||
empty($contact)) {
1067 foreach ($components as $name => $tokens) {
1068 if (!is_array($tokens) ||
empty($tokens)) {
1072 foreach ($tokens as $token) {
1073 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1074 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1076 elseif (!$returnEmptyToken) {
1077 //replacing empty token
1078 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1086 * Get array of string tokens
1088 * @param string $string
1089 * The input string to parse for tokens.
1091 * @return array $tokens array of tokens mentioned in field
1095 public static function getTokens($string) {
1098 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1105 foreach ($matches[1] as $token) {
1106 list($type, $name) = preg_split('/\./', $token, 2);
1107 if ($name && $type) {
1108 if (!isset($tokens[$type])) {
1109 $tokens[$type] = array();
1111 $tokens[$type][] = $name;
1119 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1120 * and getTokens appears to be historical rather than intentional and should be reviewed
1122 * @return array fields to pass in as return properties when populating token
1125 public static function getReturnProperties(&$string) {
1126 $returnProperties = array();
1128 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1134 foreach ($matches[1] as $token) {
1135 list($type, $name) = preg_split('/\./', $token, 2);
1137 $returnProperties["{$name}"] = 1;
1142 return $returnProperties;
1146 * Gives required details of contacts in an indexed array format so we
1147 * can iterate in a nice loop and do token evaluation
1149 * @param $contactIDs
1150 * @param array $returnProperties
1151 * Of required properties.
1152 * @param bool $skipOnHoldDon't return on_hold contact info also.
1153 * Don't return on_hold contact info also.
1154 * @param bool $skipDeceasedDon't return deceased contact info.
1155 * Don't return deceased contact info.
1156 * @param array $extraParams
1158 * @param array $tokens
1159 * The list of tokens we've extracted from the content.
1160 * @param null $className
1162 * The mailing list jobID - this is a legacy param.
1167 static function getTokenDetails(
1169 $returnProperties = NULL,
1171 $skipDeceased = TRUE,
1172 $extraParams = NULL,
1177 if (empty($contactIDs)) {
1178 // putting a fatal here so we can track if/when this happens
1179 CRM_Core_Error
::fatal();
1183 foreach ($contactIDs as $key => $contactID) {
1185 CRM_Core_Form
::CB_PREFIX
. $contactID,
1191 if ($skipDeceased) {
1192 $params[] = array('is_deceased', '=', 0, 0, 0);
1197 $params[] = array('on_hold', '=', 0, 0, 0);
1201 $params = array_merge($params, $extraParams);
1204 // if return properties are not passed then get all return properties
1205 if (empty($returnProperties)) {
1206 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1207 array('display_name', 'checksum', 'contact_id')
1209 foreach ($fields as $key => $val) {
1210 $returnProperties[$val] = 1;
1215 foreach ($returnProperties as $name => $dontCare) {
1216 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1222 //get the total number of contacts to fetch from database.
1223 $numberofContacts = count($contactIDs);
1224 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1226 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1228 $contactDetails = &$details[0];
1230 foreach ($contactIDs as $key => $contactID) {
1231 if (array_key_exists($contactID, $contactDetails)) {
1232 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1233 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1235 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1237 // communication Prefferance
1238 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1239 $contactDetails[$contactID]['preferred_communication_method']
1242 foreach ($contactPcm as $key => $val) {
1244 $result[$val] = $pcm[$val];
1247 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1250 foreach ($custom as $cfID) {
1251 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1252 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1258 //special case for greeting replacement
1260 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1261 if (!empty($contactDetails[$contactID][$val])) {
1262 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1268 // also call a hook and get token details
1269 CRM_Utils_Hook
::tokenValues($details[0],
1279 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1280 * specific tokens to be rendered
1282 * @param array $contactIDs
1283 * This should always be array(0) or its not anonymous - left to keep signature same.
1285 * @param string $returnProperties
1286 * @param bool $skipOnHold
1287 * @param bool $skipDeceased
1288 * @param string $extraParams
1289 * @param array $tokens
1290 * @param string $className
1291 * Sent as context to the hook.
1292 * @param string $jobID
1293 * @return array contactDetails with hooks swapped out
1295 public function getAnonymousTokenDetails($contactIDs = array(
1297 $returnProperties = NULL,
1299 $skipDeceased = TRUE,
1300 $extraParams = NULL,
1304 $details = array(0 => array());
1305 // also call a hook and get token details
1306 CRM_Utils_Hook
::tokenValues($details[0],
1316 * Gives required details of contribuion in an indexed array format so we
1317 * can iterate in a nice loop and do token evaluation
1319 * @param array $contributionIDs
1320 * @param array $returnProperties
1321 * Of required properties.
1322 * @param array $extraParams
1324 * @param array $tokens
1325 * The list of tokens we've extracted from the content.
1326 * @param string $className
1331 static function getContributionTokenDetails(
1333 $returnProperties = NULL,
1334 $extraParams = NULL,
1338 //@todo - this function basically replications calling civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1339 if (empty($contributionIDs)) {
1340 // putting a fatal here so we can track if/when this happens
1341 CRM_Core_Error
::fatal();
1346 // no apiQuery helper yet, so do a loop and find contribution by id
1347 foreach ($contributionIDs as $contributionID) {
1349 $dao = new CRM_Contribute_DAO_Contribution();
1350 $dao->id
= $contributionID;
1352 if ($dao->find(TRUE)) {
1354 $details[$dao->id
] = array();
1355 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1357 // do the necessary transformation
1358 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1359 $piId = $details[$dao->id
]['payment_instrument_id'];
1360 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1361 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1363 if (!empty($details[$dao->id
]['campaign_id'])) {
1364 $campaignId = $details[$dao->id
]['campaign_id'];
1365 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1366 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1369 if (!empty($details[$dao->id
]['financial_type_id'])) {
1370 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1371 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1372 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1375 // TODO: call a hook to get token contribution details
1383 * Get Membership Token Details
1384 * @param array $membershipIDs
1385 * Array of membership IDS.
1387 public static function getMembershipTokenDetails($membershipIDs) {
1388 $memberships = civicrm_api3('membership', 'get', array('options' => array('limit' => 200000), 'membership_id' => array('IN' => (array) $membershipIDs)));
1389 return $memberships['values'];
1392 * Replace greeting tokens exists in message/subject
1395 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1397 if (!$contactDetails && !$contactId) {
1401 // check if there are any tokens
1402 $greetingTokens = self
::getTokens($tokenString);
1404 if (!empty($greetingTokens)) {
1405 // first use the existing contact object for token replacement
1406 if (!empty($contactDetails)) {
1407 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1410 // check if there are any unevaluated tokens
1411 $greetingTokens = self
::getTokens($tokenString);
1413 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1414 // so retrieve it from database
1415 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1416 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1417 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1418 $contactParams = array('contact_id' => $contactId);
1420 $greetingDetails = self
::getTokenDetails($contactParams,
1421 $greetingsReturnProperties,
1427 // again replace tokens
1428 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1437 // check if there are still any unevaluated tokens
1438 $remainingTokens = self
::getTokens($tokenString);
1440 // contact related $greetingTokens not empty, there are customized or hook tokens to replace
1441 if (!empty($remainingTokens['contact'])) {
1442 // Fill the return properties array
1443 $greetingTokens = $remainingTokens['contact'];
1444 reset($greetingTokens);
1445 $greetingsReturnProperties = array();
1446 while (list($key) = each($greetingTokens)) {
1447 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1448 $props = array_fill_keys(array_keys($props), 1);
1449 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1451 $contactParams = array('contact_id' => $contactId);
1452 $greetingDetails = self
::getTokenDetails($contactParams,
1453 $greetingsReturnProperties,
1458 // Prepare variables for calling replaceHookTokens
1459 $categories = array_keys($greetingTokens);
1460 list($contact) = $greetingDetails;
1461 // Replace tokens defined in Hooks.
1462 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1472 public static function flattenTokens(&$tokens) {
1473 $flattenTokens = array();
1476 'html', 'text', 'subject') as $prop) {
1477 if (!isset($tokens[$prop])) {
1480 foreach ($tokens[$prop] as $type => $names) {
1481 if (!isset($flattenTokens[$type])) {
1482 $flattenTokens[$type] = array();
1484 foreach ($names as $name) {
1485 $flattenTokens[$type][$name] = 1;
1490 return $flattenTokens;
1494 * Replace all user tokens in $str
1496 * @param string $str
1497 * The string with tokens to be replaced.
1499 * @param null $knownTokens
1500 * @param bool $escapeSmarty
1502 * @return string The processed string
1505 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1507 if (!$knownTokens ||
1508 !isset($knownTokens[$key])
1513 $str = preg_replace_callback(
1514 self
::tokenRegex($key),
1515 function ($matches) use($escapeSmarty) {
1516 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1525 * @param bool $escapeSmarty
1529 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1532 list($objectName, $objectValue) = explode('-', $token, 2);
1534 switch ($objectName) {
1536 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1540 $value = CRM_Core_Permission
::roleEmails($objectValue);
1544 if ($escapeSmarty) {
1545 $value = self
::tokenEscapeSmarty($value);
1554 protected static function _buildContributionTokens() {
1555 $key = 'contribution';
1556 if (self
::$_tokens[$key] == NULL) {
1557 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1558 array('campaign', 'financial_type')
1564 * Store membership tokens on the static _tokens array
1566 protected static function _buildMembershipTokens() {
1567 $key = 'membership';
1568 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1569 $membershipTokens = array();
1570 $tokens = CRM_Core_SelectValues
::membershipTokens();
1571 foreach ($tokens as $token => $dontCare) {
1572 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1574 self
::$_tokens[$key] = $membershipTokens;
1579 * Replace tokens for an entity
1580 * @param string $entity
1581 * @param array $entityArray
1582 * (e.g. in format from api).
1583 * @param string $str
1584 * String to replace in.
1585 * @param array $knownTokens
1586 * Array of tokens present.
1587 * @param bool $escapeSmarty
1588 * @return string string with replacements made
1590 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1591 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1595 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1596 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1597 foreach ($knownTokens[$entity] as $token) {
1598 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1599 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1601 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1606 * Replace Contribution tokens in html
1608 * @param string $str
1609 * @param array $contribution
1610 * @param bool|string $html
1611 * @param string $knownTokens
1612 * @param bool|string $escapeSmarty
1614 * @return unknown|Ambigous <string, mixed>|mixed
1616 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1617 $key = 'contribution';
1618 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1619 return $str; //early return
1621 self
::_buildContributionTokens();
1623 // here we intersect with the list of pre-configured valid tokens
1624 // so that we remove anything we do not recognize
1625 // I hope to move this step out of here soon and
1626 // then we will just iterate on a list of tokens that are passed to us
1628 $str = preg_replace_callback(
1629 self
::tokenRegex($key),
1630 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1631 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1636 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1641 * We have a situation where we are rendering more than one token in each field because we are combining
1642 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1644 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1645 * it applies (other tokens are OK including date fields)
1647 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1648 * does - but the fields is already being formatted through a date function
1650 * @param string $separator
1651 * @param string $str
1652 * @param array $contribution
1653 * @param bool|string $html
1654 * @param string $knownTokens
1655 * @param bool|string $escapeSmarty
1657 * @return \Ambigous|mixed|string|\unknown
1659 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1660 if (empty($knownTokens['contribution'])) {
1664 if (in_array('receive_date', $knownTokens['contribution'])) {
1665 $formattedDates = array();
1666 $dates = explode($separator, $contribution['receive_date']);
1667 foreach ($dates as $date) {
1668 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1670 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1671 unset($knownTokens['contribution']['receive_date']);
1673 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1677 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1678 * - this is used by the pdfLetter task from membership search
1679 * @param string $token
1680 * @param array $membership
1681 * An api result array for a single membership.
1682 * @param bool $escapeSmarty
1683 * @return string token replacement
1685 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1686 $entity = 'membership';
1687 self
::_buildMembershipTokens();
1690 $value = $membership['membership_name'];
1694 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1695 $value = $statuses[$membership['status_id']];
1700 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1702 catch (CiviCRM_API3_Exception
$e) {
1703 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1704 // api handles NULL (4.4)
1710 if (in_array($token, self
::$_tokens[$entity])) {
1711 $value = $membership[$token];
1715 $value = "{$entity}.{$token}";
1720 if ($escapeSmarty) {
1721 $value = self
::tokenEscapeSmarty($value);
1728 * @param $contribution
1730 * @param bool $escapeSmarty
1732 * @return mixed|string
1734 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1735 self
::_buildContributionTokens();
1738 case 'total_amount':
1741 case 'non_deductible_amount':
1742 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1745 case 'receive_date':
1746 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1747 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1751 if (!in_array($token, self
::$_tokens['contribution'])) {
1752 $value = "{contribution.$token}";
1755 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1760 if ($escapeSmarty) {
1761 $value = self
::tokenEscapeSmarty($value);
1767 * @return array: legacy_token => new_token
1769 public static function legacyContactTokens() {
1771 'individual_prefix' => 'prefix_id',
1772 'individual_suffix' => 'suffix_id',
1773 'gender' => 'gender_id',
1774 'communication_style' => 'communication_style_id',
1779 * Formats a token list for the select2 widget
1783 public static function formatTokensForDisplay($tokens) {
1784 $sorted = $output = array();
1786 // Sort in ascending order by ignoring word case
1787 natcasesort($tokens);
1789 // Attempt to place tokens into optgroups
1790 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1791 foreach ($tokens as $k => $v) {
1792 // Check to see if this token is already in a group e.g. for custom fields
1793 $split = explode(' :: ', $v);
1794 if (!empty($split[1])) {
1795 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1799 $split = explode('.', trim($k, '{}'));
1800 if (isset($split[1])) {
1801 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1804 $entity = 'Contact';
1806 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1811 foreach ($sorted as $k => $v) {
1812 $output[] = array('text' => $k, 'children' => $v);