3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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.
96 * @param string $str The message
98 * @return true|array true if all required tokens are found,
99 * 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' =>
109 'action.optOut' => ts("'Opt out via email' - displays an email address for recipients to opt out of receiving emails from your organization."),
110 '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."),
111 'action.unsubscribe' => ts("'Unsubscribe via email' - displays an email address for recipients to unsubscribe from the specific mailing list used to send this message."),
112 '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."),
118 foreach (self
::$_requiredTokens as $token => $value) {
119 if (!is_array($value)) {
120 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
121 $missing[$token] = $value;
127 foreach ($value as $t => $d) {
129 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
134 $missing[$token] = $desc;
139 if (empty($missing)) {
146 * Wrapper for token matching
148 * @param string $type The token type (domain,mailing,contact,action)
149 * @param string $var The token variable
150 * @param string $str The string to search
152 * @return boolean Was there a match
156 public static function token_match($type, $var, &$str) {
157 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
158 return preg_match("/(^|[^\{])$token/", $str);
162 * Wrapper for token replacing
164 * @param string $type The token type
165 * @param string $var The token variable
166 * @param string $value The value to substitute for the token
167 * @param string (reference) $str The string to replace in
169 * @param bool $escapeSmarty
171 * @return string The processed string
175 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
176 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
181 $value = self
::tokenEscapeSmarty($value);
183 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
188 * get< the regex for token replacement
192 * @internal param string $key a string indicating the the type of token to be used in the expression
194 * @return string regular expression sutiable for using in preg_replace
198 private static function tokenRegex($token_type) {
199 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
203 * escape the string so a malicious user cannot inject smarty code into the template
205 * @param string $string a string that needs to be escaped from smarty parsing
207 * @return string the escaped string
211 private static function tokenEscapeSmarty($string) {
212 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
213 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
217 * Replace all the domain-level tokens in $str
219 * @param string $str The string with tokens to be replaced
220 * @param object $domain The domain BAO
221 * @param boolean $html Replace tokens with HTML or plain text
223 * @param null $knownTokens
224 * @param bool $escapeSmarty
226 * @return string The processed string
230 public static function &replaceDomainTokens(
235 $escapeSmarty = FALSE
239 !$knownTokens ||
empty($knownTokens[$key])) {
243 $str = preg_replace_callback(
244 self
::tokenRegex($key),
245 function ($matches) use(&$domain, $html, $escapeSmarty) {
246 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
257 * @param bool $escapeSmarty
259 * @return mixed|null|string
261 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
262 // check if the token we were passed is valid
263 // we have to do this because this function is
264 // called only when we find a token in the string
266 $loc = &$domain->getLocationValues();
268 if (!in_array($token, self
::$_tokens['domain'])) {
269 $value = "{domain.$token}";
271 elseif ($token == 'address') {
272 static $addressCache = array();
274 $cache_key = $html ?
'address-html' : 'address-text';
275 if (array_key_exists($cache_key, $addressCache)) {
276 return $addressCache[$cache_key];
280 /* Construct the address token */
282 if (!empty($loc[$token])) {
284 $value = $loc[$token][1]['display'];
285 $value = str_replace("\n", '<br />', $value);
288 $value = $loc[$token][1]['display_text'];
290 $addressCache[$cache_key] = $value;
293 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
294 $value = $domain->$token;
296 elseif ($token == 'phone' ||
$token == 'email') {
297 /* Construct the phone and email tokens */
300 if (!empty($loc[$token])) {
301 foreach ($loc[$token] as $index => $entity) {
302 $value = $entity[$token];
309 $value = self
::tokenEscapeSmarty($value);
316 * Replace all the org-level tokens in $str
318 * @param string $str The string with tokens to be replaced
319 * @param object $org Associative array of org properties
320 * @param boolean $html Replace tokens with HTML or plain text
322 * @param bool $escapeSmarty
324 * @return string The processed string
328 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
329 self
::$_tokens['org'] =
331 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
332 array('address', 'display_name', 'checksum', 'contact_id')
336 foreach (self
::$_tokens['org'] as $token) {
337 // print "Getting token value for $token<br/><br/>";
342 /* If the string doesn't contain this token, skip it. */
344 if (!self
::token_match('org', $token, $str)) {
348 /* Construct value from $token and $contact */
352 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
353 // only generate cv if we need it
355 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
357 foreach ($cv as $cvFieldID => $value) {
358 if ($cvFieldID == $cfID) {
359 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
364 elseif ($token == 'checksum') {
365 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
368 elseif ($token == 'address') {
369 /* Build the location values array */
372 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
373 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
374 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
375 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
376 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
378 /* Construct the address token */
380 $value = CRM_Utils_Address
::format($loc);
382 $value = str_replace("\n", '<br />', $value);
386 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
389 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
396 * Replace all mailing tokens in $str
398 * @param string $str The string with tokens to be replaced
399 * @param object $mailing The mailing BAO, or null for validation
400 * @param boolean $html Replace tokens with HTML or plain text
402 * @param null $knownTokens
403 * @param bool $escapeSmarty
405 * @return string The processed sstring
409 public static function &replaceMailingTokens(
414 $escapeSmarty = FALSE
417 if (!$knownTokens ||
!isset($knownTokens[$key])) {
421 $str = preg_replace_callback(
422 self
::tokenRegex($key),
423 function ($matches) use(&$mailing, $escapeSmarty) {
424 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
434 * @param bool $escapeSmarty
438 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
444 $value = $mailing ?
$mailing->id
: 'undefined';
448 $value = $mailing ?
$mailing->name
: 'Mailing Name';
452 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
453 $value = implode(', ', $groups);
457 $value = $mailing->subject
;
461 $mailingKey = $mailing->id
;
462 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
465 $value = CRM_Utils_System
::url('civicrm/mailing/view',
466 "reset=1&id={$mailingKey}",
467 TRUE, NULL, FALSE, TRUE
472 $value = CRM_Utils_System
::url('civicrm/mailing/send',
473 "reset=1&mid={$mailing->id}&continue=true",
474 TRUE, NULL, FALSE, TRUE
479 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
480 "reset=1&mid={$mailing->id}",
481 TRUE, NULL, FALSE, TRUE
486 $page = new CRM_Mailing_Page_View();
487 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
490 case 'approvalStatus':
491 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
495 $value = $mailing->approval_note
;
499 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
500 "reset=1&mid={$mailing->id}",
501 TRUE, NULL, FALSE, TRUE
506 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
510 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
514 $value = "{mailing.$token}";
519 $value = self
::tokenEscapeSmarty($value);
525 * Replace all action tokens in $str
527 * @param string $str The string with tokens to be replaced
528 * @param array $addresses Assoc. array of VERP event addresses
529 * @param array $urls Assoc. array of action URLs
530 * @param boolean $html Replace tokens with HTML or plain text
531 * @param array $knownTokens A list of tokens that are known to exist in the email body
533 * @param bool $escapeSmarty
535 * @return string The processed string
539 public static function &replaceActionTokens(
545 $escapeSmarty = FALSE
548 // here we intersect with the list of pre-configured valid tokens
549 // so that we remove anything we do not recognize
550 // I hope to move this step out of here soon and
551 // then we will just iterate on a list of tokens that are passed to us
552 if (!$knownTokens ||
empty($knownTokens[$key])) {
556 $str = preg_replace_callback(
557 self
::tokenRegex($key),
558 function ($matches) use(&$addresses, &$urls, $html, $escapeSmarty) {
559 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
571 * @param bool $escapeSmarty
573 * @return mixed|string
575 public static function getActionTokenReplacement(
580 $escapeSmarty = FALSE
582 /* If the token is an email action, use it. Otherwise, find the
585 if (!in_array($token, self
::$_tokens['action'])) {
586 $value = "{action.$token}";
589 $value = CRM_Utils_Array
::value($token, $addresses);
591 if ($value == NULL) {
592 $value = CRM_Utils_Array
::value($token, $urls);
595 if ($value && $html) {
597 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
598 $value = "mailto:$value";
601 elseif ($value && !$html) {
602 $value = str_replace('&', '&', $value);
607 $value = self
::tokenEscapeSmarty($value);
613 * Replace all the contact-level tokens in $str with information from
616 * @param string $str The string with tokens to be replaced
617 * @param array $contact Associative array of contact properties
618 * @param boolean $html Replace tokens with HTML or plain text
619 * @param array $knownTokens A list of tokens that are known to exist in the email body
620 * @param boolean $returnBlankToken return unevaluated token if value is null
622 * @param bool $escapeSmarty
624 * @return string The processed string
628 public static function &replaceContactTokens(
633 $returnBlankToken = FALSE,
634 $escapeSmarty = FALSE
637 if (self
::$_tokens[$key] == NULL) {
638 /* This should come from UF */
640 self
::$_tokens[$key] =
642 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
643 array('checksum', 'contact_id')
647 // here we intersect with the list of pre-configured valid tokens
648 // so that we remove anything we do not recognize
649 // I hope to move this step out of here soon and
650 // then we will just iterate on a list of tokens that are passed to us
651 if (!$knownTokens ||
empty($knownTokens[$key])) {
655 $str = preg_replace_callback(
656 self
::tokenRegex($key),
657 function ($matches) use(&$contact, $html, $returnBlankToken, $escapeSmarty) {
658 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
663 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
671 * @param bool $returnBlankToken
672 * @param bool $escapeSmarty
674 * @return bool|mixed|null|string
676 public static function getContactTokenReplacement(
680 $returnBlankToken = FALSE,
681 $escapeSmarty = FALSE
683 if (self
::$_tokens['contact'] == NULL) {
684 /* This should come from UF */
686 self
::$_tokens['contact'] =
688 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
689 array('checksum', 'contact_id')
693 /* Construct value from $token and $contact */
698 // Support legacy tokens
699 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
701 // check if the token we were passed is valid
702 // we have to do this because this function is
703 // called only when we find a token in the string
705 if (!in_array($token, self
::$_tokens['contact'])) {
708 elseif ($token == 'checksum') {
709 $hash = CRM_Utils_Array
::value('hash', $contact);
710 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
711 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
719 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
721 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
722 if (is_array($value)) {
725 // Convert pseudoconstants using metadata
726 elseif ($value && is_numeric($value)) {
727 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
728 if (!empty($allFields[$token]['pseudoconstant'])) {
729 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
735 $value = str_replace('&', '&', $value);
738 // if null then return actual token
739 if ($returnBlankToken && !$value) {
744 $value = "{contact.$token}";
748 && !($returnBlankToken && $noReplace)) { // $returnBlankToken means the caller wants to do further attempts at processing unreplaced tokens -- so don't escape them yet in this case.
749 $value = self
::tokenEscapeSmarty($value);
756 * Replace all the hook tokens in $str with information from
759 * @param string $str The string with tokens to be replaced
760 * @param array $contact Associative array of contact properties (including hook token values)
762 * @param boolean $html Replace tokens with HTML or plain text
764 * @param bool $escapeSmarty
766 * @return string The processed string
770 public static function &replaceHookTokens(
775 $escapeSmarty = FALSE
777 foreach ($categories as $key) {
778 $str = preg_replace_callback(
779 self
::tokenRegex($key),
780 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
781 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
790 * Parse html through Smarty resolving any smarty functions
791 * @param string $tokenHtml
792 * @param array $entity
793 * @param string $entityType
794 * @return string html parsed through smarty
796 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
797 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
798 $smarty = CRM_Core_Smarty
::singleton();
799 // also add the tokens to the template
800 $smarty->assign_by_ref($entityType, $entity);
801 $tokenHtml = $smarty->fetch("string:$tokenHtml");
805 public static function getHookTokenReplacement(
810 $escapeSmarty = FALSE
812 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
814 if ($value && !$html) {
815 $value = str_replace('&', '&', $value);
819 $value = self
::tokenEscapeSmarty($value);
826 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
827 * for example {{token}} or \{token} will result in {token} in the final email
829 * this routine will remove the extra backslashes and braces
831 * @param $str ref to the string that will be scanned and modified
832 * @return void this function works directly on the string that is passed
836 public static function unescapeTokens(&$str) {
837 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
841 * Replace unsubscribe tokens
843 * @param string $str the string with tokens to be replaced
844 * @param object $domain The domain BAO
845 * @param array $groups The groups (if any) being unsubscribed
846 * @param boolean $html Replace tokens with html or plain text
847 * @param int $contact_id The contact ID
848 * @param string hash The security hash of the unsub event
850 * @return string The processed string
854 public static function &replaceUnsubscribeTokens(
862 if (self
::token_match('unsubscribe', 'group', $str)) {
863 if (!empty($groups)) {
864 $config = CRM_Core_Config
::singleton();
865 $base = CRM_Utils_System
::baseURL();
867 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
868 $dao = new CRM_Contact_DAO_Group();
870 while ($dao->fetch()) {
871 if (substr($dao->visibility
, 0, 6) == 'Public') {
872 $visibleGroups[] = $dao->id
;
875 $value = implode(', ', $groups);
876 self
::token_replace('unsubscribe', 'group', $value, $str);
883 * Replace resubscribe tokens
885 * @param string $str the string with tokens to be replaced
886 * @param object $domain The domain BAO
887 * @param array $groups The groups (if any) being resubscribed
888 * @param boolean $html Replace tokens with html or plain text
889 * @param int $contact_id The contact ID
890 * @param string hash The security hash of the resub event
892 * @return string The processed string
896 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
899 if (self
::token_match('resubscribe', 'group', $str)) {
900 if (!empty($groups)) {
901 $value = implode(', ', $groups);
902 self
::token_replace('resubscribe', 'group', $value, $str);
909 * Replace subscription-confirmation-request tokens
911 * @param string $str The string with tokens to be replaced
912 * @param string $group The name of the group being subscribed
914 * @param boolean $html Replace tokens with html or plain text
916 * @return string The processed string
920 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
921 if (self
::token_match('subscribe', 'group', $str)) {
922 self
::token_replace('subscribe', 'group', $group, $str);
924 if (self
::token_match('subscribe', 'url', $str)) {
925 self
::token_replace('subscribe', 'url', $url, $str);
931 * Replace subscription-invitation tokens
933 * @param string $str The string with tokens to be replaced
935 * @return string The processed string
939 public static function &replaceSubscribeInviteTokens($str) {
940 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
941 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
943 TRUE, NULL, TRUE, TRUE
945 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
948 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
949 foreach ($matches as $key => $value) {
950 $gid = substr($value, 21, -1);
951 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
952 "reset=1&gid={$gid}",
953 TRUE, NULL, TRUE, TRUE
955 $url = str_replace('&', '&', $url);
956 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
960 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
961 foreach ($matches as $key => $value) {
962 $gid = substr($value, 18, -1);
963 $config = CRM_Core_Config
::singleton();
964 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
965 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
966 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
967 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
974 * Replace welcome/confirmation tokens
976 * @param string $str The string with tokens to be replaced
977 * @param string $group The name of the group being subscribed
978 * @param boolean $html Replace tokens with html or plain text
980 * @return string The processed string
984 public static function &replaceWelcomeTokens($str, $group, $html) {
985 if (self
::token_match('welcome', 'group', $str)) {
986 self
::token_replace('welcome', 'group', $group, $str);
992 * Find unprocessed tokens (call this last)
994 * @param string $str The string to search
996 * @return array Array of tokens that weren't replaced
1000 public static function &unmatchedTokens(&$str) {
1001 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1002 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1007 * Find and replace tokens for each component
1009 * @param string $str The string to search
1010 * @param array $contact Associative array of contact properties
1011 * @param array $components A list of tokens that are known to exist in the email body
1013 * @param bool $escapeSmarty
1014 * @param bool $returnEmptyToken
1016 * @return string The processed string
1020 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1021 if (!is_array($components) ||
empty($contact)) {
1025 foreach ($components as $name => $tokens) {
1026 if (!is_array($tokens) ||
empty($tokens)) {
1030 foreach ($tokens as $token) {
1031 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1032 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1034 elseif (!$returnEmptyToken) {
1035 //replacing empty token
1036 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1044 * Get array of string tokens
1046 * @param $string the input string to parse for tokens
1048 * @return array $tokens array of tokens mentioned in field@access public
1051 static function getTokens($string) {
1054 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1061 foreach ($matches[1] as $token) {
1062 list($type, $name) = preg_split('/\./', $token, 2);
1063 if ($name && $type) {
1064 if (!isset($tokens[$type])) {
1065 $tokens[$type] = array();
1067 $tokens[$type][] = $name;
1075 * gives required details of contacts in an indexed array format so we
1076 * can iterate in a nice loop and do token evaluation
1078 * @param $contactIDs
1079 * @param array $returnProperties of required properties
1080 * @param boolean $skipOnHold don't return on_hold contact info also.
1081 * @param boolean $skipDeceased don't return deceased contact info.
1082 * @param array $extraParams extra params
1083 * @param array $tokens the list of tokens we've extracted from the content
1084 * @param null $className
1085 * @param int $jobID the mailing list jobID - this is a legacy param
1087 * @internal param array $contactIds of contacts
1092 static function getTokenDetails($contactIDs,
1093 $returnProperties = NULL,
1095 $skipDeceased = TRUE,
1096 $extraParams = NULL,
1101 if (empty($contactIDs)) {
1102 // putting a fatal here so we can track if/when this happens
1103 CRM_Core_Error
::fatal();
1107 foreach ($contactIDs as $key => $contactID) {
1109 CRM_Core_Form
::CB_PREFIX
. $contactID,
1115 if ($skipDeceased) {
1116 $params[] = array('is_deceased', '=', 0, 0, 0);
1121 $params[] = array('on_hold', '=', 0, 0, 0);
1125 $params = array_merge($params, $extraParams);
1128 // if return properties are not passed then get all return properties
1129 if (empty($returnProperties)) {
1130 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1131 array('display_name', 'checksum', 'contact_id')
1133 foreach ($fields as $key => $val) {
1134 $returnProperties[$val] = 1;
1139 foreach ($returnProperties as $name => $dontCare) {
1140 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1146 //get the total number of contacts to fetch from database.
1147 $numberofContacts = count($contactIDs);
1148 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1150 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1152 $contactDetails = &$details[0];
1154 foreach ($contactIDs as $key => $contactID) {
1155 if (array_key_exists($contactID, $contactDetails)) {
1156 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1157 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1159 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1161 // communication Prefferance
1162 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1163 $contactDetails[$contactID]['preferred_communication_method']
1166 foreach ($contactPcm as $key => $val) {
1168 $result[$val] = $pcm[$val];
1171 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1174 foreach ($custom as $cfID) {
1175 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1176 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1182 //special case for greeting replacement
1184 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1185 if (!empty($contactDetails[$contactID][$val])) {
1186 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1192 // also call a hook and get token details
1193 CRM_Utils_Hook
::tokenValues($details[0],
1203 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1204 * specific tokens to be rendered
1206 * @param array $contactIDs - this should always be array(0) or its not anonymous - left to keep signature same
1208 * @param string $returnProperties
1209 * @param boolean $skipOnHold
1210 * @param boolean $skipDeceased
1211 * @param string $extraParams
1212 * @param array $tokens
1213 * @param string $className sent as context to the hook
1214 * @param string $jobID
1215 * @return array contactDetails with hooks swapped out
1217 function getAnonymousTokenDetails($contactIDs = array(0),
1218 $returnProperties = NULL,
1220 $skipDeceased = TRUE,
1221 $extraParams = NULL,
1225 $details = array(0 => array());
1226 // also call a hook and get token details
1227 CRM_Utils_Hook
::tokenValues($details[0],
1237 * gives required details of contribuion in an indexed array format so we
1238 * can iterate in a nice loop and do token evaluation
1240 * @param $contributionIDs
1241 * @param array $returnProperties of required properties
1242 * @param array $extraParams extra params
1243 * @param array $tokens the list of tokens we've extracted from the content
1245 * @param null $className
1247 * @internal param array $contributionId one contribution id
1248 * @internal param bool $skipOnHold don't return on_hold contact info.
1249 * @internal param bool $skipDeceased don't return deceased contact info.
1254 static function getContributionTokenDetails($contributionIDs,
1255 $returnProperties = NULL,
1256 $extraParams = NULL,
1260 //@todo - this function basically replications calling civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1261 if (empty($contributionIDs)) {
1262 // putting a fatal here so we can track if/when this happens
1263 CRM_Core_Error
::fatal();
1268 // no apiQuery helper yet, so do a loop and find contribution by id
1269 foreach ($contributionIDs as $contributionID) {
1271 $dao = new CRM_Contribute_DAO_Contribution();
1272 $dao->id
= $contributionID;
1274 if ($dao->find(TRUE)) {
1276 $details[$dao->id
] = array();
1277 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1279 // do the necessary transformation
1280 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1281 $piId = $details[$dao->id
]['payment_instrument_id'];
1282 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1283 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1285 if (!empty($details[$dao->id
]['campaign_id'])) {
1286 $campaignId = $details[$dao->id
]['campaign_id'];
1287 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1288 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1291 if (!empty($details[$dao->id
]['financial_type_id'])) {
1292 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1293 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1294 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1297 // TODO: call a hook to get token contribution details
1305 * Get Membership Token Details
1306 * @param array $membershipIDs array of membership IDS
1308 static function getMembershipTokenDetails($membershipIDs) {
1309 $memberships = civicrm_api3('membership', 'get', array('options' => array('limit' => 200000), 'membership_id' => array('IN' => (array) $membershipIDs)));
1310 return $memberships['values'];
1313 * replace greeting tokens exists in message/subject
1317 static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1319 if (!$contactDetails && !$contactId) {
1323 // check if there are any tokens
1324 $greetingTokens = self
::getTokens($tokenString);
1326 if (!empty($greetingTokens)) {
1327 // first use the existing contact object for token replacement
1328 if (!empty($contactDetails)) {
1329 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1332 // check if there are any unevaluated tokens
1333 $greetingTokens = self
::getTokens($tokenString);
1335 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1336 // so retrieve it from database
1337 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1338 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1339 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1340 $contactParams = array('contact_id' => $contactId);
1342 $greetingDetails = self
::getTokenDetails($contactParams,
1343 $greetingsReturnProperties,
1349 // again replace tokens
1350 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1361 static function flattenTokens(&$tokens) {
1362 $flattenTokens = array();
1365 'html', 'text', 'subject') as $prop) {
1366 if (!isset($tokens[$prop])) {
1369 foreach ($tokens[$prop] as $type => $names) {
1370 if (!isset($flattenTokens[$type])) {
1371 $flattenTokens[$type] = array();
1373 foreach ($names as $name) {
1374 $flattenTokens[$type][$name] = 1;
1379 return $flattenTokens;
1383 * Replace all user tokens in $str
1385 * @param string $str The string with tokens to be replaced
1387 * @param null $knownTokens
1388 * @param bool $escapeSmarty
1390 * @return string The processed string
1394 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1396 if (!$knownTokens ||
1397 !isset($knownTokens[$key])
1402 $str = preg_replace_callback(
1403 self
::tokenRegex($key),
1404 function ($matches) use($escapeSmarty) {
1405 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1414 * @param bool $escapeSmarty
1418 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1421 list($objectName, $objectValue) = explode('-', $token, 2);
1423 switch ($objectName) {
1425 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1429 $value = CRM_Core_Permission
::roleEmails($objectValue);
1433 if ($escapeSmarty) {
1434 $value = self
::tokenEscapeSmarty($value);
1443 protected static function _buildContributionTokens() {
1444 $key = 'contribution';
1445 if (self
::$_tokens[$key] == NULL) {
1446 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1447 array('campaign', 'financial_type')
1453 * store membership tokens on the static _tokens array
1455 protected static function _buildMembershipTokens() {
1456 $key = 'membership';
1457 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1458 $membershipTokens = array();
1459 $tokens = CRM_Core_SelectValues
::membershipTokens();
1460 foreach ($tokens as $token => $dontCare) {
1461 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1463 self
::$_tokens[$key] = $membershipTokens;
1468 * Replace tokens for an entity
1469 * @param string $entity
1470 * @param array $entityArray (e.g. in format from api)
1471 * @param string $str string to replace in
1472 * @param array $knownTokens array of tokens present
1473 * @param boolean $escapeSmarty
1474 * @return string string with replacements made
1476 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1477 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1481 $fn = 'get' . ucFirst($entity) . 'tokenReplacement';
1482 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1483 foreach ($knownTokens[$entity] as $token) {
1484 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1485 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1487 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1492 * Replace Contribution tokens in html
1494 * @param string $str
1495 * @param array $contribution
1496 * @param bool|string $html
1497 * @param string $knownTokens
1498 * @param bool|string $escapeSmarty
1500 * @return unknown|Ambigous <string, mixed>|mixed
1502 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1503 $key = 'contribution';
1504 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1505 return $str; //early return
1507 self
::_buildContributionTokens();
1509 // here we intersect with the list of pre-configured valid tokens
1510 // so that we remove anything we do not recognize
1511 // I hope to move this step out of here soon and
1512 // then we will just iterate on a list of tokens that are passed to us
1514 $str = preg_replace_callback(
1515 self
::tokenRegex($key),
1516 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1517 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1522 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1527 * We have a situation where we are rendering more than one token in each field because we are combining
1528 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1530 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1531 * it applies (other tokens are OK including date fields)
1533 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1534 * does - but the fields is already being formatted through a date function
1536 * @param string $separator
1537 * @param string $str
1538 * @param array $contribution
1539 * @param bool|string $html
1540 * @param string $knownTokens
1541 * @param bool|string $escapeSmarty
1543 * @return \Ambigous|mixed|string|\unknown
1545 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1546 if(empty($knownTokens['contribution'])) {
1550 if(in_array('receive_date', $knownTokens['contribution'])) {
1551 $formattedDates = array();
1552 $dates = explode($separator, $contribution['receive_date']);
1553 foreach ($dates as $date) {
1554 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1556 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1557 unset($knownTokens['contribution']['receive_date']);
1559 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1563 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1564 * - this is used by the pdfLetter task from membership search
1565 * @param string $token
1566 * @param array $membership an api result array for a single membership
1567 * @param boolean $escapeSmarty
1568 * @return string token replacement
1570 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1571 $entity = 'membership';
1572 self
::_buildMembershipTokens();
1575 $value = $membership['membership_name'];
1578 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1579 $value = $statuses[$membership['status_id']];
1583 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1585 catch (CiviCRM_API3_Exception
$e) {
1586 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1587 // api handles NULL (4.4)
1592 if (in_array($token, self
::$_tokens[$entity])) {
1593 $value = $membership[$token];
1597 $value = "{$entity}.{$token}";
1602 if ($escapeSmarty) {
1603 $value = self
::tokenEscapeSmarty($value);
1610 * @param $contribution
1612 * @param bool $escapeSmarty
1614 * @return mixed|string
1616 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1617 self
::_buildContributionTokens();
1620 case 'total_amount':
1623 case 'non_deductible_amount':
1624 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1627 case 'receive_date':
1628 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1629 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1633 if (!in_array($token, self
::$_tokens['contribution'])) {
1634 $value = "{contribution.$token}";
1637 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1643 if ($escapeSmarty) {
1644 $value = self
::tokenEscapeSmarty($value);
1650 * @return array: legacy_token => new_token
1652 static function legacyContactTokens() {
1654 'individual_prefix' => 'prefix_id',
1655 'individual_suffix' => 'suffix_id',
1656 'gender' => 'gender_id',
1657 'communication_style' => 'communication_style_id',
1662 * Formats a token list for the select2 widget
1666 static function formatTokensForDisplay($tokens) {
1667 $sorted = $output = array();
1669 // Sort in ascending order by ignoring word case
1670 natcasesort($tokens);
1672 // Attempt to place tokens into optgroups
1673 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1674 foreach ($tokens as $k => $v) {
1675 // Check to see if this token is already in a group e.g. for custom fields
1676 $split = explode(' :: ', $v);
1677 if (!empty($split[1])) {
1678 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1682 $split = explode('.', trim($k, '{}'));
1683 $entity = isset($split[1]) ?
ucfirst($split[0]) : 'Contact';
1684 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1689 foreach ($sorted as $k => $v) {
1690 $output[] = array('text' => $k, 'children' => $v);