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@access public
1094 public static function getTokens($string) {
1097 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1104 foreach ($matches[1] as $token) {
1105 list($type, $name) = preg_split('/\./', $token, 2);
1106 if ($name && $type) {
1107 if (!isset($tokens[$type])) {
1108 $tokens[$type] = array();
1110 $tokens[$type][] = $name;
1118 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1119 * and getTokens appears to be historical rather than intentional and should be reviewed
1121 * @return array fields to pass in as return properties when populating token
1124 public static function getReturnProperties(&$string) {
1125 $returnProperties = array();
1127 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1133 foreach ($matches[1] as $token) {
1134 list($type, $name) = preg_split('/\./', $token, 2);
1136 $returnProperties["{$name}"] = 1;
1141 return $returnProperties;
1145 * Gives required details of contacts in an indexed array format so we
1146 * can iterate in a nice loop and do token evaluation
1148 * @param $contactIDs
1149 * @param array $returnProperties
1150 * Of required properties.
1151 * @param bool $skipOnHoldDon't return on_hold contact info also.
1152 * Don't return on_hold contact info also.
1153 * @param bool $skipDeceasedDon't return deceased contact info.
1154 * Don't return deceased contact info.
1155 * @param array $extraParams
1157 * @param array $tokens
1158 * The list of tokens we've extracted from the content.
1159 * @param null $className
1161 * The mailing list jobID - this is a legacy param.
1166 static function getTokenDetails(
1168 $returnProperties = NULL,
1170 $skipDeceased = TRUE,
1171 $extraParams = NULL,
1176 if (empty($contactIDs)) {
1177 // putting a fatal here so we can track if/when this happens
1178 CRM_Core_Error
::fatal();
1182 foreach ($contactIDs as $key => $contactID) {
1184 CRM_Core_Form
::CB_PREFIX
. $contactID,
1190 if ($skipDeceased) {
1191 $params[] = array('is_deceased', '=', 0, 0, 0);
1196 $params[] = array('on_hold', '=', 0, 0, 0);
1200 $params = array_merge($params, $extraParams);
1203 // if return properties are not passed then get all return properties
1204 if (empty($returnProperties)) {
1205 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1206 array('display_name', 'checksum', 'contact_id')
1208 foreach ($fields as $key => $val) {
1209 $returnProperties[$val] = 1;
1214 foreach ($returnProperties as $name => $dontCare) {
1215 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1221 //get the total number of contacts to fetch from database.
1222 $numberofContacts = count($contactIDs);
1223 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1225 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1227 $contactDetails = &$details[0];
1229 foreach ($contactIDs as $key => $contactID) {
1230 if (array_key_exists($contactID, $contactDetails)) {
1231 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1232 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1234 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1236 // communication Prefferance
1237 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1238 $contactDetails[$contactID]['preferred_communication_method']
1241 foreach ($contactPcm as $key => $val) {
1243 $result[$val] = $pcm[$val];
1246 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1249 foreach ($custom as $cfID) {
1250 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1251 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1257 //special case for greeting replacement
1259 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1260 if (!empty($contactDetails[$contactID][$val])) {
1261 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1267 // also call a hook and get token details
1268 CRM_Utils_Hook
::tokenValues($details[0],
1278 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1279 * specific tokens to be rendered
1281 * @param array $contactIDs
1282 * This should always be array(0) or its not anonymous - left to keep signature same.
1284 * @param string $returnProperties
1285 * @param bool $skipOnHold
1286 * @param bool $skipDeceased
1287 * @param string $extraParams
1288 * @param array $tokens
1289 * @param string $className
1290 * Sent as context to the hook.
1291 * @param string $jobID
1292 * @return array contactDetails with hooks swapped out
1294 public function getAnonymousTokenDetails($contactIDs = array(
1296 $returnProperties = NULL,
1298 $skipDeceased = TRUE,
1299 $extraParams = NULL,
1303 $details = array(0 => array());
1304 // also call a hook and get token details
1305 CRM_Utils_Hook
::tokenValues($details[0],
1315 * Gives required details of contribuion in an indexed array format so we
1316 * can iterate in a nice loop and do token evaluation
1318 * @param array $contributionIDs
1319 * @param array $returnProperties
1320 * Of required properties.
1321 * @param array $extraParams
1323 * @param array $tokens
1324 * The list of tokens we've extracted from the content.
1325 * @param string $className
1330 static function getContributionTokenDetails(
1332 $returnProperties = NULL,
1333 $extraParams = NULL,
1337 //@todo - this function basically replications calling civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1338 if (empty($contributionIDs)) {
1339 // putting a fatal here so we can track if/when this happens
1340 CRM_Core_Error
::fatal();
1345 // no apiQuery helper yet, so do a loop and find contribution by id
1346 foreach ($contributionIDs as $contributionID) {
1348 $dao = new CRM_Contribute_DAO_Contribution();
1349 $dao->id
= $contributionID;
1351 if ($dao->find(TRUE)) {
1353 $details[$dao->id
] = array();
1354 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1356 // do the necessary transformation
1357 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1358 $piId = $details[$dao->id
]['payment_instrument_id'];
1359 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1360 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1362 if (!empty($details[$dao->id
]['campaign_id'])) {
1363 $campaignId = $details[$dao->id
]['campaign_id'];
1364 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1365 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1368 if (!empty($details[$dao->id
]['financial_type_id'])) {
1369 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1370 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1371 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1374 // TODO: call a hook to get token contribution details
1382 * Get Membership Token Details
1383 * @param array $membershipIDs
1384 * Array of membership IDS.
1386 public static function getMembershipTokenDetails($membershipIDs) {
1387 $memberships = civicrm_api3('membership', 'get', array('options' => array('limit' => 200000), 'membership_id' => array('IN' => (array) $membershipIDs)));
1388 return $memberships['values'];
1391 * Replace greeting tokens exists in message/subject
1394 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1396 if (!$contactDetails && !$contactId) {
1400 // check if there are any tokens
1401 $greetingTokens = self
::getTokens($tokenString);
1403 if (!empty($greetingTokens)) {
1404 // first use the existing contact object for token replacement
1405 if (!empty($contactDetails)) {
1406 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1409 // check if there are any unevaluated tokens
1410 $greetingTokens = self
::getTokens($tokenString);
1412 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1413 // so retrieve it from database
1414 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1415 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1416 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1417 $contactParams = array('contact_id' => $contactId);
1419 $greetingDetails = self
::getTokenDetails($contactParams,
1420 $greetingsReturnProperties,
1426 // again replace tokens
1427 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1436 // check if there are still any unevaluated tokens
1437 $remainingTokens = self
::getTokens($tokenString);
1439 // contact related $greetingTokens not empty, there are customized or hook tokens to replace
1440 if (!empty($remainingTokens['contact'])) {
1441 // Fill the return properties array
1442 $greetingTokens = $remainingTokens['contact'];
1443 reset($greetingTokens);
1444 $greetingsReturnProperties = array();
1445 while (list($key) = each($greetingTokens)) {
1446 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1447 $props = array_fill_keys(array_keys($props), 1);
1448 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1450 $contactParams = array('contact_id' => $contactId);
1451 $greetingDetails = self
::getTokenDetails($contactParams,
1452 $greetingsReturnProperties,
1457 // Prepare variables for calling replaceHookTokens
1458 $categories = array_keys($greetingTokens);
1459 list($contact) = $greetingDetails;
1460 // Replace tokens defined in Hooks.
1461 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1471 public static function flattenTokens(&$tokens) {
1472 $flattenTokens = array();
1475 'html', 'text', 'subject') as $prop) {
1476 if (!isset($tokens[$prop])) {
1479 foreach ($tokens[$prop] as $type => $names) {
1480 if (!isset($flattenTokens[$type])) {
1481 $flattenTokens[$type] = array();
1483 foreach ($names as $name) {
1484 $flattenTokens[$type][$name] = 1;
1489 return $flattenTokens;
1493 * Replace all user tokens in $str
1495 * @param string $str
1496 * The string with tokens to be replaced.
1498 * @param null $knownTokens
1499 * @param bool $escapeSmarty
1501 * @return string The processed string
1504 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1506 if (!$knownTokens ||
1507 !isset($knownTokens[$key])
1512 $str = preg_replace_callback(
1513 self
::tokenRegex($key),
1514 function ($matches) use($escapeSmarty) {
1515 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1524 * @param bool $escapeSmarty
1528 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1531 list($objectName, $objectValue) = explode('-', $token, 2);
1533 switch ($objectName) {
1535 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1539 $value = CRM_Core_Permission
::roleEmails($objectValue);
1543 if ($escapeSmarty) {
1544 $value = self
::tokenEscapeSmarty($value);
1553 protected static function _buildContributionTokens() {
1554 $key = 'contribution';
1555 if (self
::$_tokens[$key] == NULL) {
1556 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1557 array('campaign', 'financial_type')
1563 * Store membership tokens on the static _tokens array
1565 protected static function _buildMembershipTokens() {
1566 $key = 'membership';
1567 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1568 $membershipTokens = array();
1569 $tokens = CRM_Core_SelectValues
::membershipTokens();
1570 foreach ($tokens as $token => $dontCare) {
1571 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1573 self
::$_tokens[$key] = $membershipTokens;
1578 * Replace tokens for an entity
1579 * @param string $entity
1580 * @param array $entityArray
1581 * (e.g. in format from api).
1582 * @param string $str
1583 * String to replace in.
1584 * @param array $knownTokens
1585 * Array of tokens present.
1586 * @param bool $escapeSmarty
1587 * @return string string with replacements made
1589 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1590 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1594 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1595 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1596 foreach ($knownTokens[$entity] as $token) {
1597 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1598 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1600 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1605 * Replace Contribution tokens in html
1607 * @param string $str
1608 * @param array $contribution
1609 * @param bool|string $html
1610 * @param string $knownTokens
1611 * @param bool|string $escapeSmarty
1613 * @return unknown|Ambigous <string, mixed>|mixed
1615 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1616 $key = 'contribution';
1617 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1618 return $str; //early return
1620 self
::_buildContributionTokens();
1622 // here we intersect with the list of pre-configured valid tokens
1623 // so that we remove anything we do not recognize
1624 // I hope to move this step out of here soon and
1625 // then we will just iterate on a list of tokens that are passed to us
1627 $str = preg_replace_callback(
1628 self
::tokenRegex($key),
1629 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1630 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1635 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1640 * We have a situation where we are rendering more than one token in each field because we are combining
1641 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1643 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1644 * it applies (other tokens are OK including date fields)
1646 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1647 * does - but the fields is already being formatted through a date function
1649 * @param string $separator
1650 * @param string $str
1651 * @param array $contribution
1652 * @param bool|string $html
1653 * @param string $knownTokens
1654 * @param bool|string $escapeSmarty
1656 * @return \Ambigous|mixed|string|\unknown
1658 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1659 if (empty($knownTokens['contribution'])) {
1663 if (in_array('receive_date', $knownTokens['contribution'])) {
1664 $formattedDates = array();
1665 $dates = explode($separator, $contribution['receive_date']);
1666 foreach ($dates as $date) {
1667 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1669 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1670 unset($knownTokens['contribution']['receive_date']);
1672 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1676 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1677 * - this is used by the pdfLetter task from membership search
1678 * @param string $token
1679 * @param array $membership
1680 * An api result array for a single membership.
1681 * @param bool $escapeSmarty
1682 * @return string token replacement
1684 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1685 $entity = 'membership';
1686 self
::_buildMembershipTokens();
1689 $value = $membership['membership_name'];
1693 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1694 $value = $statuses[$membership['status_id']];
1699 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1701 catch (CiviCRM_API3_Exception
$e) {
1702 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1703 // api handles NULL (4.4)
1709 if (in_array($token, self
::$_tokens[$entity])) {
1710 $value = $membership[$token];
1714 $value = "{$entity}.{$token}";
1719 if ($escapeSmarty) {
1720 $value = self
::tokenEscapeSmarty($value);
1727 * @param $contribution
1729 * @param bool $escapeSmarty
1731 * @return mixed|string
1733 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1734 self
::_buildContributionTokens();
1737 case 'total_amount':
1740 case 'non_deductible_amount':
1741 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1744 case 'receive_date':
1745 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1746 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1750 if (!in_array($token, self
::$_tokens['contribution'])) {
1751 $value = "{contribution.$token}";
1754 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1759 if ($escapeSmarty) {
1760 $value = self
::tokenEscapeSmarty($value);
1766 * @return array: legacy_token => new_token
1768 public static function legacyContactTokens() {
1770 'individual_prefix' => 'prefix_id',
1771 'individual_suffix' => 'suffix_id',
1772 'gender' => 'gender_id',
1773 'communication_style' => 'communication_style_id',
1778 * Formats a token list for the select2 widget
1782 public static function formatTokensForDisplay($tokens) {
1783 $sorted = $output = array();
1785 // Sort in ascending order by ignoring word case
1786 natcasesort($tokens);
1788 // Attempt to place tokens into optgroups
1789 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1790 foreach ($tokens as $k => $v) {
1791 // Check to see if this token is already in a group e.g. for custom fields
1792 $split = explode(' :: ', $v);
1793 if (!empty($split[1])) {
1794 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1798 $split = explode('.', trim($k, '{}'));
1799 if (isset($split[1])) {
1800 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1803 $entity = 'Contact';
1805 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1810 foreach ($sorted as $k => $v) {
1811 $output[] = array('text' => $k, 'children' => $v);