3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Class to abstract token replacement
39 class CRM_Utils_Token
{
40 static $_requiredTokens = NULL;
42 static $_tokens = array(
69 // we extract the stuff after the role / permission and return the
70 // civicrm email addresses of all users with that role / permission
71 // useful with rules integration
75 // populate this dynamically
77 // populate this dynamically
78 'contribution' => NULL,
87 'subscribe' => array('group'),
88 'unsubscribe' => array('group'),
89 'resubscribe' => array('group'),
90 'welcome' => array('group'),
94 * Check a string (mailing body) for required tokens.
99 * @return true|array true if all required tokens are found,
100 * else an array of the missing tokens
103 public static function requiredTokens(&$str) {
104 if (self
::$_requiredTokens == NULL) {
105 self
::$_requiredTokens = array(
106 'domain.address' => ts("Domain address - displays your organization's postal address."),
107 'action.optOutUrl or action.unsubscribeUrl' => array(
108 'action.optOut' => ts("'Opt out via email' - displays an email address for recipients to opt out of receiving emails from your organization."),
109 'action.optOutUrl' => ts("'Opt out via web page' - creates a link for recipients to click if they want to opt out of receiving emails from your organization. Alternatively, you can include the 'Opt out via email' token."),
110 'action.unsubscribe' => ts("'Unsubscribe via email' - displays an email address for recipients to unsubscribe from the specific mailing list used to send this message."),
111 'action.unsubscribeUrl' => ts("'Unsubscribe via web page' - creates a link for recipients to unsubscribe from the specific mailing list used to send this message. Alternatively, you can include the 'Unsubscribe via email' token or one of the Opt-out tokens."),
117 foreach (self
::$_requiredTokens as $token => $value) {
118 if (!is_array($value)) {
119 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
120 $missing[$token] = $value;
126 foreach ($value as $t => $d) {
128 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
133 $missing[$token] = $desc;
138 if (empty($missing)) {
145 * Wrapper for token matching
147 * @param string $type
148 * The token type (domain,mailing,contact,action).
150 * The token variable.
152 * The string to search.
158 public static function token_match($type, $var, &$str) {
159 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
160 return preg_match("/(^|[^\{])$token/", $str);
164 * Wrapper for token replacing
166 * @param string $type
169 * The token variable.
170 * @param string $value
171 * The value to substitute for the token.
172 * @param string (reference) $str The string to replace in
174 * @param bool $escapeSmarty
177 * The processed string
180 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
181 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
186 $value = self
::tokenEscapeSmarty($value);
188 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
193 * Get< the regex for token replacement
195 * @param string $token_type
196 * A string indicating the the type of token to be used in the expression.
199 * regular expression sutiable for using in preg_replace
202 private static function tokenRegex($token_type) {
203 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
207 * Escape the string so a malicious user cannot inject smarty code into the template
209 * @param string $string
210 * A string that needs to be escaped from smarty parsing.
216 private static function tokenEscapeSmarty($string) {
217 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
218 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
222 * Replace all the domain-level tokens in $str
225 * The string with tokens to be replaced.
226 * @param object $domain
229 * Replace tokens with HTML or plain text.
231 * @param null $knownTokens
232 * @param bool $escapeSmarty
235 * The processed string
238 public static function &replaceDomainTokens(
243 $escapeSmarty = FALSE
247 !$knownTokens ||
empty($knownTokens[$key])) {
251 $str = preg_replace_callback(
252 self
::tokenRegex($key),
253 function ($matches) use(&$domain, $html, $escapeSmarty) {
254 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
265 * @param bool $escapeSmarty
267 * @return mixed|null|string
269 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
270 // check if the token we were passed is valid
271 // we have to do this because this function is
272 // called only when we find a token in the string
274 $loc = &$domain->getLocationValues();
276 if (!in_array($token, self
::$_tokens['domain'])) {
277 $value = "{domain.$token}";
279 elseif ($token == 'address') {
280 static $addressCache = array();
282 $cache_key = $html ?
'address-html' : 'address-text';
283 if (array_key_exists($cache_key, $addressCache)) {
284 return $addressCache[$cache_key];
288 /* Construct the address token */
290 if (!empty($loc[$token])) {
292 $value = $loc[$token][1]['display'];
293 $value = str_replace("\n", '<br />', $value);
296 $value = $loc[$token][1]['display_text'];
298 $addressCache[$cache_key] = $value;
301 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
302 $value = $domain->$token;
304 elseif ($token == 'phone' ||
$token == 'email') {
305 /* Construct the phone and email tokens */
308 if (!empty($loc[$token])) {
309 foreach ($loc[$token] as $index => $entity) {
310 $value = $entity[$token];
317 $value = self
::tokenEscapeSmarty($value);
324 * Replace all the org-level tokens in $str
327 * The string with tokens to be replaced.
329 * Associative array of org properties.
331 * Replace tokens with HTML or plain text.
333 * @param bool $escapeSmarty
336 * The processed string
339 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
340 self
::$_tokens['org'] =
342 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
343 array('address', 'display_name', 'checksum', 'contact_id')
347 foreach (self
::$_tokens['org'] as $token) {
348 // print "Getting token value for $token<br/><br/>";
353 /* If the string doesn't contain this token, skip it. */
355 if (!self
::token_match('org', $token, $str)) {
359 /* Construct value from $token and $contact */
363 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
364 // only generate cv if we need it
366 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
368 foreach ($cv as $cvFieldID => $value) {
369 if ($cvFieldID == $cfID) {
370 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
375 elseif ($token == 'checksum') {
376 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
379 elseif ($token == 'address') {
380 /* Build the location values array */
383 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
384 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
385 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
386 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
387 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
389 /* Construct the address token */
391 $value = CRM_Utils_Address
::format($loc);
393 $value = str_replace("\n", '<br />', $value);
397 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
400 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
407 * Replace all mailing tokens in $str
410 * The string with tokens to be replaced.
411 * @param object $mailing
412 * The mailing BAO, or null for validation.
414 * Replace tokens with HTML or plain text.
416 * @param null $knownTokens
417 * @param bool $escapeSmarty
420 * The processed sstring
423 public static function &replaceMailingTokens(
428 $escapeSmarty = FALSE
431 if (!$knownTokens ||
!isset($knownTokens[$key])) {
435 $str = preg_replace_callback(
436 self
::tokenRegex($key),
437 function ($matches) use(&$mailing, $escapeSmarty) {
438 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
448 * @param bool $escapeSmarty
452 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
458 $value = $mailing ?
$mailing->id
: 'undefined';
462 $value = $mailing ?
$mailing->name
: 'Mailing Name';
466 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
467 $value = implode(', ', $groups);
471 $value = $mailing->subject
;
475 $mailingKey = $mailing->id
;
476 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
479 $value = CRM_Utils_System
::url('civicrm/mailing/view',
480 "reset=1&id={$mailingKey}",
481 TRUE, NULL, FALSE, TRUE
486 $value = CRM_Utils_System
::url('civicrm/mailing/send',
487 "reset=1&mid={$mailing->id}&continue=true",
488 TRUE, NULL, FALSE, TRUE
493 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
494 "reset=1&mid={$mailing->id}",
495 TRUE, NULL, FALSE, TRUE
500 $page = new CRM_Mailing_Page_View();
501 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
504 case 'approvalStatus':
505 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
509 $value = $mailing->approval_note
;
513 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
514 "reset=1&mid={$mailing->id}",
515 TRUE, NULL, FALSE, TRUE
520 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
524 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
528 $value = "{mailing.$token}";
533 $value = self
::tokenEscapeSmarty($value);
539 * Replace all action tokens in $str
542 * The string with tokens to be replaced.
543 * @param array $addresses
544 * Assoc. array of VERP event addresses.
546 * Assoc. array of action URLs.
548 * Replace tokens with HTML or plain text.
549 * @param array $knownTokens
550 * A list of tokens that are known to exist in the email body.
552 * @param bool $escapeSmarty
555 * The processed string
558 public static function &replaceActionTokens(
564 $escapeSmarty = FALSE
567 // here we intersect with the list of pre-configured valid tokens
568 // so that we remove anything we do not recognize
569 // I hope to move this step out of here soon and
570 // then we will just iterate on a list of tokens that are passed to us
571 if (!$knownTokens ||
empty($knownTokens[$key])) {
575 $str = preg_replace_callback(
576 self
::tokenRegex($key),
577 function ($matches) use(&$addresses, &$urls, $html, $escapeSmarty) {
578 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
590 * @param bool $escapeSmarty
592 * @return mixed|string
594 public static function getActionTokenReplacement(
599 $escapeSmarty = FALSE
601 /* If the token is an email action, use it. Otherwise, find the
604 if (!in_array($token, self
::$_tokens['action'])) {
605 $value = "{action.$token}";
608 $value = CRM_Utils_Array
::value($token, $addresses);
610 if ($value == NULL) {
611 $value = CRM_Utils_Array
::value($token, $urls);
614 if ($value && $html) {
616 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
617 $value = "mailto:$value";
620 elseif ($value && !$html) {
621 $value = str_replace('&', '&', $value);
626 $value = self
::tokenEscapeSmarty($value);
632 * Replace all the contact-level tokens in $str with information from
636 * The string with tokens to be replaced.
637 * @param array $contact
638 * Associative array of contact properties.
640 * Replace tokens with HTML or plain text.
641 * @param array $knownTokens
642 * A list of tokens that are known to exist in the email body.
643 * @param bool $returnBlankToken
644 * Return unevaluated token if value is null.
646 * @param bool $escapeSmarty
649 * The processed string
652 public static function &replaceContactTokens(
657 $returnBlankToken = FALSE,
658 $escapeSmarty = FALSE
661 if (self
::$_tokens[$key] == NULL) {
662 /* This should come from UF */
664 self
::$_tokens[$key] =
666 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
667 array('checksum', 'contact_id')
671 // here we intersect with the list of pre-configured valid tokens
672 // so that we remove anything we do not recognize
673 // I hope to move this step out of here soon and
674 // then we will just iterate on a list of tokens that are passed to us
675 if (!$knownTokens ||
empty($knownTokens[$key])) {
679 $str = preg_replace_callback(
680 self
::tokenRegex($key),
681 function ($matches) use(&$contact, $html, $returnBlankToken, $escapeSmarty) {
682 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
687 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
695 * @param bool $returnBlankToken
696 * @param bool $escapeSmarty
698 * @return bool|mixed|null|string
700 public static function getContactTokenReplacement(
704 $returnBlankToken = FALSE,
705 $escapeSmarty = FALSE
707 if (self
::$_tokens['contact'] == NULL) {
708 /* This should come from UF */
710 self
::$_tokens['contact'] =
712 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
713 array('checksum', 'contact_id')
717 /* Construct value from $token and $contact */
722 // Support legacy tokens
723 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
725 // check if the token we were passed is valid
726 // we have to do this because this function is
727 // called only when we find a token in the string
729 if (!in_array($token, self
::$_tokens['contact'])) {
732 elseif ($token == 'checksum') {
733 $hash = CRM_Utils_Array
::value('hash', $contact);
734 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
735 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
743 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
745 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
746 if (is_array($value)) {
749 // Convert pseudoconstants using metadata
750 elseif ($value && is_numeric($value)) {
751 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
752 if (!empty($allFields[$token]['pseudoconstant'])) {
753 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
759 $value = str_replace('&', '&', $value);
762 // if null then return actual token
763 if ($returnBlankToken && !$value) {
768 $value = "{contact.$token}";
772 && !($returnBlankToken && $noReplace)) { // $returnBlankToken means the caller wants to do further attempts at processing unreplaced tokens -- so don't escape them yet in this case.
773 $value = self
::tokenEscapeSmarty($value);
780 * Replace all the hook tokens in $str with information from
784 * The string with tokens to be replaced.
785 * @param array $contact
786 * Associative array of contact properties (including hook token values).
789 * Replace tokens with HTML or plain text.
791 * @param bool $escapeSmarty
794 * The processed string
797 public static function &replaceHookTokens(
802 $escapeSmarty = FALSE
804 foreach ($categories as $key) {
805 $str = preg_replace_callback(
806 self
::tokenRegex($key),
807 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
808 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
817 * Parse html through Smarty resolving any smarty functions
818 * @param string $tokenHtml
819 * @param array $entity
820 * @param string $entityType
822 * html parsed through smarty
824 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
825 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
826 $smarty = CRM_Core_Smarty
::singleton();
827 // also add the tokens to the template
828 $smarty->assign_by_ref($entityType, $entity);
829 $tokenHtml = $smarty->fetch("string:$tokenHtml");
839 * @param bool $escapeSmarty
841 * @return mixed|string
843 public static function getHookTokenReplacement(
848 $escapeSmarty = FALSE
850 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
852 if ($value && !$html) {
853 $value = str_replace('&', '&', $value);
857 $value = self
::tokenEscapeSmarty($value);
864 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
865 * for example {{token}} or \{token} will result in {token} in the final email
867 * this routine will remove the extra backslashes and braces
869 * @param $str ref to the string that will be scanned and modified
871 * this function works directly on the string that is passed
875 public static function unescapeTokens(&$str) {
876 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
880 * Replace unsubscribe tokens
883 * The string with tokens to be replaced.
884 * @param object $domain
886 * @param array $groups
887 * The groups (if any) being unsubscribed.
889 * Replace tokens with html or plain text.
890 * @param int $contact_id
892 * @param string hash The security hash of the unsub event
895 * The processed string
898 public static function &replaceUnsubscribeTokens(
906 if (self
::token_match('unsubscribe', 'group', $str)) {
907 if (!empty($groups)) {
908 $config = CRM_Core_Config
::singleton();
909 $base = CRM_Utils_System
::baseURL();
911 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
912 $dao = new CRM_Contact_DAO_Group();
914 while ($dao->fetch()) {
915 if (substr($dao->visibility
, 0, 6) == 'Public') {
916 $visibleGroups[] = $dao->id
;
919 $value = implode(', ', $groups);
920 self
::token_replace('unsubscribe', 'group', $value, $str);
927 * Replace resubscribe tokens
930 * The string with tokens to be replaced.
931 * @param object $domain
933 * @param array $groups
934 * The groups (if any) being resubscribed.
936 * Replace tokens with html or plain text.
937 * @param int $contact_id
939 * @param string hash The security hash of the resub event
942 * The processed string
945 public static function &replaceResubscribeTokens(
946 $str, &$domain, &$groups, $html,
949 if (self
::token_match('resubscribe', 'group', $str)) {
950 if (!empty($groups)) {
951 $value = implode(', ', $groups);
952 self
::token_replace('resubscribe', 'group', $value, $str);
959 * Replace subscription-confirmation-request tokens
962 * The string with tokens to be replaced.
963 * @param string $group
964 * The name of the group being subscribed.
967 * Replace tokens with html or plain text.
970 * The processed string
973 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
974 if (self
::token_match('subscribe', 'group', $str)) {
975 self
::token_replace('subscribe', 'group', $group, $str);
977 if (self
::token_match('subscribe', 'url', $str)) {
978 self
::token_replace('subscribe', 'url', $url, $str);
984 * Replace subscription-invitation tokens
987 * The string with tokens to be replaced.
990 * The processed string
993 public static function &replaceSubscribeInviteTokens($str) {
994 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
995 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
997 TRUE, NULL, TRUE, TRUE
999 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
1002 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
1003 foreach ($matches as $key => $value) {
1004 $gid = substr($value, 21, -1);
1005 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
1006 "reset=1&gid={$gid}",
1007 TRUE, NULL, TRUE, TRUE
1009 $url = str_replace('&', '&', $url);
1010 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
1014 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
1015 foreach ($matches as $key => $value) {
1016 $gid = substr($value, 18, -1);
1017 $config = CRM_Core_Config
::singleton();
1018 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
1019 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1020 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1021 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1028 * Replace welcome/confirmation tokens
1030 * @param string $str
1031 * The string with tokens to be replaced.
1032 * @param string $group
1033 * The name of the group being subscribed.
1035 * Replace tokens with html or plain text.
1038 * The processed string
1041 public static function &replaceWelcomeTokens($str, $group, $html) {
1042 if (self
::token_match('welcome', 'group', $str)) {
1043 self
::token_replace('welcome', 'group', $group, $str);
1049 * Find unprocessed tokens (call this last)
1051 * @param string $str
1052 * The string to search.
1055 * Array of tokens that weren't replaced
1058 public static function &unmatchedTokens(&$str) {
1059 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1060 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1065 * Find and replace tokens for each component
1067 * @param string $str
1068 * The string to search.
1069 * @param array $contact
1070 * Associative array of contact properties.
1071 * @param array $components
1072 * A list of tokens that are known to exist in the email body.
1074 * @param bool $escapeSmarty
1075 * @param bool $returnEmptyToken
1078 * The processed string
1081 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1082 if (!is_array($components) ||
empty($contact)) {
1086 foreach ($components as $name => $tokens) {
1087 if (!is_array($tokens) ||
empty($tokens)) {
1091 foreach ($tokens as $token) {
1092 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1093 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1095 elseif (!$returnEmptyToken) {
1096 //replacing empty token
1097 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1105 * Get array of string tokens
1107 * @param string $string
1108 * The input string to parse for tokens.
1111 * array of tokens mentioned in field
1115 public static function getTokens($string) {
1118 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1125 foreach ($matches[1] as $token) {
1126 list($type, $name) = preg_split('/\./', $token, 2);
1127 if ($name && $type) {
1128 if (!isset($tokens[$type])) {
1129 $tokens[$type] = array();
1131 $tokens[$type][] = $name;
1139 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1140 * and getTokens appears to be historical rather than intentional and should be reviewed
1143 * fields to pass in as return properties when populating token
1145 public static function getReturnProperties(&$string) {
1146 $returnProperties = array();
1148 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1154 foreach ($matches[1] as $token) {
1155 list($type, $name) = preg_split('/\./', $token, 2);
1157 $returnProperties["{$name}"] = 1;
1162 return $returnProperties;
1166 * Gives required details of contacts in an indexed array format so we
1167 * can iterate in a nice loop and do token evaluation
1169 * @param $contactIDs
1170 * @param array $returnProperties
1171 * Of required properties.
1172 * @param bool $skipOnHoldDon't return on_hold contact info also.
1173 * Don't return on_hold contact info also.
1174 * @param bool $skipDeceasedDon't return deceased contact info.
1175 * Don't return deceased contact info.
1176 * @param array $extraParams
1178 * @param array $tokens
1179 * The list of tokens we've extracted from the content.
1180 * @param null $className
1182 * The mailing list jobID - this is a legacy param.
1187 static function getTokenDetails(
1189 $returnProperties = NULL,
1191 $skipDeceased = TRUE,
1192 $extraParams = NULL,
1197 if (empty($contactIDs)) {
1198 // putting a fatal here so we can track if/when this happens
1199 CRM_Core_Error
::fatal();
1203 foreach ($contactIDs as $key => $contactID) {
1205 CRM_Core_Form
::CB_PREFIX
. $contactID,
1211 if ($skipDeceased) {
1212 $params[] = array('is_deceased', '=', 0, 0, 0);
1217 $params[] = array('on_hold', '=', 0, 0, 0);
1221 $params = array_merge($params, $extraParams);
1224 // if return properties are not passed then get all return properties
1225 if (empty($returnProperties)) {
1226 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1227 array('display_name', 'checksum', 'contact_id')
1229 foreach ($fields as $key => $val) {
1230 $returnProperties[$val] = 1;
1235 foreach ($returnProperties as $name => $dontCare) {
1236 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1242 //get the total number of contacts to fetch from database.
1243 $numberofContacts = count($contactIDs);
1244 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1246 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1248 $contactDetails = &$details[0];
1250 foreach ($contactIDs as $key => $contactID) {
1251 if (array_key_exists($contactID, $contactDetails)) {
1252 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1253 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1255 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1257 // communication Prefferance
1258 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1259 $contactDetails[$contactID]['preferred_communication_method']
1262 foreach ($contactPcm as $key => $val) {
1264 $result[$val] = $pcm[$val];
1267 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1270 foreach ($custom as $cfID) {
1271 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1272 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1278 //special case for greeting replacement
1280 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1281 if (!empty($contactDetails[$contactID][$val])) {
1282 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1288 // also call a hook and get token details
1289 CRM_Utils_Hook
::tokenValues($details[0],
1299 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1300 * specific tokens to be rendered
1302 * @param array $contactIDs
1303 * This should always be array(0) or its not anonymous - left to keep signature same.
1305 * @param string $returnProperties
1306 * @param bool $skipOnHold
1307 * @param bool $skipDeceased
1308 * @param string $extraParams
1309 * @param array $tokens
1310 * @param string $className
1311 * Sent as context to the hook.
1312 * @param string $jobID
1314 * contactDetails with hooks swapped out
1316 public function getAnonymousTokenDetails($contactIDs = array(
1318 $returnProperties = NULL,
1320 $skipDeceased = TRUE,
1321 $extraParams = NULL,
1325 $details = array(0 => array());
1326 // also call a hook and get token details
1327 CRM_Utils_Hook
::tokenValues($details[0],
1337 * Gives required details of contribuion in an indexed array format so we
1338 * can iterate in a nice loop and do token evaluation
1340 * @param array $contributionIDs
1341 * @param array $returnProperties
1342 * Of required properties.
1343 * @param array $extraParams
1345 * @param array $tokens
1346 * The list of tokens we've extracted from the content.
1347 * @param string $className
1352 static function getContributionTokenDetails(
1354 $returnProperties = NULL,
1355 $extraParams = NULL,
1359 //@todo - this function basically replications calling civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1360 if (empty($contributionIDs)) {
1361 // putting a fatal here so we can track if/when this happens
1362 CRM_Core_Error
::fatal();
1367 // no apiQuery helper yet, so do a loop and find contribution by id
1368 foreach ($contributionIDs as $contributionID) {
1370 $dao = new CRM_Contribute_DAO_Contribution();
1371 $dao->id
= $contributionID;
1373 if ($dao->find(TRUE)) {
1375 $details[$dao->id
] = array();
1376 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1378 // do the necessary transformation
1379 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1380 $piId = $details[$dao->id
]['payment_instrument_id'];
1381 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1382 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1384 if (!empty($details[$dao->id
]['campaign_id'])) {
1385 $campaignId = $details[$dao->id
]['campaign_id'];
1386 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1387 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1390 if (!empty($details[$dao->id
]['financial_type_id'])) {
1391 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1392 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1393 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1396 // TODO: call a hook to get token contribution details
1404 * Get Membership Token Details
1405 * @param array $membershipIDs
1406 * Array of membership IDS.
1408 public static function getMembershipTokenDetails($membershipIDs) {
1409 $memberships = civicrm_api3('membership', 'get', array('options' => array('limit' => 200000), 'membership_id' => array('IN' => (array) $membershipIDs)));
1410 return $memberships['values'];
1413 * Replace greeting tokens exists in message/subject
1415 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1417 if (!$contactDetails && !$contactId) {
1421 // check if there are any tokens
1422 $greetingTokens = self
::getTokens($tokenString);
1424 if (!empty($greetingTokens)) {
1425 // first use the existing contact object for token replacement
1426 if (!empty($contactDetails)) {
1427 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1430 // check if there are any unevaluated tokens
1431 $greetingTokens = self
::getTokens($tokenString);
1433 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1434 // so retrieve it from database
1435 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1436 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1437 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1438 $contactParams = array('contact_id' => $contactId);
1440 $greetingDetails = self
::getTokenDetails($contactParams,
1441 $greetingsReturnProperties,
1447 // again replace tokens
1448 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1457 // check if there are still any unevaluated tokens
1458 $remainingTokens = self
::getTokens($tokenString);
1460 // contact related $greetingTokens not empty, there are customized or hook tokens to replace
1461 if (!empty($remainingTokens['contact'])) {
1462 // Fill the return properties array
1463 $greetingTokens = $remainingTokens['contact'];
1464 reset($greetingTokens);
1465 $greetingsReturnProperties = array();
1466 while (list($key) = each($greetingTokens)) {
1467 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1468 $props = array_fill_keys(array_keys($props), 1);
1469 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1471 $contactParams = array('contact_id' => $contactId);
1472 $greetingDetails = self
::getTokenDetails($contactParams,
1473 $greetingsReturnProperties,
1478 // Prepare variables for calling replaceHookTokens
1479 $categories = array_keys($greetingTokens);
1480 list($contact) = $greetingDetails;
1481 // Replace tokens defined in Hooks.
1482 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1492 public static function flattenTokens(&$tokens) {
1493 $flattenTokens = array();
1496 'html', 'text', 'subject') as $prop) {
1497 if (!isset($tokens[$prop])) {
1500 foreach ($tokens[$prop] as $type => $names) {
1501 if (!isset($flattenTokens[$type])) {
1502 $flattenTokens[$type] = array();
1504 foreach ($names as $name) {
1505 $flattenTokens[$type][$name] = 1;
1510 return $flattenTokens;
1514 * Replace all user tokens in $str
1516 * @param string $str
1517 * The string with tokens to be replaced.
1519 * @param null $knownTokens
1520 * @param bool $escapeSmarty
1523 * The processed string
1526 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1528 if (!$knownTokens ||
1529 !isset($knownTokens[$key])
1534 $str = preg_replace_callback(
1535 self
::tokenRegex($key),
1536 function ($matches) use($escapeSmarty) {
1537 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1546 * @param bool $escapeSmarty
1550 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1553 list($objectName, $objectValue) = explode('-', $token, 2);
1555 switch ($objectName) {
1557 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1561 $value = CRM_Core_Permission
::roleEmails($objectValue);
1565 if ($escapeSmarty) {
1566 $value = self
::tokenEscapeSmarty($value);
1574 protected static function _buildContributionTokens() {
1575 $key = 'contribution';
1576 if (self
::$_tokens[$key] == NULL) {
1577 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1578 array('campaign', 'financial_type')
1584 * Store membership tokens on the static _tokens array
1586 protected static function _buildMembershipTokens() {
1587 $key = 'membership';
1588 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1589 $membershipTokens = array();
1590 $tokens = CRM_Core_SelectValues
::membershipTokens();
1591 foreach ($tokens as $token => $dontCare) {
1592 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1594 self
::$_tokens[$key] = $membershipTokens;
1599 * Replace tokens for an entity
1600 * @param string $entity
1601 * @param array $entityArray
1602 * (e.g. in format from api).
1603 * @param string $str
1604 * String to replace in.
1605 * @param array $knownTokens
1606 * Array of tokens present.
1607 * @param bool $escapeSmarty
1609 * string with replacements made
1611 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1612 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1616 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1617 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1618 foreach ($knownTokens[$entity] as $token) {
1619 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1620 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1622 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1627 * Replace Contribution tokens in html
1629 * @param string $str
1630 * @param array $contribution
1631 * @param bool|string $html
1632 * @param string $knownTokens
1633 * @param bool|string $escapeSmarty
1635 * @return unknown|Ambigous <string, mixed>|mixed
1637 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1638 $key = 'contribution';
1639 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1640 return $str; //early return
1642 self
::_buildContributionTokens();
1644 // here we intersect with the list of pre-configured valid tokens
1645 // so that we remove anything we do not recognize
1646 // I hope to move this step out of here soon and
1647 // then we will just iterate on a list of tokens that are passed to us
1649 $str = preg_replace_callback(
1650 self
::tokenRegex($key),
1651 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1652 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1657 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1662 * We have a situation where we are rendering more than one token in each field because we are combining
1663 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1665 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1666 * it applies (other tokens are OK including date fields)
1668 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1669 * does - but the fields is already being formatted through a date function
1671 * @param string $separator
1672 * @param string $str
1673 * @param array $contribution
1674 * @param bool|string $html
1675 * @param string $knownTokens
1676 * @param bool|string $escapeSmarty
1678 * @return \Ambigous|mixed|string|\unknown
1680 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1681 if (empty($knownTokens['contribution'])) {
1685 if (in_array('receive_date', $knownTokens['contribution'])) {
1686 $formattedDates = array();
1687 $dates = explode($separator, $contribution['receive_date']);
1688 foreach ($dates as $date) {
1689 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1691 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1692 unset($knownTokens['contribution']['receive_date']);
1694 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1698 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1699 * - this is used by the pdfLetter task from membership search
1700 * @param string $token
1701 * @param array $membership
1702 * An api result array for a single membership.
1703 * @param bool $escapeSmarty
1707 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1708 $entity = 'membership';
1709 self
::_buildMembershipTokens();
1712 $value = $membership['membership_name'];
1716 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1717 $value = $statuses[$membership['status_id']];
1722 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1724 catch (CiviCRM_API3_Exception
$e) {
1725 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1726 // api handles NULL (4.4)
1732 if (in_array($token, self
::$_tokens[$entity])) {
1733 $value = $membership[$token];
1737 $value = "{$entity}.{$token}";
1742 if ($escapeSmarty) {
1743 $value = self
::tokenEscapeSmarty($value);
1750 * @param $contribution
1752 * @param bool $escapeSmarty
1754 * @return mixed|string
1756 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1757 self
::_buildContributionTokens();
1760 case 'total_amount':
1763 case 'non_deductible_amount':
1764 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1767 case 'receive_date':
1768 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1769 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1773 if (!in_array($token, self
::$_tokens['contribution'])) {
1774 $value = "{contribution.$token}";
1777 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1782 if ($escapeSmarty) {
1783 $value = self
::tokenEscapeSmarty($value);
1790 * legacy_token => new_token
1792 public static function legacyContactTokens() {
1794 'individual_prefix' => 'prefix_id',
1795 'individual_suffix' => 'suffix_id',
1796 'gender' => 'gender_id',
1797 'communication_style' => 'communication_style_id',
1802 * Formats a token list for the select2 widget
1806 public static function formatTokensForDisplay($tokens) {
1807 $sorted = $output = array();
1809 // Sort in ascending order by ignoring word case
1810 natcasesort($tokens);
1812 // Attempt to place tokens into optgroups
1813 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1814 foreach ($tokens as $k => $v) {
1815 // Check to see if this token is already in a group e.g. for custom fields
1816 $split = explode(' :: ', $v);
1817 if (!empty($split[1])) {
1818 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1822 $split = explode('.', trim($k, '{}'));
1823 if (isset($split[1])) {
1824 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1827 $entity = 'Contact';
1829 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1834 foreach ($sorted as $k => $v) {
1835 $output[] = array('text' => $k, 'children' => $v);