3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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-2015
35 * Class to abstract token replacement.
37 class CRM_Utils_Token
{
38 static $_requiredTokens = NULL;
40 static $_tokens = array(
67 // we extract the stuff after the role / permission and return the
68 // civicrm email addresses of all users with that role / permission
69 // useful with rules integration
73 // populate this dynamically
75 // populate this dynamically
76 'contribution' => NULL,
85 'subscribe' => array('group'),
86 'unsubscribe' => array('group'),
87 'resubscribe' => array('group'),
88 'welcome' => array('group'),
95 public static function getRequiredTokens() {
96 if (self
::$_requiredTokens == NULL) {
97 self
::$_requiredTokens = array(
98 'domain.address' => ts("Domain address - displays your organization's postal address."),
99 'action.optOutUrl or action.unsubscribeUrl' => array(
100 'action.optOut' => ts("'Opt out via email' - displays an email address for recipients to opt out of receiving emails from your organization."),
101 '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."),
102 'action.unsubscribe' => ts("'Unsubscribe via email' - displays an email address for recipients to unsubscribe from the specific mailing list used to send this message."),
103 '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."),
107 return self
::$_requiredTokens;
111 * Check a string (mailing body) for required tokens.
117 * true if all required tokens are found,
118 * else an array of the missing tokens
120 public static function requiredTokens(&$str) {
121 $requiredTokens = self
::getRequiredTokens();
124 foreach ($requiredTokens as $token => $value) {
125 if (!is_array($value)) {
126 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
127 $missing[$token] = $value;
133 foreach ($value as $t => $d) {
135 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
140 $missing[$token] = $desc;
145 if (empty($missing)) {
152 * Wrapper for token matching.
154 * @param string $type
155 * The token type (domain,mailing,contact,action).
157 * The token variable.
159 * The string to search.
164 public static function token_match($type, $var, &$str) {
165 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
166 return preg_match("/(^|[^\{])$token/", $str);
170 * Wrapper for token replacing.
172 * @param string $type
175 * The token variable.
176 * @param string $value
177 * The value to substitute for the token.
178 * @param string (reference) $str The string to replace in
180 * @param bool $escapeSmarty
183 * The processed string
185 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
186 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
191 $value = self
::tokenEscapeSmarty($value);
193 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
198 * Get< the regex for token replacement
200 * @param string $token_type
201 * A string indicating the the type of token to be used in the expression.
204 * regular expression sutiable for using in preg_replace
206 private static function tokenRegex($token_type) {
207 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
211 * Escape the string so a malicious user cannot inject smarty code into the template.
213 * @param string $string
214 * A string that needs to be escaped from smarty parsing.
219 public static function tokenEscapeSmarty($string) {
220 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
221 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
225 * Replace all the domain-level tokens in $str
228 * The string with tokens to be replaced.
229 * @param object $domain
232 * Replace tokens with HTML or plain text.
234 * @param null $knownTokens
235 * @param bool $escapeSmarty
238 * The processed string
240 public static function &replaceDomainTokens(
245 $escapeSmarty = FALSE
249 !$knownTokens ||
empty($knownTokens[$key])
254 $str = preg_replace_callback(
255 self
::tokenRegex($key),
256 function ($matches) use (&$domain, $html, $escapeSmarty) {
257 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
268 * @param bool $escapeSmarty
270 * @return mixed|null|string
272 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
273 // check if the token we were passed is valid
274 // we have to do this because this function is
275 // called only when we find a token in the string
277 $loc = &$domain->getLocationValues();
279 if (!in_array($token, self
::$_tokens['domain'])) {
280 $value = "{domain.$token}";
282 elseif ($token == 'address') {
283 static $addressCache = array();
285 $cache_key = $html ?
'address-html' : 'address-text';
286 if (array_key_exists($cache_key, $addressCache)) {
287 return $addressCache[$cache_key];
291 /* Construct the address token */
293 if (!empty($loc[$token])) {
295 $value = $loc[$token][1]['display'];
296 $value = str_replace("\n", '<br />', $value);
299 $value = $loc[$token][1]['display_text'];
301 $addressCache[$cache_key] = $value;
304 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
305 $value = $domain->$token;
307 elseif ($token == 'phone' ||
$token == 'email') {
308 /* Construct the phone and email tokens */
311 if (!empty($loc[$token])) {
312 foreach ($loc[$token] as $index => $entity) {
313 $value = $entity[$token];
320 $value = self
::tokenEscapeSmarty($value);
327 * Replace all the org-level tokens in $str
330 * The string with tokens to be replaced.
332 * Associative array of org properties.
334 * Replace tokens with HTML or plain text.
336 * @param bool $escapeSmarty
339 * The processed string
341 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
342 self
::$_tokens['org']
344 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
345 array('address', 'display_name', 'checksum', 'contact_id')
349 foreach (self
::$_tokens['org'] as $token) {
350 // print "Getting token value for $token<br/><br/>";
355 /* If the string doesn't contain this token, skip it. */
357 if (!self
::token_match('org', $token, $str)) {
361 /* Construct value from $token and $contact */
365 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
366 // only generate cv if we need it
368 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
370 foreach ($cv as $cvFieldID => $value) {
371 if ($cvFieldID == $cfID) {
372 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
377 elseif ($token == 'checksum') {
378 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
381 elseif ($token == 'address') {
382 /* Build the location values array */
385 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
386 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
387 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
388 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
389 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
391 /* Construct the address token */
393 $value = CRM_Utils_Address
::format($loc);
395 $value = str_replace("\n", '<br />', $value);
399 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
402 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
409 * Replace all mailing tokens in $str
412 * The string with tokens to be replaced.
413 * @param object $mailing
414 * The mailing BAO, or null for validation.
416 * Replace tokens with HTML or plain text.
418 * @param null $knownTokens
419 * @param bool $escapeSmarty
422 * The processed sstring
424 public static function &replaceMailingTokens(
429 $escapeSmarty = FALSE
432 if (!$knownTokens ||
!isset($knownTokens[$key])) {
436 $str = preg_replace_callback(
437 self
::tokenRegex($key),
438 function ($matches) use (&$mailing, $escapeSmarty) {
439 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
449 * @param bool $escapeSmarty
453 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
459 $value = $mailing ?
$mailing->id
: 'undefined';
463 $value = $mailing ?
$mailing->name
: 'Mailing Name';
467 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
468 $value = implode(', ', $groups);
472 $value = $mailing->subject
;
476 $mailingKey = $mailing->id
;
477 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
480 $value = CRM_Utils_System
::url('civicrm/mailing/view',
481 "reset=1&id={$mailingKey}",
482 TRUE, NULL, FALSE, TRUE
488 // Note: editUrl and scheduleUrl used to be different, but now there's
489 // one screen which can adapt based on permissions (in workflow mode).
490 $value = CRM_Utils_System
::url('civicrm/mailing/send',
491 "reset=1&mid={$mailing->id}&continue=true",
492 TRUE, NULL, FALSE, TRUE
497 $page = new CRM_Mailing_Page_View();
498 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
501 case 'approvalStatus':
502 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
506 $value = $mailing->approval_note
;
510 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
511 "reset=1&mid={$mailing->id}",
512 TRUE, NULL, FALSE, TRUE
517 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
521 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
525 $value = "{mailing.$token}";
530 $value = self
::tokenEscapeSmarty($value);
536 * Replace all action tokens in $str
539 * The string with tokens to be replaced.
540 * @param array $addresses
541 * Assoc. array of VERP event addresses.
543 * Assoc. array of action URLs.
545 * Replace tokens with HTML or plain text.
546 * @param array $knownTokens
547 * A list of tokens that are known to exist in the email body.
549 * @param bool $escapeSmarty
552 * The processed string
554 public static function &replaceActionTokens(
560 $escapeSmarty = FALSE
563 // here we intersect with the list of pre-configured valid tokens
564 // so that we remove anything we do not recognize
565 // I hope to move this step out of here soon and
566 // then we will just iterate on a list of tokens that are passed to us
567 if (!$knownTokens ||
empty($knownTokens[$key])) {
571 $str = preg_replace_callback(
572 self
::tokenRegex($key),
573 function ($matches) use (&$addresses, &$urls, $html, $escapeSmarty) {
574 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
586 * @param bool $escapeSmarty
588 * @return mixed|string
590 public static function getActionTokenReplacement(
595 $escapeSmarty = FALSE
597 /* If the token is an email action, use it. Otherwise, find the
600 if (!in_array($token, self
::$_tokens['action'])) {
601 $value = "{action.$token}";
604 $value = CRM_Utils_Array
::value($token, $addresses);
606 if ($value == NULL) {
607 $value = CRM_Utils_Array
::value($token, $urls);
610 if ($value && $html) {
612 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
613 $value = "mailto:$value";
616 elseif ($value && !$html) {
617 $value = str_replace('&', '&', $value);
622 $value = self
::tokenEscapeSmarty($value);
628 * Replace all the contact-level tokens in $str with information from
632 * The string with tokens to be replaced.
633 * @param array $contact
634 * Associative array of contact properties.
636 * Replace tokens with HTML or plain text.
637 * @param array $knownTokens
638 * A list of tokens that are known to exist in the email body.
639 * @param bool $returnBlankToken
640 * Return unevaluated token if value is null.
642 * @param bool $escapeSmarty
645 * The processed string
647 public static function &replaceContactTokens(
652 $returnBlankToken = FALSE,
653 $escapeSmarty = FALSE
656 if (self
::$_tokens[$key] == NULL) {
657 /* This should come from UF */
661 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
662 array('checksum', 'contact_id')
666 // here we intersect with the list of pre-configured valid tokens
667 // so that we remove anything we do not recognize
668 // I hope to move this step out of here soon and
669 // then we will just iterate on a list of tokens that are passed to us
670 if (!$knownTokens ||
empty($knownTokens[$key])) {
674 $str = preg_replace_callback(
675 self
::tokenRegex($key),
676 function ($matches) use (&$contact, $html, $returnBlankToken, $escapeSmarty) {
677 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
682 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
690 * @param bool $returnBlankToken
691 * @param bool $escapeSmarty
693 * @return bool|mixed|null|string
695 public static function getContactTokenReplacement(
699 $returnBlankToken = FALSE,
700 $escapeSmarty = FALSE
702 if (self
::$_tokens['contact'] == NULL) {
703 /* This should come from UF */
705 self
::$_tokens['contact']
707 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
708 array('checksum', 'contact_id')
712 /* Construct value from $token and $contact */
717 // Support legacy tokens
718 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
720 // check if the token we were passed is valid
721 // we have to do this because this function is
722 // called only when we find a token in the string
724 if (!in_array($token, self
::$_tokens['contact'])) {
727 elseif ($token == 'checksum') {
728 $hash = CRM_Utils_Array
::value('hash', $contact);
729 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
730 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
738 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
740 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
741 if (is_array($value)) {
744 // Convert pseudoconstants using metadata
745 elseif ($value && is_numeric($value)) {
746 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
747 if (!empty($allFields[$token]['pseudoconstant'])) {
748 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
754 $value = str_replace('&', '&', $value);
757 // if null then return actual token
758 if ($returnBlankToken && !$value) {
763 $value = "{contact.$token}";
767 && !($returnBlankToken && $noReplace)
769 // $returnBlankToken means the caller wants to do further attempts at
770 // processing unreplaced tokens -- so don't escape them yet in this case.
771 $value = self
::tokenEscapeSmarty($value);
778 * Replace all the hook tokens in $str with information from
782 * The string with tokens to be replaced.
783 * @param array $contact
784 * Associative array of contact properties (including hook token values).
787 * Replace tokens with HTML or plain text.
789 * @param bool $escapeSmarty
792 * The processed string
794 public static function &replaceHookTokens(
799 $escapeSmarty = FALSE
801 foreach ($categories as $key) {
802 $str = preg_replace_callback(
803 self
::tokenRegex($key),
804 function ($matches) use (&$contact, $key, $html, $escapeSmarty) {
805 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
814 * Parse html through Smarty resolving any smarty functions.
815 * @param string $tokenHtml
816 * @param array $entity
817 * @param string $entityType
819 * html parsed through smarty
821 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
822 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
823 $smarty = CRM_Core_Smarty
::singleton();
824 // also add the tokens to the template
825 $smarty->assign_by_ref($entityType, $entity);
826 $tokenHtml = $smarty->fetch("string:$tokenHtml");
836 * @param bool $escapeSmarty
838 * @return mixed|string
840 public static function getHookTokenReplacement(
845 $escapeSmarty = FALSE
847 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
849 if ($value && !$html) {
850 $value = str_replace('&', '&', $value);
854 $value = self
::tokenEscapeSmarty($value);
861 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
862 * for example {{token}} or \{token} will result in {token} in the final email
864 * this routine will remove the extra backslashes and braces
866 * @param $str ref to the string that will be scanned and modified
868 public static function unescapeTokens(&$str) {
869 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
873 * Replace unsubscribe tokens.
876 * The string with tokens to be replaced.
877 * @param object $domain
879 * @param array $groups
880 * The groups (if any) being unsubscribed.
882 * Replace tokens with html or plain text.
883 * @param int $contact_id
885 * @param string $hash The security hash of the unsub event
888 * The processed string
890 public static function &replaceUnsubscribeTokens(
898 if (self
::token_match('unsubscribe', 'group', $str)) {
899 if (!empty($groups)) {
900 $config = CRM_Core_Config
::singleton();
901 $base = CRM_Utils_System
::baseURL();
903 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
904 $dao = new CRM_Contact_DAO_Group();
906 while ($dao->fetch()) {
907 if (substr($dao->visibility
, 0, 6) == 'Public') {
908 $visibleGroups[] = $dao->id
;
911 $value = implode(', ', $groups);
912 self
::token_replace('unsubscribe', 'group', $value, $str);
919 * Replace resubscribe tokens.
922 * The string with tokens to be replaced.
923 * @param object $domain
925 * @param array $groups
926 * The groups (if any) being resubscribed.
928 * Replace tokens with html or plain text.
929 * @param int $contact_id
931 * @param string $hash The security hash of the resub event
934 * The processed string
936 public static function &replaceResubscribeTokens(
937 $str, &$domain, &$groups, $html,
940 if (self
::token_match('resubscribe', 'group', $str)) {
941 if (!empty($groups)) {
942 $value = implode(', ', $groups);
943 self
::token_replace('resubscribe', 'group', $value, $str);
950 * Replace subscription-confirmation-request tokens
953 * The string with tokens to be replaced.
954 * @param string $group
955 * The name of the group being subscribed.
958 * Replace tokens with html or plain text.
961 * The processed string
963 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
964 if (self
::token_match('subscribe', 'group', $str)) {
965 self
::token_replace('subscribe', 'group', $group, $str);
967 if (self
::token_match('subscribe', 'url', $str)) {
968 self
::token_replace('subscribe', 'url', $url, $str);
974 * Replace subscription-invitation tokens
977 * The string with tokens to be replaced.
980 * The processed string
982 public static function &replaceSubscribeInviteTokens($str) {
983 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
984 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
986 TRUE, NULL, TRUE, TRUE
988 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
991 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
992 foreach ($matches as $key => $value) {
993 $gid = substr($value, 21, -1);
994 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
995 "reset=1&gid={$gid}",
996 TRUE, NULL, TRUE, TRUE
998 $url = str_replace('&', '&', $url);
999 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
1003 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
1004 foreach ($matches as $key => $value) {
1005 $gid = substr($value, 18, -1);
1006 $config = CRM_Core_Config
::singleton();
1007 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
1008 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1009 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1010 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1017 * Replace welcome/confirmation tokens
1019 * @param string $str
1020 * The string with tokens to be replaced.
1021 * @param string $group
1022 * The name of the group being subscribed.
1024 * Replace tokens with html or plain text.
1027 * The processed string
1029 public static function &replaceWelcomeTokens($str, $group, $html) {
1030 if (self
::token_match('welcome', 'group', $str)) {
1031 self
::token_replace('welcome', 'group', $group, $str);
1037 * Find unprocessed tokens (call this last)
1039 * @param string $str
1040 * The string to search.
1043 * Array of tokens that weren't replaced
1045 public static function &unmatchedTokens(&$str) {
1046 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1047 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1052 * Find and replace tokens for each component.
1054 * @param string $str
1055 * The string to search.
1056 * @param array $contact
1057 * Associative array of contact properties.
1058 * @param array $components
1059 * A list of tokens that are known to exist in the email body.
1061 * @param bool $escapeSmarty
1062 * @param bool $returnEmptyToken
1065 * The processed string
1067 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1068 if (!is_array($components) ||
empty($contact)) {
1072 foreach ($components as $name => $tokens) {
1073 if (!is_array($tokens) ||
empty($tokens)) {
1077 foreach ($tokens as $token) {
1078 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1079 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1081 elseif (!$returnEmptyToken) {
1082 //replacing empty token
1083 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1091 * Get array of string tokens.
1093 * @param string $string
1094 * The input string to parse for tokens.
1097 * array of tokens mentioned in field
1099 public static function getTokens($string) {
1102 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1109 foreach ($matches[1] as $token) {
1110 list($type, $name) = preg_split('/\./', $token, 2);
1111 if ($name && $type) {
1112 if (!isset($tokens[$type])) {
1113 $tokens[$type] = array();
1115 $tokens[$type][] = $name;
1123 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1124 * and getTokens appears to be historical rather than intentional and should be reviewed
1127 * fields to pass in as return properties when populating token
1129 public static function getReturnProperties(&$string) {
1130 $returnProperties = array();
1132 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1138 foreach ($matches[1] as $token) {
1139 list($type, $name) = preg_split('/\./', $token, 2);
1141 $returnProperties["{$name}"] = 1;
1146 return $returnProperties;
1150 * Gives required details of contacts in an indexed array format so we
1151 * can iterate in a nice loop and do token evaluation
1153 * @param $contactIDs
1154 * @param array $returnProperties
1155 * Of required properties.
1156 * @param bool $skipOnHold Don't return on_hold contact info also.
1157 * Don't return on_hold contact info also.
1158 * @param bool $skipDeceased Don't return deceased contact info.
1159 * Don't return deceased contact info.
1160 * @param array $extraParams
1162 * @param array $tokens
1163 * The list of tokens we've extracted from the content.
1164 * @param null $className
1166 * The mailing list jobID - this is a legacy param.
1170 public static function getTokenDetails(
1172 $returnProperties = NULL,
1174 $skipDeceased = TRUE,
1175 $extraParams = NULL,
1180 if (empty($contactIDs)) {
1181 // putting a fatal here so we can track if/when this happens
1182 CRM_Core_Error
::fatal();
1186 foreach ($contactIDs as $key => $contactID) {
1188 CRM_Core_Form
::CB_PREFIX
. $contactID,
1197 if ($skipDeceased) {
1198 $params[] = array('is_deceased', '=', 0, 0, 0);
1203 $params[] = array('on_hold', '=', 0, 0, 0);
1207 $params = array_merge($params, $extraParams);
1210 // if return properties are not passed then get all return properties
1211 if (empty($returnProperties)) {
1212 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1213 array('display_name', 'checksum', 'contact_id')
1215 foreach ($fields as $key => $val) {
1216 $returnProperties[$val] = 1;
1221 foreach ($returnProperties as $name => $dontCare) {
1222 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1228 //get the total number of contacts to fetch from database.
1229 $numberofContacts = count($contactIDs);
1230 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1232 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1234 $contactDetails = &$details[0];
1236 foreach ($contactIDs as $key => $contactID) {
1237 if (array_key_exists($contactID, $contactDetails)) {
1238 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1239 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1241 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1243 // communication Prefferance
1244 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1245 $contactDetails[$contactID]['preferred_communication_method']
1248 foreach ($contactPcm as $key => $val) {
1250 $result[$val] = $pcm[$val];
1253 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1256 foreach ($custom as $cfID) {
1257 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1258 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1264 //special case for greeting replacement
1270 if (!empty($contactDetails[$contactID][$val])) {
1271 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1277 // also call a hook and get token details
1278 CRM_Utils_Hook
::tokenValues($details[0],
1288 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1289 * specific tokens to be rendered
1291 * @param array $contactIDs
1292 * This should always be array(0) or its not anonymous - left to keep signature same.
1294 * @param string $returnProperties
1295 * @param bool $skipOnHold
1296 * @param bool $skipDeceased
1297 * @param string $extraParams
1298 * @param array $tokens
1299 * @param string $className
1300 * Sent as context to the hook.
1301 * @param string $jobID
1303 * contactDetails with hooks swapped out
1305 public function getAnonymousTokenDetails($contactIDs = array(
1308 $returnProperties = NULL,
1310 $skipDeceased = TRUE,
1311 $extraParams = NULL,
1315 $details = array(0 => array());
1316 // also call a hook and get token details
1317 CRM_Utils_Hook
::tokenValues($details[0],
1327 * Gives required details of contribuion in an indexed array format so we
1328 * can iterate in a nice loop and do token evaluation
1330 * @param array $contributionIDs
1331 * @param array $returnProperties
1332 * Of required properties.
1333 * @param array $extraParams
1335 * @param array $tokens
1336 * The list of tokens we've extracted from the content.
1337 * @param string $className
1341 public static function getContributionTokenDetails(
1343 $returnProperties = NULL,
1344 $extraParams = NULL,
1348 //@todo - this function basically replicates calling
1349 //civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1350 if (empty($contributionIDs)) {
1351 // putting a fatal here so we can track if/when this happens
1352 CRM_Core_Error
::fatal();
1357 // no apiQuery helper yet, so do a loop and find contribution by id
1358 foreach ($contributionIDs as $contributionID) {
1360 $dao = new CRM_Contribute_DAO_Contribution();
1361 $dao->id
= $contributionID;
1363 if ($dao->find(TRUE)) {
1365 $details[$dao->id
] = array();
1366 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1368 // do the necessary transformation
1369 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1370 $piId = $details[$dao->id
]['payment_instrument_id'];
1371 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1372 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1374 if (!empty($details[$dao->id
]['campaign_id'])) {
1375 $campaignId = $details[$dao->id
]['campaign_id'];
1376 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1377 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1380 if (!empty($details[$dao->id
]['financial_type_id'])) {
1381 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1382 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1383 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1386 // TODO: call a hook to get token contribution details
1394 * Get Membership Token Details.
1395 * @param array $membershipIDs
1396 * Array of membership IDS.
1398 public static function getMembershipTokenDetails($membershipIDs) {
1399 $memberships = civicrm_api3('membership', 'get', array(
1400 'options' => array('limit' => 200000),
1401 'membership_id' => array('IN' => (array) $membershipIDs),
1403 return $memberships['values'];
1407 * Replace greeting tokens exists in message/subject
1409 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1411 if (!$contactDetails && !$contactId) {
1415 // check if there are any tokens
1416 $greetingTokens = self
::getTokens($tokenString);
1418 if (!empty($greetingTokens)) {
1419 // first use the existing contact object for token replacement
1420 if (!empty($contactDetails)) {
1421 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1424 // check if there are any unevaluated tokens
1425 $greetingTokens = self
::getTokens($tokenString);
1427 // $greetingTokens not empty, means there are few tokens which are not
1428 // evaluated, like custom data etc
1429 // so retrieve it from database
1430 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1431 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1432 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1433 $contactParams = array('contact_id' => $contactId);
1435 $greetingDetails = self
::getTokenDetails($contactParams,
1436 $greetingsReturnProperties,
1442 // again replace tokens
1443 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1452 // check if there are still any unevaluated tokens
1453 $remainingTokens = self
::getTokens($tokenString);
1455 // $greetingTokens not empty, there are customized or hook tokens to replace
1456 if (!empty($remainingTokens)) {
1457 // Fill the return properties array
1458 $greetingTokens = $remainingTokens;
1459 reset($greetingTokens);
1460 $greetingsReturnProperties = array();
1461 while (list($key) = each($greetingTokens)) {
1462 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1463 $props = array_fill_keys(array_keys($props), 1);
1464 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1466 $contactParams = array('contact_id' => $contactId);
1467 $greetingDetails = self
::getTokenDetails($contactParams,
1468 $greetingsReturnProperties,
1473 // Prepare variables for calling replaceHookTokens
1474 $categories = array_keys($greetingTokens);
1475 list($contact) = $greetingDetails;
1476 // Replace tokens defined in Hooks.
1477 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1487 public static function flattenTokens(&$tokens) {
1488 $flattenTokens = array();
1495 if (!isset($tokens[$prop])) {
1498 foreach ($tokens[$prop] as $type => $names) {
1499 if (!isset($flattenTokens[$type])) {
1500 $flattenTokens[$type] = array();
1502 foreach ($names as $name) {
1503 $flattenTokens[$type][$name] = 1;
1508 return $flattenTokens;
1512 * Replace all user tokens in $str
1514 * @param string $str
1515 * The string with tokens to be replaced.
1517 * @param null $knownTokens
1518 * @param bool $escapeSmarty
1521 * The processed string
1523 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1525 if (!$knownTokens ||
1526 !isset($knownTokens[$key])
1531 $str = preg_replace_callback(
1532 self
::tokenRegex($key),
1533 function ($matches) use ($escapeSmarty) {
1534 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1543 * @param bool $escapeSmarty
1547 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1550 list($objectName, $objectValue) = explode('-', $token, 2);
1552 switch ($objectName) {
1554 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1558 $value = CRM_Core_Permission
::roleEmails($objectValue);
1562 if ($escapeSmarty) {
1563 $value = self
::tokenEscapeSmarty($value);
1571 protected static function _buildContributionTokens() {
1572 $key = 'contribution';
1573 if (self
::$_tokens[$key] == NULL) {
1574 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1575 array('campaign', 'financial_type')
1581 * Store membership tokens on the static _tokens array.
1583 protected static function _buildMembershipTokens() {
1584 $key = 'membership';
1585 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1586 $membershipTokens = array();
1587 $tokens = CRM_Core_SelectValues
::membershipTokens();
1588 foreach ($tokens as $token => $dontCare) {
1589 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1591 self
::$_tokens[$key] = $membershipTokens;
1596 * Replace tokens for an entity.
1597 * @param string $entity
1598 * @param array $entityArray
1599 * (e.g. in format from api).
1600 * @param string $str
1601 * String to replace in.
1602 * @param array $knownTokens
1603 * Array of tokens present.
1604 * @param bool $escapeSmarty
1606 * string with replacements made
1608 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1609 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1613 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1614 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1615 foreach ($knownTokens[$entity] as $token) {
1616 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1617 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1619 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1624 * Replace Contribution tokens in html.
1626 * @param string $str
1627 * @param array $contribution
1628 * @param bool|string $html
1629 * @param string $knownTokens
1630 * @param bool|string $escapeSmarty
1634 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1635 $key = 'contribution';
1636 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1637 return $str; //early return
1639 self
::_buildContributionTokens();
1641 // here we intersect with the list of pre-configured valid tokens
1642 // so that we remove anything we do not recognize
1643 // I hope to move this step out of here soon and
1644 // then we will just iterate on a list of tokens that are passed to us
1646 $str = preg_replace_callback(
1647 self
::tokenRegex($key),
1648 function ($matches) use (&$contribution, $html, $escapeSmarty) {
1649 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1654 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1659 * We have a situation where we are rendering more than one token in each field because we are combining
1660 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1662 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1663 * it applies (other tokens are OK including date fields)
1665 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1666 * does - but the fields is already being formatted through a date function
1668 * @param string $separator
1669 * @param string $str
1670 * @param array $contribution
1671 * @param bool|string $html
1672 * @param string $knownTokens
1673 * @param bool|string $escapeSmarty
1675 * @return \Ambigous|mixed|string|\unknown
1677 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1678 if (empty($knownTokens['contribution'])) {
1682 if (in_array('receive_date', $knownTokens['contribution'])) {
1683 $formattedDates = array();
1684 $dates = explode($separator, $contribution['receive_date']);
1685 foreach ($dates as $date) {
1686 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1688 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1689 unset($knownTokens['contribution']['receive_date']);
1691 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1695 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1696 * - this is used by the pdfLetter task from membership search
1697 * @param string $token
1698 * @param array $membership
1699 * An api result array for a single membership.
1700 * @param bool $escapeSmarty
1704 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1705 $entity = 'membership';
1706 self
::_buildMembershipTokens();
1709 $value = $membership['membership_name'];
1713 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1714 $value = $statuses[$membership['status_id']];
1719 $value = civicrm_api3('membership_type', 'getvalue', array(
1720 'id' => $membership['membership_type_id'],
1721 '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
1807 public static function formatTokensForDisplay($tokens) {
1808 $sorted = $output = array();
1810 // Sort in ascending order by ignoring word case
1811 natcasesort($tokens);
1813 // Attempt to place tokens into optgroups
1814 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1815 foreach ($tokens as $k => $v) {
1816 // Check to see if this token is already in a group e.g. for custom fields
1817 $split = explode(' :: ', $v);
1818 if (!empty($split[1])) {
1819 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1823 $split = explode('.', trim($k, '{}'));
1824 if (isset($split[1])) {
1825 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1828 $entity = 'Contact';
1830 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1835 foreach ($sorted as $k => $v) {
1836 $output[] = array('text' => $k, 'children' => $v);