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
329 * @fixme: This function appears to be broken, as it depends on
330 * nonexistant method: CRM_Core_BAO_CustomValue::getContactValues()
331 * Marking as deprecated until this is fixed
335 * The string with tokens to be replaced.
337 * Associative array of org properties.
339 * Replace tokens with HTML or plain text.
341 * @param bool $escapeSmarty
344 * The processed string
346 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
347 self
::$_tokens['org']
349 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
350 array('address', 'display_name', 'checksum', 'contact_id')
354 foreach (self
::$_tokens['org'] as $token) {
355 // print "Getting token value for $token<br/><br/>";
360 // If the string doesn't contain this token, skip it.
362 if (!self
::token_match('org', $token, $str)) {
366 // Construct value from $token and $contact
370 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
371 // only generate cv if we need it
373 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
375 foreach ($cv as $cvFieldID => $value) {
376 if ($cvFieldID == $cfID) {
377 $value = CRM_Core_BAO_CustomField
::displayValue($value, $cfID);
382 elseif ($token == 'checksum') {
383 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
386 elseif ($token == 'address') {
387 // Build the location values array
390 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
391 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
392 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
393 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
394 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
396 // Construct the address token
398 $value = CRM_Utils_Address
::format($loc);
400 $value = str_replace("\n", '<br />', $value);
404 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
407 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
414 * Replace all mailing tokens in $str
417 * The string with tokens to be replaced.
418 * @param object $mailing
419 * The mailing BAO, or null for validation.
421 * Replace tokens with HTML or plain text.
423 * @param null $knownTokens
424 * @param bool $escapeSmarty
427 * The processed string
429 public static function &replaceMailingTokens(
434 $escapeSmarty = FALSE
437 if (!$knownTokens ||
!isset($knownTokens[$key])) {
441 $str = preg_replace_callback(
442 self
::tokenRegex($key),
443 function ($matches) use (&$mailing, $escapeSmarty) {
444 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
454 * @param bool $escapeSmarty
458 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
464 $value = $mailing ?
$mailing->id
: 'undefined';
468 $value = $mailing ?
$mailing->name
: 'Mailing Name';
472 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
473 $value = implode(', ', $groups);
477 $value = $mailing->subject
;
481 $mailingKey = $mailing->id
;
482 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
485 $value = CRM_Utils_System
::url('civicrm/mailing/view',
486 "reset=1&id={$mailingKey}",
487 TRUE, NULL, FALSE, TRUE
493 // Note: editUrl and scheduleUrl used to be different, but now there's
494 // one screen which can adapt based on permissions (in workflow mode).
495 $value = CRM_Utils_System
::url('civicrm/mailing/send',
496 "reset=1&mid={$mailing->id}&continue=true",
497 TRUE, NULL, FALSE, TRUE
502 $page = new CRM_Mailing_Page_View();
503 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
506 case 'approvalStatus':
507 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
511 $value = $mailing->approval_note
;
515 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
516 "reset=1&mid={$mailing->id}",
517 TRUE, NULL, FALSE, TRUE
522 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
526 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
530 $value = "{mailing.$token}";
535 $value = self
::tokenEscapeSmarty($value);
541 * Replace all action tokens in $str
544 * The string with tokens to be replaced.
545 * @param array $addresses
546 * Assoc. array of VERP event addresses.
548 * Assoc. array of action URLs.
550 * Replace tokens with HTML or plain text.
551 * @param array $knownTokens
552 * A list of tokens that are known to exist in the email body.
554 * @param bool $escapeSmarty
557 * The processed string
559 public static function &replaceActionTokens(
565 $escapeSmarty = FALSE
568 // here we intersect with the list of pre-configured valid tokens
569 // so that we remove anything we do not recognize
570 // I hope to move this step out of here soon and
571 // then we will just iterate on a list of tokens that are passed to us
572 if (!$knownTokens ||
empty($knownTokens[$key])) {
576 $str = preg_replace_callback(
577 self
::tokenRegex($key),
578 function ($matches) use (&$addresses, &$urls, $html, $escapeSmarty) {
579 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
591 * @param bool $escapeSmarty
593 * @return mixed|string
595 public static function getActionTokenReplacement(
600 $escapeSmarty = FALSE
602 // If the token is an email action, use it. Otherwise, find the
605 if (!in_array($token, self
::$_tokens['action'])) {
606 $value = "{action.$token}";
609 $value = CRM_Utils_Array
::value($token, $addresses);
611 if ($value == NULL) {
612 $value = CRM_Utils_Array
::value($token, $urls);
615 if ($value && $html) {
617 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
618 $value = "mailto:$value";
621 elseif ($value && !$html) {
622 $value = str_replace('&', '&', $value);
627 $value = self
::tokenEscapeSmarty($value);
633 * Replace all the contact-level tokens in $str with information from
637 * The string with tokens to be replaced.
638 * @param array $contact
639 * Associative array of contact properties.
641 * Replace tokens with HTML or plain text.
642 * @param array $knownTokens
643 * A list of tokens that are known to exist in the email body.
644 * @param bool $returnBlankToken
645 * Return unevaluated token if value is null.
647 * @param bool $escapeSmarty
650 * 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
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)
774 // $returnBlankToken means the caller wants to do further attempts at
775 // processing unreplaced tokens -- so don't escape them yet in this case.
776 $value = self
::tokenEscapeSmarty($value);
783 * Replace all the hook tokens in $str with information from
787 * The string with tokens to be replaced.
788 * @param array $contact
789 * Associative array of contact properties (including hook token values).
792 * Replace tokens with HTML or plain text.
794 * @param bool $escapeSmarty
797 * The processed string
799 public static function &replaceHookTokens(
804 $escapeSmarty = FALSE
806 foreach ($categories as $key) {
807 $str = preg_replace_callback(
808 self
::tokenRegex($key),
809 function ($matches) use (&$contact, $key, $html, $escapeSmarty) {
810 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
819 * Parse html through Smarty resolving any smarty functions.
820 * @param string $tokenHtml
821 * @param array $entity
822 * @param string $entityType
824 * html parsed through smarty
826 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
827 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
828 $smarty = CRM_Core_Smarty
::singleton();
829 // also add the tokens to the template
830 $smarty->assign_by_ref($entityType, $entity);
831 $tokenHtml = $smarty->fetch("string:$tokenHtml");
841 * @param bool $escapeSmarty
843 * @return mixed|string
845 public static function getHookTokenReplacement(
850 $escapeSmarty = FALSE
852 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
854 if ($value && !$html) {
855 $value = str_replace('&', '&', $value);
859 $value = self
::tokenEscapeSmarty($value);
866 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
867 * for example {{token}} or \{token} will result in {token} in the final email
869 * this routine will remove the extra backslashes and braces
871 * @param $str ref to the string that will be scanned and modified
873 public static function unescapeTokens(&$str) {
874 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
878 * Replace unsubscribe tokens.
881 * The string with tokens to be replaced.
882 * @param object $domain
884 * @param array $groups
885 * The groups (if any) being unsubscribed.
887 * Replace tokens with html or plain text.
888 * @param int $contact_id
890 * @param string $hash The security hash of the unsub event
893 * The processed string
895 public static function &replaceUnsubscribeTokens(
903 if (self
::token_match('unsubscribe', 'group', $str)) {
904 if (!empty($groups)) {
905 $config = CRM_Core_Config
::singleton();
906 $base = CRM_Utils_System
::baseURL();
908 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
909 $dao = new CRM_Contact_DAO_Group();
911 while ($dao->fetch()) {
912 if (substr($dao->visibility
, 0, 6) == 'Public') {
913 $visibleGroups[] = $dao->id
;
916 $value = implode(', ', $groups);
917 self
::token_replace('unsubscribe', 'group', $value, $str);
924 * Replace resubscribe tokens.
927 * The string with tokens to be replaced.
928 * @param object $domain
930 * @param array $groups
931 * The groups (if any) being resubscribed.
933 * Replace tokens with html or plain text.
934 * @param int $contact_id
936 * @param string $hash The security hash of the resub event
939 * The processed string
941 public static function &replaceResubscribeTokens(
942 $str, &$domain, &$groups, $html,
945 if (self
::token_match('resubscribe', 'group', $str)) {
946 if (!empty($groups)) {
947 $value = implode(', ', $groups);
948 self
::token_replace('resubscribe', 'group', $value, $str);
955 * Replace subscription-confirmation-request tokens
958 * The string with tokens to be replaced.
959 * @param string $group
960 * The name of the group being subscribed.
963 * Replace tokens with html or plain text.
966 * The processed string
968 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
969 if (self
::token_match('subscribe', 'group', $str)) {
970 self
::token_replace('subscribe', 'group', $group, $str);
972 if (self
::token_match('subscribe', 'url', $str)) {
973 self
::token_replace('subscribe', 'url', $url, $str);
979 * Replace subscription-invitation tokens
982 * The string with tokens to be replaced.
985 * The processed string
987 public static function &replaceSubscribeInviteTokens($str) {
988 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
989 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
991 TRUE, NULL, TRUE, TRUE
993 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
996 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
997 foreach ($matches as $key => $value) {
998 $gid = substr($value, 21, -1);
999 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
1000 "reset=1&gid={$gid}",
1001 TRUE, NULL, TRUE, TRUE
1003 $url = str_replace('&', '&', $url);
1004 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
1008 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
1009 foreach ($matches as $key => $value) {
1010 $gid = substr($value, 18, -1);
1011 $config = CRM_Core_Config
::singleton();
1012 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
1013 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1014 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1015 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1022 * Replace welcome/confirmation tokens
1024 * @param string $str
1025 * The string with tokens to be replaced.
1026 * @param string $group
1027 * The name of the group being subscribed.
1029 * Replace tokens with html or plain text.
1032 * The processed string
1034 public static function &replaceWelcomeTokens($str, $group, $html) {
1035 if (self
::token_match('welcome', 'group', $str)) {
1036 self
::token_replace('welcome', 'group', $group, $str);
1042 * Find unprocessed tokens (call this last)
1044 * @param string $str
1045 * The string to search.
1048 * Array of tokens that weren't replaced
1050 public static function &unmatchedTokens(&$str) {
1051 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1052 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1057 * Find and replace tokens for each component.
1059 * @param string $str
1060 * The string to search.
1061 * @param array $contact
1062 * Associative array of contact properties.
1063 * @param array $components
1064 * A list of tokens that are known to exist in the email body.
1066 * @param bool $escapeSmarty
1067 * @param bool $returnEmptyToken
1070 * The processed string
1072 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1073 if (!is_array($components) ||
empty($contact)) {
1077 foreach ($components as $name => $tokens) {
1078 if (!is_array($tokens) ||
empty($tokens)) {
1082 foreach ($tokens as $token) {
1083 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1084 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1086 elseif (!$returnEmptyToken) {
1087 //replacing empty token
1088 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1096 * Get array of string tokens.
1098 * @param string $string
1099 * The input string to parse for tokens.
1102 * array of tokens mentioned in field
1104 public static function getTokens($string) {
1107 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1114 foreach ($matches[1] as $token) {
1115 list($type, $name) = preg_split('/\./', $token, 2);
1116 if ($name && $type) {
1117 if (!isset($tokens[$type])) {
1118 $tokens[$type] = array();
1120 $tokens[$type][] = $name;
1128 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1129 * and getTokens appears to be historical rather than intentional and should be reviewed
1132 * fields to pass in as return properties when populating token
1134 public static function getReturnProperties(&$string) {
1135 $returnProperties = array();
1137 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1143 foreach ($matches[1] as $token) {
1144 list($type, $name) = preg_split('/\./', $token, 2);
1146 $returnProperties["{$name}"] = 1;
1151 return $returnProperties;
1155 * Gives required details of contacts in an indexed array format so we
1156 * can iterate in a nice loop and do token evaluation
1158 * @param $contactIDs
1159 * @param array $returnProperties
1160 * Of required properties.
1161 * @param bool $skipOnHold Don't return on_hold contact info also.
1162 * Don't return on_hold contact info also.
1163 * @param bool $skipDeceased Don't return deceased contact info.
1164 * Don't return deceased contact info.
1165 * @param array $extraParams
1167 * @param array $tokens
1168 * The list of tokens we've extracted from the content.
1169 * @param null $className
1171 * The mailing list jobID - this is a legacy param.
1175 public static function getTokenDetails(
1177 $returnProperties = NULL,
1179 $skipDeceased = TRUE,
1180 $extraParams = NULL,
1185 if (empty($contactIDs)) {
1186 // putting a fatal here so we can track if/when this happens
1187 CRM_Core_Error
::fatal();
1189 // @todo this functions needs unit tests.
1191 foreach ($contactIDs as $key => $contactID) {
1193 CRM_Core_Form
::CB_PREFIX
. $contactID,
1202 if ($skipDeceased) {
1203 $params[] = array('is_deceased', '=', 0, 0, 0);
1208 $params[] = array('on_hold', '=', 0, 0, 0);
1212 $params = array_merge($params, $extraParams);
1215 // if return properties are not passed then get all return properties
1216 if (empty($returnProperties)) {
1217 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1218 array('display_name', 'checksum', 'contact_id')
1220 foreach ($fields as $key => $val) {
1221 // The unavailable fields are not available as tokens, do not have a one-2-one relationship
1222 // with contacts and are expensive to resolve.
1223 // @todo see CRM-17253 - there are some other fields (e.g note) that should be excluded
1224 // and upstream calls to this should populate return properties.
1225 $unavailableFields = array('group', 'tag');
1226 if (!in_array($val, $unavailableFields)) {
1227 $returnProperties[$val] = 1;
1233 foreach ($returnProperties as $name => $dontCare) {
1234 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1240 //get the total number of contacts to fetch from database.
1241 $numberofContacts = count($contactIDs);
1242 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1244 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1246 $contactDetails = &$details[0];
1248 foreach ($contactIDs as $key => $contactID) {
1249 if (array_key_exists($contactID, $contactDetails)) {
1250 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1251 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1253 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1255 // communication Preference
1256 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1257 $contactDetails[$contactID]['preferred_communication_method']
1260 foreach ($contactPcm as $key => $val) {
1262 $result[$val] = $pcm[$val];
1265 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1268 foreach ($custom as $cfID) {
1269 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1270 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::displayValue($contactDetails[$contactID]["custom_{$cfID}"], $cfID);
1274 // special case for greeting replacement
1280 if (!empty($contactDetails[$contactID][$val])) {
1281 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1287 // also call a hook and get token details
1288 CRM_Utils_Hook
::tokenValues($details[0],
1298 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1299 * specific tokens to be rendered
1301 * @param array $contactIDs
1302 * This should always be array(0) or its not anonymous - left to keep signature same.
1304 * @param string $returnProperties
1305 * @param bool $skipOnHold
1306 * @param bool $skipDeceased
1307 * @param string $extraParams
1308 * @param array $tokens
1309 * @param string $className
1310 * Sent as context to the hook.
1311 * @param string $jobID
1313 * contactDetails with hooks swapped out
1315 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
1351 public static function getContributionTokenDetails(
1353 $returnProperties = NULL,
1354 $extraParams = NULL,
1358 // @todo this function basically replicates calling
1359 // 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(
1410 'options' => array('limit' => 200000),
1411 'membership_id' => array('IN' => (array) $membershipIDs),
1413 return $memberships['values'];
1417 * Replace existing greeting tokens in message/subject.
1419 * @param string $tokenString
1420 * @param array $contactDetails
1421 * @param int $contactId
1422 * @param string $className
1423 * @param bool $escapeSmarty
1425 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1427 if (!$contactDetails && !$contactId) {
1431 // check if there are any tokens
1432 $greetingTokens = self
::getTokens($tokenString);
1434 if (!empty($greetingTokens)) {
1435 // first use the existing contact object for token replacement
1436 if (!empty($contactDetails)) {
1437 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1440 // check if there are any unevaluated tokens
1441 $greetingTokens = self
::getTokens($tokenString);
1443 // $greetingTokens not empty, means there are few tokens which are not
1444 // evaluated, like custom data etc
1445 // so retrieve it from database
1446 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1447 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1448 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1449 $contactParams = array('contact_id' => $contactId);
1451 $greetingDetails = self
::getTokenDetails($contactParams,
1452 $greetingsReturnProperties,
1458 // again replace tokens
1459 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1468 // check if there are still any unevaluated tokens
1469 $remainingTokens = self
::getTokens($tokenString);
1471 // $greetingTokens not empty, there are customized or hook tokens to replace
1472 if (!empty($remainingTokens)) {
1473 // Fill the return properties array
1474 $greetingTokens = $remainingTokens;
1475 reset($greetingTokens);
1476 $greetingsReturnProperties = array();
1477 while (list($key) = each($greetingTokens)) {
1478 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1479 $props = array_fill_keys(array_keys($props), 1);
1480 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1482 $contactParams = array('contact_id' => $contactId);
1483 $greetingDetails = self
::getTokenDetails($contactParams,
1484 $greetingsReturnProperties,
1489 // Prepare variables for calling replaceHookTokens
1490 $categories = array_keys($greetingTokens);
1491 list($contact) = $greetingDetails;
1492 // Replace tokens defined in Hooks.
1493 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1503 public static function flattenTokens(&$tokens) {
1504 $flattenTokens = array();
1511 if (!isset($tokens[$prop])) {
1514 foreach ($tokens[$prop] as $type => $names) {
1515 if (!isset($flattenTokens[$type])) {
1516 $flattenTokens[$type] = array();
1518 foreach ($names as $name) {
1519 $flattenTokens[$type][$name] = 1;
1524 return $flattenTokens;
1528 * Replace all user tokens in $str
1530 * @param string $str
1531 * The string with tokens to be replaced.
1533 * @param null $knownTokens
1534 * @param bool $escapeSmarty
1537 * The processed string
1539 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1541 if (!$knownTokens ||
1542 !isset($knownTokens[$key])
1547 $str = preg_replace_callback(
1548 self
::tokenRegex($key),
1549 function ($matches) use ($escapeSmarty) {
1550 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1559 * @param bool $escapeSmarty
1563 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1566 list($objectName, $objectValue) = explode('-', $token, 2);
1568 switch ($objectName) {
1570 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1574 $value = CRM_Core_Permission
::roleEmails($objectValue);
1578 if ($escapeSmarty) {
1579 $value = self
::tokenEscapeSmarty($value);
1585 protected static function _buildContributionTokens() {
1586 $key = 'contribution';
1587 if (self
::$_tokens[$key] == NULL) {
1588 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1589 array('campaign', 'financial_type')
1595 * Store membership tokens on the static _tokens array.
1597 protected static function _buildMembershipTokens() {
1598 $key = 'membership';
1599 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1600 $membershipTokens = array();
1601 $tokens = CRM_Core_SelectValues
::membershipTokens();
1602 foreach ($tokens as $token => $dontCare) {
1603 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1605 self
::$_tokens[$key] = $membershipTokens;
1610 * Replace tokens for an entity.
1611 * @param string $entity
1612 * @param array $entityArray
1613 * (e.g. in format from api).
1614 * @param string $str
1615 * String to replace in.
1616 * @param array $knownTokens
1617 * Array of tokens present.
1618 * @param bool $escapeSmarty
1620 * string with replacements made
1622 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1623 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1627 $fn = 'get' . ucfirst($entity) . 'TokenReplacement';
1628 $fn = is_callable(array('CRM_Utils_Token', $fn)) ?
$fn : 'getApiTokenReplacement';
1629 // since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1630 foreach ($knownTokens[$entity] as $token) {
1631 $replacement = self
::$fn($entity, $token, $entityArray);
1632 if ($escapeSmarty) {
1633 $replacement = self
::tokenEscapeSmarty($replacement);
1635 $str = str_replace('{' . $entity . '.' . $token . '}', $replacement, $str);
1637 return preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1641 * @param int $caseId
1643 * @param array $knownTokens
1644 * @param bool $escapeSmarty
1646 * @throws \CiviCRM_API3_Exception
1648 public static function replaceCaseTokens($caseId, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1649 if (!$knownTokens ||
empty($knownTokens['case'])) {
1652 $case = civicrm_api3('case', 'getsingle', array('id' => $caseId));
1653 return self
::replaceEntityTokens('case', $case, $str, $knownTokens, $escapeSmarty);
1657 * Generic function for formatting token replacement for an api field
1659 * @param string $entity
1660 * @param string $token
1661 * @param array $entityArray
1663 * @throws \CiviCRM_API3_Exception
1665 public static function getApiTokenReplacement($entity, $token, $entityArray) {
1666 if (!isset($entityArray[$token])) {
1669 $field = civicrm_api3($entity, 'getfield', array('action' => 'get', 'name' => $token, 'get_options' => 'get'));
1670 $field = $field['values'];
1671 $fieldType = CRM_Utils_Array
::value('type', $field);
1673 if ($fieldType == CRM_Utils_Type
::T_BOOLEAN
&& empty($field['options'])) {
1674 $field['options'] = array(ts('No'), ts('Yes'));
1676 // Match pseudoconstants
1677 if (!empty($field['options'])) {
1679 foreach ((array) $entityArray[$token] as $val) {
1680 $ret[] = $field['options'][$val];
1682 return implode(', ', $ret);
1684 // Format date fields
1685 elseif ($entityArray[$token] && $fieldType == CRM_Utils_Type
::T_DATE
) {
1686 return CRM_Utils_Date
::customFormat($entityArray[$token]);
1688 return implode(', ', (array) $entityArray[$token]);
1692 * Replace Contribution tokens in html.
1694 * @param string $str
1695 * @param array $contribution
1696 * @param bool|string $html
1697 * @param string $knownTokens
1698 * @param bool|string $escapeSmarty
1702 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1703 $key = 'contribution';
1704 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1705 return $str; //early return
1707 self
::_buildContributionTokens();
1709 // here we intersect with the list of pre-configured valid tokens
1710 // so that we remove anything we do not recognize
1711 // I hope to move this step out of here soon and
1712 // then we will just iterate on a list of tokens that are passed to us
1714 $str = preg_replace_callback(
1715 self
::tokenRegex($key),
1716 function ($matches) use (&$contribution, $html, $escapeSmarty) {
1717 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1722 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1727 * We have a situation where we are rendering more than one token in each field because we are combining
1728 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1730 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1731 * it applies (other tokens are OK including date fields)
1733 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1734 * does - but the fields is already being formatted through a date function
1736 * @param string $separator
1737 * @param string $str
1738 * @param array $contribution
1739 * @param bool|string $html
1740 * @param string $knownTokens
1741 * @param bool|string $escapeSmarty
1745 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1746 if (empty($knownTokens['contribution'])) {
1750 if (in_array('receive_date', $knownTokens['contribution'])) {
1751 $formattedDates = array();
1752 $dates = explode($separator, $contribution['receive_date']);
1753 foreach ($dates as $date) {
1754 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1756 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1757 unset($knownTokens['contribution']['receive_date']);
1759 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1763 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1764 * - this is used by the pdfLetter task from membership search
1765 * @param string $entity
1766 * should always be "membership"
1767 * @param string $token
1769 * @param array $membership
1770 * An api result array for a single membership.
1771 * @return string token replacement
1773 public static function getMembershipTokenReplacement($entity, $token, $membership) {
1774 self
::_buildMembershipTokens();
1777 $value = $membership['membership_name'];
1781 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1782 $value = $statuses[$membership['status_id']];
1787 $value = civicrm_api3('membership_type', 'getvalue', array(
1788 'id' => $membership['membership_type_id'],
1789 'return' => 'minimum_fee',
1792 catch (CiviCRM_API3_Exception
$e) {
1793 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1794 // api handles NULL (4.4)
1800 if (in_array($token, self
::$_tokens[$entity])) {
1801 $value = $membership[$token];
1805 $value = "{$entity}.{$token}";
1815 * @param $contribution
1817 * @param bool $escapeSmarty
1819 * @return mixed|string
1821 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1822 self
::_buildContributionTokens();
1825 case 'total_amount':
1828 case 'non_deductible_amount':
1829 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1832 case 'receive_date':
1833 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1834 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1838 if (!in_array($token, self
::$_tokens['contribution'])) {
1839 $value = "{contribution.$token}";
1842 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1847 if ($escapeSmarty) {
1848 $value = self
::tokenEscapeSmarty($value);
1855 * [legacy_token => new_token]
1857 public static function legacyContactTokens() {
1859 'individual_prefix' => 'prefix_id',
1860 'individual_suffix' => 'suffix_id',
1861 'gender' => 'gender_id',
1862 'communication_style' => 'communication_style_id',
1867 * Formats a token list for the select2 widget
1872 public static function formatTokensForDisplay($tokens) {
1873 $sorted = $output = array();
1875 // Sort in ascending order by ignoring word case
1876 natcasesort($tokens);
1878 // Attempt to place tokens into optgroups
1879 // @todo These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1880 foreach ($tokens as $k => $v) {
1881 // Check to see if this token is already in a group e.g. for custom fields
1882 $split = explode(' :: ', $v);
1883 if (!empty($split[1])) {
1884 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1888 $split = explode('.', trim($k, '{}'));
1889 if (isset($split[1])) {
1890 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1893 $entity = 'Contact';
1895 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1900 foreach ($sorted as $k => $v) {
1901 $output[] = array('text' => $k, 'children' => $v);