3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Class to abstract token replacement
39 class CRM_Utils_Token
{
40 static $_requiredTokens = NULL;
42 static $_tokens = array(
69 // we extract the stuff after the role / permission and return the
70 // civicrm email addresses of all users with that role / permission
71 // useful with rules integration
75 // populate this dynamically
77 // populate this dynamically
78 'contribution' => NULL,
87 'subscribe' => array('group'),
88 'unsubscribe' => array('group'),
89 'resubscribe' => array('group'),
90 'welcome' => array('group'),
94 * Check a string (mailing body) for required tokens.
100 * true if all required tokens are found,
101 * else an array of the missing tokens
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.
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
176 * 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.
197 * 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.
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
231 * The processed string
233 public static function &replaceDomainTokens(
238 $escapeSmarty = FALSE
242 !$knownTokens ||
empty($knownTokens[$key])
247 $str = preg_replace_callback(
248 self
::tokenRegex($key),
249 function ($matches) use (&$domain, $html, $escapeSmarty) {
250 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
261 * @param bool $escapeSmarty
263 * @return mixed|null|string
265 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
266 // check if the token we were passed is valid
267 // we have to do this because this function is
268 // called only when we find a token in the string
270 $loc = &$domain->getLocationValues();
272 if (!in_array($token, self
::$_tokens['domain'])) {
273 $value = "{domain.$token}";
275 elseif ($token == 'address') {
276 static $addressCache = array();
278 $cache_key = $html ?
'address-html' : 'address-text';
279 if (array_key_exists($cache_key, $addressCache)) {
280 return $addressCache[$cache_key];
284 /* Construct the address token */
286 if (!empty($loc[$token])) {
288 $value = $loc[$token][1]['display'];
289 $value = str_replace("\n", '<br />', $value);
292 $value = $loc[$token][1]['display_text'];
294 $addressCache[$cache_key] = $value;
297 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
298 $value = $domain->$token;
300 elseif ($token == 'phone' ||
$token == 'email') {
301 /* Construct the phone and email tokens */
304 if (!empty($loc[$token])) {
305 foreach ($loc[$token] as $index => $entity) {
306 $value = $entity[$token];
313 $value = self
::tokenEscapeSmarty($value);
320 * Replace all the org-level tokens in $str
323 * The string with tokens to be replaced.
325 * Associative array of org properties.
327 * Replace tokens with HTML or plain text.
329 * @param bool $escapeSmarty
332 * The processed string
334 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
335 self
::$_tokens['org'] =
337 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
338 array('address', 'display_name', 'checksum', 'contact_id')
342 foreach (self
::$_tokens['org'] as $token) {
343 // print "Getting token value for $token<br/><br/>";
348 /* If the string doesn't contain this token, skip it. */
350 if (!self
::token_match('org', $token, $str)) {
354 /* Construct value from $token and $contact */
358 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
359 // only generate cv if we need it
361 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
363 foreach ($cv as $cvFieldID => $value) {
364 if ($cvFieldID == $cfID) {
365 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
370 elseif ($token == 'checksum') {
371 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
374 elseif ($token == 'address') {
375 /* Build the location values array */
378 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
379 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
380 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
381 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
382 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
384 /* Construct the address token */
386 $value = CRM_Utils_Address
::format($loc);
388 $value = str_replace("\n", '<br />', $value);
392 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
395 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
402 * Replace all mailing tokens in $str
405 * The string with tokens to be replaced.
406 * @param object $mailing
407 * The mailing BAO, or null for validation.
409 * Replace tokens with HTML or plain text.
411 * @param null $knownTokens
412 * @param bool $escapeSmarty
415 * The processed sstring
417 public static function &replaceMailingTokens(
422 $escapeSmarty = FALSE
425 if (!$knownTokens ||
!isset($knownTokens[$key])) {
429 $str = preg_replace_callback(
430 self
::tokenRegex($key),
431 function ($matches) use (&$mailing, $escapeSmarty) {
432 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
442 * @param bool $escapeSmarty
446 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
452 $value = $mailing ?
$mailing->id
: 'undefined';
456 $value = $mailing ?
$mailing->name
: 'Mailing Name';
460 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
461 $value = implode(', ', $groups);
465 $value = $mailing->subject
;
469 $mailingKey = $mailing->id
;
470 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
473 $value = CRM_Utils_System
::url('civicrm/mailing/view',
474 "reset=1&id={$mailingKey}",
475 TRUE, NULL, FALSE, TRUE
480 $value = CRM_Utils_System
::url('civicrm/mailing/send',
481 "reset=1&mid={$mailing->id}&continue=true",
482 TRUE, NULL, FALSE, TRUE
487 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
488 "reset=1&mid={$mailing->id}",
489 TRUE, NULL, FALSE, TRUE
494 $page = new CRM_Mailing_Page_View();
495 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
498 case 'approvalStatus':
499 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
503 $value = $mailing->approval_note
;
507 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
508 "reset=1&mid={$mailing->id}",
509 TRUE, NULL, FALSE, TRUE
514 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
518 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
522 $value = "{mailing.$token}";
527 $value = self
::tokenEscapeSmarty($value);
533 * Replace all action tokens in $str
536 * The string with tokens to be replaced.
537 * @param array $addresses
538 * Assoc. array of VERP event addresses.
540 * Assoc. array of action URLs.
542 * Replace tokens with HTML or plain text.
543 * @param array $knownTokens
544 * A list of tokens that are known to exist in the email body.
546 * @param bool $escapeSmarty
549 * The processed string
551 public static function &replaceActionTokens(
557 $escapeSmarty = FALSE
560 // here we intersect with the list of pre-configured valid tokens
561 // so that we remove anything we do not recognize
562 // I hope to move this step out of here soon and
563 // then we will just iterate on a list of tokens that are passed to us
564 if (!$knownTokens ||
empty($knownTokens[$key])) {
568 $str = preg_replace_callback(
569 self
::tokenRegex($key),
570 function ($matches) use (&$addresses, &$urls, $html, $escapeSmarty) {
571 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
583 * @param bool $escapeSmarty
585 * @return mixed|string
587 public static function getActionTokenReplacement(
592 $escapeSmarty = FALSE
594 /* If the token is an email action, use it. Otherwise, find the
597 if (!in_array($token, self
::$_tokens['action'])) {
598 $value = "{action.$token}";
601 $value = CRM_Utils_Array
::value($token, $addresses);
603 if ($value == NULL) {
604 $value = CRM_Utils_Array
::value($token, $urls);
607 if ($value && $html) {
609 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
610 $value = "mailto:$value";
613 elseif ($value && !$html) {
614 $value = str_replace('&', '&', $value);
619 $value = self
::tokenEscapeSmarty($value);
625 * Replace all the contact-level tokens in $str with information from
629 * The string with tokens to be replaced.
630 * @param array $contact
631 * Associative array of contact properties.
633 * Replace tokens with HTML or plain text.
634 * @param array $knownTokens
635 * A list of tokens that are known to exist in the email body.
636 * @param bool $returnBlankToken
637 * Return unevaluated token if value is null.
639 * @param bool $escapeSmarty
642 * The processed string
644 public static function &replaceContactTokens(
649 $returnBlankToken = FALSE,
650 $escapeSmarty = FALSE
653 if (self
::$_tokens[$key] == NULL) {
654 /* This should come from UF */
656 self
::$_tokens[$key] =
658 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
659 array('checksum', 'contact_id')
663 // here we intersect with the list of pre-configured valid tokens
664 // so that we remove anything we do not recognize
665 // I hope to move this step out of here soon and
666 // then we will just iterate on a list of tokens that are passed to us
667 if (!$knownTokens ||
empty($knownTokens[$key])) {
671 $str = preg_replace_callback(
672 self
::tokenRegex($key),
673 function ($matches) use (&$contact, $html, $returnBlankToken, $escapeSmarty) {
674 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
679 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
687 * @param bool $returnBlankToken
688 * @param bool $escapeSmarty
690 * @return bool|mixed|null|string
692 public static function getContactTokenReplacement(
696 $returnBlankToken = FALSE,
697 $escapeSmarty = FALSE
699 if (self
::$_tokens['contact'] == NULL) {
700 /* This should come from UF */
702 self
::$_tokens['contact'] =
704 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
705 array('checksum', 'contact_id')
709 /* Construct value from $token and $contact */
714 // Support legacy tokens
715 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
717 // check if the token we were passed is valid
718 // we have to do this because this function is
719 // called only when we find a token in the string
721 if (!in_array($token, self
::$_tokens['contact'])) {
724 elseif ($token == 'checksum') {
725 $hash = CRM_Utils_Array
::value('hash', $contact);
726 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
727 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
735 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
737 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
738 if (is_array($value)) {
741 // Convert pseudoconstants using metadata
742 elseif ($value && is_numeric($value)) {
743 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
744 if (!empty($allFields[$token]['pseudoconstant'])) {
745 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
751 $value = str_replace('&', '&', $value);
754 // if null then return actual token
755 if ($returnBlankToken && !$value) {
760 $value = "{contact.$token}";
764 && !($returnBlankToken && $noReplace)
765 ) { // $returnBlankToken means the caller wants to do further attempts at processing unreplaced tokens -- so don't escape them yet in this case.
766 $value = self
::tokenEscapeSmarty($value);
773 * Replace all the hook tokens in $str with information from
777 * The string with tokens to be replaced.
778 * @param array $contact
779 * Associative array of contact properties (including hook token values).
782 * Replace tokens with HTML or plain text.
784 * @param bool $escapeSmarty
787 * The processed string
789 public static function &replaceHookTokens(
794 $escapeSmarty = FALSE
796 foreach ($categories as $key) {
797 $str = preg_replace_callback(
798 self
::tokenRegex($key),
799 function ($matches) use (&$contact, $key, $html, $escapeSmarty) {
800 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
809 * Parse html through Smarty resolving any smarty functions
810 * @param string $tokenHtml
811 * @param array $entity
812 * @param string $entityType
814 * html parsed through smarty
816 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
817 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
818 $smarty = CRM_Core_Smarty
::singleton();
819 // also add the tokens to the template
820 $smarty->assign_by_ref($entityType, $entity);
821 $tokenHtml = $smarty->fetch("string:$tokenHtml");
831 * @param bool $escapeSmarty
833 * @return mixed|string
835 public static function getHookTokenReplacement(
840 $escapeSmarty = FALSE
842 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
844 if ($value && !$html) {
845 $value = str_replace('&', '&', $value);
849 $value = self
::tokenEscapeSmarty($value);
856 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
857 * for example {{token}} or \{token} will result in {token} in the final email
859 * this routine will remove the extra backslashes and braces
861 * @param $str ref to the string that will be scanned and modified
863 * this function works directly on the string that is passed
865 public static function unescapeTokens(&$str) {
866 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
870 * Replace unsubscribe tokens
873 * The string with tokens to be replaced.
874 * @param object $domain
876 * @param array $groups
877 * The groups (if any) being unsubscribed.
879 * Replace tokens with html or plain text.
880 * @param int $contact_id
882 * @param string hash The security hash of the unsub event
885 * The processed string
887 public static function &replaceUnsubscribeTokens(
895 if (self
::token_match('unsubscribe', 'group', $str)) {
896 if (!empty($groups)) {
897 $config = CRM_Core_Config
::singleton();
898 $base = CRM_Utils_System
::baseURL();
900 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
901 $dao = new CRM_Contact_DAO_Group();
903 while ($dao->fetch()) {
904 if (substr($dao->visibility
, 0, 6) == 'Public') {
905 $visibleGroups[] = $dao->id
;
908 $value = implode(', ', $groups);
909 self
::token_replace('unsubscribe', 'group', $value, $str);
916 * Replace resubscribe tokens
919 * The string with tokens to be replaced.
920 * @param object $domain
922 * @param array $groups
923 * The groups (if any) being resubscribed.
925 * Replace tokens with html or plain text.
926 * @param int $contact_id
928 * @param string hash The security hash of the resub event
931 * The processed string
933 public static function &replaceResubscribeTokens(
934 $str, &$domain, &$groups, $html,
937 if (self
::token_match('resubscribe', 'group', $str)) {
938 if (!empty($groups)) {
939 $value = implode(', ', $groups);
940 self
::token_replace('resubscribe', 'group', $value, $str);
947 * Replace subscription-confirmation-request tokens
950 * The string with tokens to be replaced.
951 * @param string $group
952 * The name of the group being subscribed.
955 * Replace tokens with html or plain text.
958 * The processed string
960 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
961 if (self
::token_match('subscribe', 'group', $str)) {
962 self
::token_replace('subscribe', 'group', $group, $str);
964 if (self
::token_match('subscribe', 'url', $str)) {
965 self
::token_replace('subscribe', 'url', $url, $str);
971 * Replace subscription-invitation tokens
974 * The string with tokens to be replaced.
977 * The processed string
979 public static function &replaceSubscribeInviteTokens($str) {
980 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
981 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
983 TRUE, NULL, TRUE, TRUE
985 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
988 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
989 foreach ($matches as $key => $value) {
990 $gid = substr($value, 21, -1);
991 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
992 "reset=1&gid={$gid}",
993 TRUE, NULL, TRUE, TRUE
995 $url = str_replace('&', '&', $url);
996 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
1000 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
1001 foreach ($matches as $key => $value) {
1002 $gid = substr($value, 18, -1);
1003 $config = CRM_Core_Config
::singleton();
1004 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
1005 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1006 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1007 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1014 * Replace welcome/confirmation tokens
1016 * @param string $str
1017 * The string with tokens to be replaced.
1018 * @param string $group
1019 * The name of the group being subscribed.
1021 * Replace tokens with html or plain text.
1024 * The processed string
1026 public static function &replaceWelcomeTokens($str, $group, $html) {
1027 if (self
::token_match('welcome', 'group', $str)) {
1028 self
::token_replace('welcome', 'group', $group, $str);
1034 * Find unprocessed tokens (call this last)
1036 * @param string $str
1037 * The string to search.
1040 * Array of tokens that weren't replaced
1042 public static function &unmatchedTokens(&$str) {
1043 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1044 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1049 * Find and replace tokens for each component
1051 * @param string $str
1052 * The string to search.
1053 * @param array $contact
1054 * Associative array of contact properties.
1055 * @param array $components
1056 * A list of tokens that are known to exist in the email body.
1058 * @param bool $escapeSmarty
1059 * @param bool $returnEmptyToken
1062 * The processed string
1064 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1065 if (!is_array($components) ||
empty($contact)) {
1069 foreach ($components as $name => $tokens) {
1070 if (!is_array($tokens) ||
empty($tokens)) {
1074 foreach ($tokens as $token) {
1075 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1076 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1078 elseif (!$returnEmptyToken) {
1079 //replacing empty token
1080 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1088 * Get array of string tokens
1090 * @param string $string
1091 * The input string to parse for tokens.
1094 * array of tokens mentioned in field
1096 public static function getTokens($string) {
1099 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1106 foreach ($matches[1] as $token) {
1107 list($type, $name) = preg_split('/\./', $token, 2);
1108 if ($name && $type) {
1109 if (!isset($tokens[$type])) {
1110 $tokens[$type] = array();
1112 $tokens[$type][] = $name;
1120 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1121 * and getTokens appears to be historical rather than intentional and should be reviewed
1124 * fields to pass in as return properties when populating token
1126 public static function getReturnProperties(&$string) {
1127 $returnProperties = array();
1129 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1135 foreach ($matches[1] as $token) {
1136 list($type, $name) = preg_split('/\./', $token, 2);
1138 $returnProperties["{$name}"] = 1;
1143 return $returnProperties;
1147 * Gives required details of contacts in an indexed array format so we
1148 * can iterate in a nice loop and do token evaluation
1150 * @param $contactIDs
1151 * @param array $returnProperties
1152 * Of required properties.
1153 * @param bool $skipOnHoldDon 't return on_hold contact info also.
1154 * Don't return on_hold contact info also.
1155 * @param bool $skipDeceasedDon 't return deceased contact info.
1156 * Don't return deceased contact info.
1157 * @param array $extraParams
1159 * @param array $tokens
1160 * The list of tokens we've extracted from the content.
1161 * @param null $className
1163 * 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,
1194 if ($skipDeceased) {
1195 $params[] = array('is_deceased', '=', 0, 0, 0);
1200 $params[] = array('on_hold', '=', 0, 0, 0);
1204 $params = array_merge($params, $extraParams);
1207 // if return properties are not passed then get all return properties
1208 if (empty($returnProperties)) {
1209 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1210 array('display_name', 'checksum', 'contact_id')
1212 foreach ($fields as $key => $val) {
1213 $returnProperties[$val] = 1;
1218 foreach ($returnProperties as $name => $dontCare) {
1219 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1225 //get the total number of contacts to fetch from database.
1226 $numberofContacts = count($contactIDs);
1227 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1229 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1231 $contactDetails = &$details[0];
1233 foreach ($contactIDs as $key => $contactID) {
1234 if (array_key_exists($contactID, $contactDetails)) {
1235 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1236 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1238 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1240 // communication Prefferance
1241 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1242 $contactDetails[$contactID]['preferred_communication_method']
1245 foreach ($contactPcm as $key => $val) {
1247 $result[$val] = $pcm[$val];
1250 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1253 foreach ($custom as $cfID) {
1254 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1255 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1261 //special case for greeting replacement
1267 if (!empty($contactDetails[$contactID][$val])) {
1268 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1274 // also call a hook and get token details
1275 CRM_Utils_Hook
::tokenValues($details[0],
1285 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1286 * specific tokens to be rendered
1288 * @param array $contactIDs
1289 * This should always be array(0) or its not anonymous - left to keep signature same.
1291 * @param string $returnProperties
1292 * @param bool $skipOnHold
1293 * @param bool $skipDeceased
1294 * @param string $extraParams
1295 * @param array $tokens
1296 * @param string $className
1297 * Sent as context to the hook.
1298 * @param string $jobID
1300 * contactDetails with hooks swapped out
1302 public function getAnonymousTokenDetails($contactIDs = array(
1305 $returnProperties = NULL,
1307 $skipDeceased = TRUE,
1308 $extraParams = NULL,
1312 $details = array(0 => array());
1313 // also call a hook and get token details
1314 CRM_Utils_Hook
::tokenValues($details[0],
1324 * Gives required details of contribuion in an indexed array format so we
1325 * can iterate in a nice loop and do token evaluation
1327 * @param array $contributionIDs
1328 * @param array $returnProperties
1329 * Of required properties.
1330 * @param array $extraParams
1332 * @param array $tokens
1333 * The list of tokens we've extracted from the content.
1334 * @param string $className
1338 static function getContributionTokenDetails(
1340 $returnProperties = NULL,
1341 $extraParams = NULL,
1345 //@todo - this function basically replications calling civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1346 if (empty($contributionIDs)) {
1347 // putting a fatal here so we can track if/when this happens
1348 CRM_Core_Error
::fatal();
1353 // no apiQuery helper yet, so do a loop and find contribution by id
1354 foreach ($contributionIDs as $contributionID) {
1356 $dao = new CRM_Contribute_DAO_Contribution();
1357 $dao->id
= $contributionID;
1359 if ($dao->find(TRUE)) {
1361 $details[$dao->id
] = array();
1362 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1364 // do the necessary transformation
1365 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1366 $piId = $details[$dao->id
]['payment_instrument_id'];
1367 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1368 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1370 if (!empty($details[$dao->id
]['campaign_id'])) {
1371 $campaignId = $details[$dao->id
]['campaign_id'];
1372 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1373 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1376 if (!empty($details[$dao->id
]['financial_type_id'])) {
1377 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1378 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1379 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1382 // TODO: call a hook to get token contribution details
1390 * Get Membership Token Details
1391 * @param array $membershipIDs
1392 * Array of membership IDS.
1394 public static function getMembershipTokenDetails($membershipIDs) {
1395 $memberships = civicrm_api3('membership', 'get', array(
1396 'options' => array('limit' => 200000),
1397 'membership_id' => array('IN' => (array) $membershipIDs)
1399 return $memberships['values'];
1403 * Replace greeting tokens exists in message/subject
1405 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1407 if (!$contactDetails && !$contactId) {
1411 // check if there are any tokens
1412 $greetingTokens = self
::getTokens($tokenString);
1414 if (!empty($greetingTokens)) {
1415 // first use the existing contact object for token replacement
1416 if (!empty($contactDetails)) {
1417 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1420 // check if there are any unevaluated tokens
1421 $greetingTokens = self
::getTokens($tokenString);
1423 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1424 // so retrieve it from database
1425 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1426 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1427 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1428 $contactParams = array('contact_id' => $contactId);
1430 $greetingDetails = self
::getTokenDetails($contactParams,
1431 $greetingsReturnProperties,
1437 // again replace tokens
1438 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1447 // check if there are still any unevaluated tokens
1448 $remainingTokens = self
::getTokens($tokenString);
1450 // contact related $greetingTokens not empty, there are customized or hook tokens to replace
1451 if (!empty($remainingTokens['contact'])) {
1452 // Fill the return properties array
1453 $greetingTokens = $remainingTokens['contact'];
1454 reset($greetingTokens);
1455 $greetingsReturnProperties = array();
1456 while (list($key) = each($greetingTokens)) {
1457 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1458 $props = array_fill_keys(array_keys($props), 1);
1459 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1461 $contactParams = array('contact_id' => $contactId);
1462 $greetingDetails = self
::getTokenDetails($contactParams,
1463 $greetingsReturnProperties,
1468 // Prepare variables for calling replaceHookTokens
1469 $categories = array_keys($greetingTokens);
1470 list($contact) = $greetingDetails;
1471 // Replace tokens defined in Hooks.
1472 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1482 public static function flattenTokens(&$tokens) {
1483 $flattenTokens = array();
1490 if (!isset($tokens[$prop])) {
1493 foreach ($tokens[$prop] as $type => $names) {
1494 if (!isset($flattenTokens[$type])) {
1495 $flattenTokens[$type] = array();
1497 foreach ($names as $name) {
1498 $flattenTokens[$type][$name] = 1;
1503 return $flattenTokens;
1507 * Replace all user tokens in $str
1509 * @param string $str
1510 * The string with tokens to be replaced.
1512 * @param null $knownTokens
1513 * @param bool $escapeSmarty
1516 * The processed string
1518 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1520 if (!$knownTokens ||
1521 !isset($knownTokens[$key])
1526 $str = preg_replace_callback(
1527 self
::tokenRegex($key),
1528 function ($matches) use ($escapeSmarty) {
1529 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1538 * @param bool $escapeSmarty
1542 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1545 list($objectName, $objectValue) = explode('-', $token, 2);
1547 switch ($objectName) {
1549 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1553 $value = CRM_Core_Permission
::roleEmails($objectValue);
1557 if ($escapeSmarty) {
1558 $value = self
::tokenEscapeSmarty($value);
1566 protected static function _buildContributionTokens() {
1567 $key = 'contribution';
1568 if (self
::$_tokens[$key] == NULL) {
1569 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1570 array('campaign', 'financial_type')
1576 * Store membership tokens on the static _tokens array
1578 protected static function _buildMembershipTokens() {
1579 $key = 'membership';
1580 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1581 $membershipTokens = array();
1582 $tokens = CRM_Core_SelectValues
::membershipTokens();
1583 foreach ($tokens as $token => $dontCare) {
1584 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1586 self
::$_tokens[$key] = $membershipTokens;
1591 * Replace tokens for an entity
1592 * @param string $entity
1593 * @param array $entityArray
1594 * (e.g. in format from api).
1595 * @param string $str
1596 * String to replace in.
1597 * @param array $knownTokens
1598 * Array of tokens present.
1599 * @param bool $escapeSmarty
1601 * string with replacements made
1603 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1604 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1608 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1609 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1610 foreach ($knownTokens[$entity] as $token) {
1611 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1612 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1614 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1619 * Replace Contribution tokens in html
1621 * @param string $str
1622 * @param array $contribution
1623 * @param bool|string $html
1624 * @param string $knownTokens
1625 * @param bool|string $escapeSmarty
1629 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1630 $key = 'contribution';
1631 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1632 return $str; //early return
1634 self
::_buildContributionTokens();
1636 // here we intersect with the list of pre-configured valid tokens
1637 // so that we remove anything we do not recognize
1638 // I hope to move this step out of here soon and
1639 // then we will just iterate on a list of tokens that are passed to us
1641 $str = preg_replace_callback(
1642 self
::tokenRegex($key),
1643 function ($matches) use (&$contribution, $html, $escapeSmarty) {
1644 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1649 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1654 * We have a situation where we are rendering more than one token in each field because we are combining
1655 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1657 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1658 * it applies (other tokens are OK including date fields)
1660 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1661 * does - but the fields is already being formatted through a date function
1663 * @param string $separator
1664 * @param string $str
1665 * @param array $contribution
1666 * @param bool|string $html
1667 * @param string $knownTokens
1668 * @param bool|string $escapeSmarty
1670 * @return \Ambigous|mixed|string|\unknown
1672 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1673 if (empty($knownTokens['contribution'])) {
1677 if (in_array('receive_date', $knownTokens['contribution'])) {
1678 $formattedDates = array();
1679 $dates = explode($separator, $contribution['receive_date']);
1680 foreach ($dates as $date) {
1681 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1683 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1684 unset($knownTokens['contribution']['receive_date']);
1686 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1690 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1691 * - this is used by the pdfLetter task from membership search
1692 * @param string $token
1693 * @param array $membership
1694 * An api result array for a single membership.
1695 * @param bool $escapeSmarty
1699 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1700 $entity = 'membership';
1701 self
::_buildMembershipTokens();
1704 $value = $membership['membership_name'];
1708 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1709 $value = $statuses[$membership['status_id']];
1714 $value = civicrm_api3('membership_type', 'getvalue', array(
1715 'id' => $membership['membership_type_id'],
1716 'return' => 'minimum_fee'
1719 catch (CiviCRM_API3_Exception
$e) {
1720 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1721 // api handles NULL (4.4)
1727 if (in_array($token, self
::$_tokens[$entity])) {
1728 $value = $membership[$token];
1732 $value = "{$entity}.{$token}";
1737 if ($escapeSmarty) {
1738 $value = self
::tokenEscapeSmarty($value);
1745 * @param $contribution
1747 * @param bool $escapeSmarty
1749 * @return mixed|string
1751 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1752 self
::_buildContributionTokens();
1755 case 'total_amount':
1758 case 'non_deductible_amount':
1759 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1762 case 'receive_date':
1763 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1764 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1768 if (!in_array($token, self
::$_tokens['contribution'])) {
1769 $value = "{contribution.$token}";
1772 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1777 if ($escapeSmarty) {
1778 $value = self
::tokenEscapeSmarty($value);
1785 * legacy_token => new_token
1787 public static function legacyContactTokens() {
1789 'individual_prefix' => 'prefix_id',
1790 'individual_suffix' => 'suffix_id',
1791 'gender' => 'gender_id',
1792 'communication_style' => 'communication_style_id',
1797 * Formats a token list for the select2 widget
1801 public static function formatTokensForDisplay($tokens) {
1802 $sorted = $output = array();
1804 // Sort in ascending order by ignoring word case
1805 natcasesort($tokens);
1807 // Attempt to place tokens into optgroups
1808 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1809 foreach ($tokens as $k => $v) {
1810 // Check to see if this token is already in a group e.g. for custom fields
1811 $split = explode(' :: ', $v);
1812 if (!empty($split[1])) {
1813 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1817 $split = explode('.', trim($k, '{}'));
1818 if (isset($split[1])) {
1819 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1822 $entity = 'Contact';
1824 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1829 foreach ($sorted as $k => $v) {
1830 $output[] = array('text' => $k, 'children' => $v);