3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2014
37 * Class to abstract token replacement
39 class CRM_Utils_Token
{
40 static $_requiredTokens = NULL;
42 static $_tokens = array(
69 // we extract the stuff after the role / permission and return the
70 // civicrm email addresses of all users with that role / permission
71 // useful with rules integration
75 // populate this dynamically
77 // populate this dynamically
78 'contribution' => NULL,
87 'subscribe' => array( 'group' ),
88 'unsubscribe' => array( 'group' ),
89 'resubscribe' => array( 'group' ),
90 'welcome' => array( 'group' ),
94 * Check a string (mailing body) for required tokens.
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
102 public static function requiredTokens(&$str) {
103 if (self
::$_requiredTokens == NULL) {
104 self
::$_requiredTokens = array(
105 'domain.address' => ts("Domain address - displays your organization's postal address."),
106 'action.optOutUrl or action.unsubscribeUrl' => array(
107 'action.optOut' => ts("'Opt out via email' - displays an email address for recipients to opt out of receiving emails from your organization."),
108 '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."),
109 'action.unsubscribe' => ts("'Unsubscribe via email' - displays an email address for recipients to unsubscribe from the specific mailing list used to send this message."),
110 '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."),
116 foreach (self
::$_requiredTokens as $token => $value) {
117 if (!is_array($value)) {
118 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
119 $missing[$token] = $value;
125 foreach ($value as $t => $d) {
127 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
132 $missing[$token] = $desc;
137 if (empty($missing)) {
144 * Wrapper for token matching
146 * @param string $type The token type (domain,mailing,contact,action)
147 * @param string $var The token variable
148 * @param string $str The string to search
150 * @return boolean Was there a match
153 public static function token_match($type, $var, &$str) {
154 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
155 return preg_match("/(^|[^\{])$token/", $str);
159 * Wrapper for token replacing
161 * @param string $type The token type
162 * @param string $var The token variable
163 * @param string $value The value to substitute for the token
164 * @param string (reference) $str The string to replace in
166 * @param bool $escapeSmarty
168 * @return string The processed string
171 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
172 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
177 $value = self
::tokenEscapeSmarty($value);
179 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
184 * Get< the regex for token replacement
186 * @param string $token_type a string indicating the the type of token to be used in the expression
188 * @return string regular expression sutiable for using in preg_replace
191 private static function tokenRegex($token_type) {
192 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
196 * Escape the string so a malicious user cannot inject smarty code into the template
198 * @param string $string a string that needs to be escaped from smarty parsing
200 * @return string the escaped string
203 private static function tokenEscapeSmarty($string) {
204 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
205 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
209 * Replace all the domain-level tokens in $str
211 * @param string $str The string with tokens to be replaced
212 * @param object $domain The domain BAO
213 * @param boolean $html Replace tokens with HTML or plain text
215 * @param null $knownTokens
216 * @param bool $escapeSmarty
218 * @return string The processed string
221 public static function &replaceDomainTokens(
226 $escapeSmarty = FALSE
230 !$knownTokens ||
empty($knownTokens[$key])) {
234 $str = preg_replace_callback(
235 self
::tokenRegex($key),
236 function ($matches) use(&$domain, $html, $escapeSmarty) {
237 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
248 * @param bool $escapeSmarty
250 * @return mixed|null|string
252 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
253 // check if the token we were passed is valid
254 // we have to do this because this function is
255 // called only when we find a token in the string
257 $loc = &$domain->getLocationValues();
259 if (!in_array($token, self
::$_tokens['domain'])) {
260 $value = "{domain.$token}";
262 elseif ($token == 'address') {
263 static $addressCache = array();
265 $cache_key = $html ?
'address-html' : 'address-text';
266 if (array_key_exists($cache_key, $addressCache)) {
267 return $addressCache[$cache_key];
271 /* Construct the address token */
273 if (!empty($loc[$token])) {
275 $value = $loc[$token][1]['display'];
276 $value = str_replace("\n", '<br />', $value);
279 $value = $loc[$token][1]['display_text'];
281 $addressCache[$cache_key] = $value;
284 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
285 $value = $domain->$token;
287 elseif ($token == 'phone' ||
$token == 'email') {
288 /* Construct the phone and email tokens */
291 if (!empty($loc[$token])) {
292 foreach ($loc[$token] as $index => $entity) {
293 $value = $entity[$token];
300 $value = self
::tokenEscapeSmarty($value);
307 * Replace all the org-level tokens in $str
309 * @param string $str The string with tokens to be replaced
310 * @param object $org Associative array of org properties
311 * @param boolean $html Replace tokens with HTML or plain text
313 * @param bool $escapeSmarty
315 * @return string The processed string
318 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
319 self
::$_tokens['org'] =
321 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
322 array('address', 'display_name', 'checksum', 'contact_id')
326 foreach (self
::$_tokens['org'] as $token) {
327 // print "Getting token value for $token<br/><br/>";
332 /* If the string doesn't contain this token, skip it. */
334 if (!self
::token_match('org', $token, $str)) {
338 /* Construct value from $token and $contact */
342 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
343 // only generate cv if we need it
345 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
347 foreach ($cv as $cvFieldID => $value) {
348 if ($cvFieldID == $cfID) {
349 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
354 elseif ($token == 'checksum') {
355 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
358 elseif ($token == 'address') {
359 /* Build the location values array */
362 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
363 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
364 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
365 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
366 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
368 /* Construct the address token */
370 $value = CRM_Utils_Address
::format($loc);
372 $value = str_replace("\n", '<br />', $value);
376 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
379 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
386 * Replace all mailing tokens in $str
388 * @param string $str The string with tokens to be replaced
389 * @param object $mailing The mailing BAO, or null for validation
390 * @param boolean $html Replace tokens with HTML or plain text
392 * @param null $knownTokens
393 * @param bool $escapeSmarty
395 * @return string The processed sstring
398 public static function &replaceMailingTokens(
403 $escapeSmarty = FALSE
406 if (!$knownTokens ||
!isset($knownTokens[$key])) {
410 $str = preg_replace_callback(
411 self
::tokenRegex($key),
412 function ($matches) use(&$mailing, $escapeSmarty) {
413 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
423 * @param bool $escapeSmarty
427 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
433 $value = $mailing ?
$mailing->id
: 'undefined';
437 $value = $mailing ?
$mailing->name
: 'Mailing Name';
441 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
442 $value = implode(', ', $groups);
446 $value = $mailing->subject
;
450 $mailingKey = $mailing->id
;
451 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
454 $value = CRM_Utils_System
::url('civicrm/mailing/view',
455 "reset=1&id={$mailingKey}",
456 TRUE, NULL, FALSE, TRUE
461 $value = CRM_Utils_System
::url('civicrm/mailing/send',
462 "reset=1&mid={$mailing->id}&continue=true",
463 TRUE, NULL, FALSE, TRUE
468 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
469 "reset=1&mid={$mailing->id}",
470 TRUE, NULL, FALSE, TRUE
475 $page = new CRM_Mailing_Page_View();
476 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
479 case 'approvalStatus':
480 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
484 $value = $mailing->approval_note
;
488 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
489 "reset=1&mid={$mailing->id}",
490 TRUE, NULL, FALSE, TRUE
495 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
499 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
503 $value = "{mailing.$token}";
508 $value = self
::tokenEscapeSmarty($value);
514 * Replace all action tokens in $str
516 * @param string $str The string with tokens to be replaced
517 * @param array $addresses Assoc. array of VERP event addresses
518 * @param array $urls Assoc. array of action URLs
519 * @param boolean $html Replace tokens with HTML or plain text
520 * @param array $knownTokens A list of tokens that are known to exist in the email body
522 * @param bool $escapeSmarty
524 * @return string The processed string
527 public static function &replaceActionTokens(
533 $escapeSmarty = FALSE
536 // here we intersect with the list of pre-configured valid tokens
537 // so that we remove anything we do not recognize
538 // I hope to move this step out of here soon and
539 // then we will just iterate on a list of tokens that are passed to us
540 if (!$knownTokens ||
empty($knownTokens[$key])) {
544 $str = preg_replace_callback(
545 self
::tokenRegex($key),
546 function ($matches) use(&$addresses, &$urls, $html, $escapeSmarty) {
547 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
559 * @param bool $escapeSmarty
561 * @return mixed|string
563 public static function getActionTokenReplacement(
568 $escapeSmarty = FALSE
570 /* If the token is an email action, use it. Otherwise, find the
573 if (!in_array($token, self
::$_tokens['action'])) {
574 $value = "{action.$token}";
577 $value = CRM_Utils_Array
::value($token, $addresses);
579 if ($value == NULL) {
580 $value = CRM_Utils_Array
::value($token, $urls);
583 if ($value && $html) {
585 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
586 $value = "mailto:$value";
589 elseif ($value && !$html) {
590 $value = str_replace('&', '&', $value);
595 $value = self
::tokenEscapeSmarty($value);
601 * Replace all the contact-level tokens in $str with information from
604 * @param string $str The string with tokens to be replaced
605 * @param array $contact Associative array of contact properties
606 * @param boolean $html Replace tokens with HTML or plain text
607 * @param array $knownTokens A list of tokens that are known to exist in the email body
608 * @param boolean $returnBlankToken return unevaluated token if value is null
610 * @param bool $escapeSmarty
612 * @return string The processed string
615 public static function &replaceContactTokens(
620 $returnBlankToken = FALSE,
621 $escapeSmarty = FALSE
624 if (self
::$_tokens[$key] == NULL) {
625 /* This should come from UF */
627 self
::$_tokens[$key] =
629 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
630 array('checksum', 'contact_id')
634 // here we intersect with the list of pre-configured valid tokens
635 // so that we remove anything we do not recognize
636 // I hope to move this step out of here soon and
637 // then we will just iterate on a list of tokens that are passed to us
638 if (!$knownTokens ||
empty($knownTokens[$key])) {
642 $str = preg_replace_callback(
643 self
::tokenRegex($key),
644 function ($matches) use(&$contact, $html, $returnBlankToken, $escapeSmarty) {
645 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
650 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
658 * @param bool $returnBlankToken
659 * @param bool $escapeSmarty
661 * @return bool|mixed|null|string
663 public static function getContactTokenReplacement(
667 $returnBlankToken = FALSE,
668 $escapeSmarty = FALSE
670 if (self
::$_tokens['contact'] == NULL) {
671 /* This should come from UF */
673 self
::$_tokens['contact'] =
675 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
676 array('checksum', 'contact_id')
680 /* Construct value from $token and $contact */
685 // Support legacy tokens
686 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
688 // check if the token we were passed is valid
689 // we have to do this because this function is
690 // called only when we find a token in the string
692 if (!in_array($token, self
::$_tokens['contact'])) {
695 elseif ($token == 'checksum') {
696 $hash = CRM_Utils_Array
::value('hash', $contact);
697 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
698 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
706 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
708 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
709 if (is_array($value)) {
712 // Convert pseudoconstants using metadata
713 elseif ($value && is_numeric($value)) {
714 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
715 if (!empty($allFields[$token]['pseudoconstant'])) {
716 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
722 $value = str_replace('&', '&', $value);
725 // if null then return actual token
726 if ($returnBlankToken && !$value) {
731 $value = "{contact.$token}";
735 && !($returnBlankToken && $noReplace)) { // $returnBlankToken means the caller wants to do further attempts at processing unreplaced tokens -- so don't escape them yet in this case.
736 $value = self
::tokenEscapeSmarty($value);
743 * Replace all the hook tokens in $str with information from
746 * @param string $str The string with tokens to be replaced
747 * @param array $contact Associative array of contact properties (including hook token values)
749 * @param boolean $html Replace tokens with HTML or plain text
751 * @param bool $escapeSmarty
753 * @return string The processed string
756 public static function &replaceHookTokens(
761 $escapeSmarty = FALSE
763 foreach ($categories as $key) {
764 $str = preg_replace_callback(
765 self
::tokenRegex($key),
766 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
767 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
776 * Parse html through Smarty resolving any smarty functions
777 * @param string $tokenHtml
778 * @param array $entity
779 * @param string $entityType
780 * @return string html parsed through smarty
782 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
783 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
784 $smarty = CRM_Core_Smarty
::singleton();
785 // also add the tokens to the template
786 $smarty->assign_by_ref($entityType, $entity);
787 $tokenHtml = $smarty->fetch("string:$tokenHtml");
797 * @param bool $escapeSmarty
799 * @return mixed|string
801 public static function getHookTokenReplacement(
806 $escapeSmarty = FALSE
808 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
810 if ($value && !$html) {
811 $value = str_replace('&', '&', $value);
815 $value = self
::tokenEscapeSmarty($value);
822 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
823 * for example {{token}} or \{token} will result in {token} in the final email
825 * this routine will remove the extra backslashes and braces
827 * @param $str ref to the string that will be scanned and modified
828 * @return void this function works directly on the string that is passed
832 public static function unescapeTokens(&$str) {
833 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
837 * Replace unsubscribe tokens
839 * @param string $str the string with tokens to be replaced
840 * @param object $domain The domain BAO
841 * @param array $groups The groups (if any) being unsubscribed
842 * @param boolean $html Replace tokens with html or plain text
843 * @param int $contact_id The contact ID
844 * @param string hash The security hash of the unsub event
846 * @return string The processed string
849 public static function &replaceUnsubscribeTokens(
857 if (self
::token_match('unsubscribe', 'group', $str)) {
858 if (!empty($groups)) {
859 $config = CRM_Core_Config
::singleton();
860 $base = CRM_Utils_System
::baseURL();
862 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
863 $dao = new CRM_Contact_DAO_Group();
865 while ($dao->fetch()) {
866 if (substr($dao->visibility
, 0, 6) == 'Public') {
867 $visibleGroups[] = $dao->id
;
870 $value = implode(', ', $groups);
871 self
::token_replace('unsubscribe', 'group', $value, $str);
878 * Replace resubscribe tokens
880 * @param string $str the string with tokens to be replaced
881 * @param object $domain The domain BAO
882 * @param array $groups The groups (if any) being resubscribed
883 * @param boolean $html Replace tokens with html or plain text
884 * @param int $contact_id The contact ID
885 * @param string hash The security hash of the resub event
887 * @return string The processed string
890 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
893 if (self
::token_match('resubscribe', 'group', $str)) {
894 if (!empty($groups)) {
895 $value = implode(', ', $groups);
896 self
::token_replace('resubscribe', 'group', $value, $str);
903 * Replace subscription-confirmation-request tokens
905 * @param string $str The string with tokens to be replaced
906 * @param string $group The name of the group being subscribed
908 * @param boolean $html Replace tokens with html or plain text
910 * @return string The processed string
913 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
914 if (self
::token_match('subscribe', 'group', $str)) {
915 self
::token_replace('subscribe', 'group', $group, $str);
917 if (self
::token_match('subscribe', 'url', $str)) {
918 self
::token_replace('subscribe', 'url', $url, $str);
924 * Replace subscription-invitation tokens
926 * @param string $str The string with tokens to be replaced
928 * @return string The processed string
931 public static function &replaceSubscribeInviteTokens($str) {
932 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
933 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
935 TRUE, NULL, TRUE, TRUE
937 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
940 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
941 foreach ($matches as $key => $value) {
942 $gid = substr($value, 21, -1);
943 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
944 "reset=1&gid={$gid}",
945 TRUE, NULL, TRUE, TRUE
947 $url = str_replace('&', '&', $url);
948 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
952 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
953 foreach ($matches as $key => $value) {
954 $gid = substr($value, 18, -1);
955 $config = CRM_Core_Config
::singleton();
956 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
957 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
958 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
959 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
966 * Replace welcome/confirmation tokens
968 * @param string $str The string with tokens to be replaced
969 * @param string $group The name of the group being subscribed
970 * @param boolean $html Replace tokens with html or plain text
972 * @return string The processed string
975 public static function &replaceWelcomeTokens($str, $group, $html) {
976 if (self
::token_match('welcome', 'group', $str)) {
977 self
::token_replace('welcome', 'group', $group, $str);
983 * Find unprocessed tokens (call this last)
985 * @param string $str The string to search
987 * @return array Array of tokens that weren't replaced
990 public static function &unmatchedTokens(&$str) {
991 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
992 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
997 * Find and replace tokens for each component
999 * @param string $str The string to search
1000 * @param array $contact Associative array of contact properties
1001 * @param array $components A list of tokens that are known to exist in the email body
1003 * @param bool $escapeSmarty
1004 * @param bool $returnEmptyToken
1006 * @return string The processed string
1009 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1010 if (!is_array($components) ||
empty($contact)) {
1014 foreach ($components as $name => $tokens) {
1015 if (!is_array($tokens) ||
empty($tokens)) {
1019 foreach ($tokens as $token) {
1020 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1021 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1023 elseif (!$returnEmptyToken) {
1024 //replacing empty token
1025 self
::token_replace($name, $token, "", $str, $escapeSmarty);
1033 * Get array of string tokens
1035 * @param $string the input string to parse for tokens
1037 * @return array $tokens array of tokens mentioned in field@access public
1040 public static function getTokens($string) {
1043 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1050 foreach ($matches[1] as $token) {
1051 list($type, $name) = preg_split('/\./', $token, 2);
1052 if ($name && $type) {
1053 if (!isset($tokens[$type])) {
1054 $tokens[$type] = array();
1056 $tokens[$type][] = $name;
1064 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1065 * and getTokens appears to be historical rather than intentional and should be reviewed
1067 * @return array fields to pass in as return properties when populating token
1070 public static function getReturnProperties(&$string) {
1071 $returnProperties = array();
1073 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1079 foreach ($matches[1] as $token) {
1080 list($type, $name) = preg_split('/\./', $token, 2);
1082 $returnProperties["{$name}"] = 1;
1087 return $returnProperties;
1091 * Gives required details of contacts in an indexed array format so we
1092 * can iterate in a nice loop and do token evaluation
1094 * @param $contactIDs
1095 * @param array $returnProperties of required properties
1096 * @param boolean $skipOnHold don't return on_hold contact info also.
1097 * @param boolean $skipDeceased don't return deceased contact info.
1098 * @param array $extraParams extra params
1099 * @param array $tokens the list of tokens we've extracted from the content
1100 * @param null $className
1101 * @param int $jobID the mailing list jobID - this is a legacy param
1106 static function getTokenDetails($contactIDs,
1107 $returnProperties = NULL,
1109 $skipDeceased = TRUE,
1110 $extraParams = NULL,
1115 if (empty($contactIDs)) {
1116 // putting a fatal here so we can track if/when this happens
1117 CRM_Core_Error
::fatal();
1121 foreach ($contactIDs as $key => $contactID) {
1123 CRM_Core_Form
::CB_PREFIX
. $contactID,
1129 if ($skipDeceased) {
1130 $params[] = array('is_deceased', '=', 0, 0, 0);
1135 $params[] = array('on_hold', '=', 0, 0, 0);
1139 $params = array_merge($params, $extraParams);
1142 // if return properties are not passed then get all return properties
1143 if (empty($returnProperties)) {
1144 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1145 array('display_name', 'checksum', 'contact_id')
1147 foreach ($fields as $key => $val) {
1148 $returnProperties[$val] = 1;
1153 foreach ($returnProperties as $name => $dontCare) {
1154 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1160 //get the total number of contacts to fetch from database.
1161 $numberofContacts = count($contactIDs);
1162 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1164 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1166 $contactDetails = &$details[0];
1168 foreach ($contactIDs as $key => $contactID) {
1169 if (array_key_exists($contactID, $contactDetails)) {
1170 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1171 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1173 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1175 // communication Prefferance
1176 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1177 $contactDetails[$contactID]['preferred_communication_method']
1180 foreach ($contactPcm as $key => $val) {
1182 $result[$val] = $pcm[$val];
1185 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1188 foreach ($custom as $cfID) {
1189 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1190 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1196 //special case for greeting replacement
1198 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1199 if (!empty($contactDetails[$contactID][$val])) {
1200 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1206 // also call a hook and get token details
1207 CRM_Utils_Hook
::tokenValues($details[0],
1217 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1218 * specific tokens to be rendered
1220 * @param array $contactIDs - this should always be array(0) or its not anonymous - left to keep signature same
1222 * @param string $returnProperties
1223 * @param boolean $skipOnHold
1224 * @param boolean $skipDeceased
1225 * @param string $extraParams
1226 * @param array $tokens
1227 * @param string $className sent as context to the hook
1228 * @param string $jobID
1229 * @return array contactDetails with hooks swapped out
1231 public function getAnonymousTokenDetails($contactIDs = array(0),
1232 $returnProperties = NULL,
1234 $skipDeceased = TRUE,
1235 $extraParams = NULL,
1239 $details = array(0 => array());
1240 // also call a hook and get token details
1241 CRM_Utils_Hook
::tokenValues($details[0],
1251 * Gives required details of contribuion in an indexed array format so we
1252 * can iterate in a nice loop and do token evaluation
1254 * @param array $contributionIDs
1255 * @param array $returnProperties of required properties
1256 * @param array $extraParams extra params
1257 * @param array $tokens the list of tokens we've extracted from the content
1258 * @param string $className
1263 static function getContributionTokenDetails($contributionIDs,
1264 $returnProperties = NULL,
1265 $extraParams = NULL,
1269 //@todo - this function basically replications calling civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1270 if (empty($contributionIDs)) {
1271 // putting a fatal here so we can track if/when this happens
1272 CRM_Core_Error
::fatal();
1277 // no apiQuery helper yet, so do a loop and find contribution by id
1278 foreach ($contributionIDs as $contributionID) {
1280 $dao = new CRM_Contribute_DAO_Contribution();
1281 $dao->id
= $contributionID;
1283 if ($dao->find(TRUE)) {
1285 $details[$dao->id
] = array();
1286 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1288 // do the necessary transformation
1289 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1290 $piId = $details[$dao->id
]['payment_instrument_id'];
1291 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1292 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1294 if (!empty($details[$dao->id
]['campaign_id'])) {
1295 $campaignId = $details[$dao->id
]['campaign_id'];
1296 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1297 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1300 if (!empty($details[$dao->id
]['financial_type_id'])) {
1301 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1302 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1303 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1306 // TODO: call a hook to get token contribution details
1314 * Get Membership Token Details
1315 * @param array $membershipIDs array of membership IDS
1317 public static function getMembershipTokenDetails($membershipIDs) {
1318 $memberships = civicrm_api3('membership', 'get', array('options' => array('limit' => 200000), 'membership_id' => array('IN' => (array) $membershipIDs)));
1319 return $memberships['values'];
1322 * Replace greeting tokens exists in message/subject
1325 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1327 if (!$contactDetails && !$contactId) {
1331 // check if there are any tokens
1332 $greetingTokens = self
::getTokens($tokenString);
1334 if (!empty($greetingTokens)) {
1335 // first use the existing contact object for token replacement
1336 if (!empty($contactDetails)) {
1337 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1340 // check if there are any unevaluated tokens
1341 $greetingTokens = self
::getTokens($tokenString);
1343 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1344 // so retrieve it from database
1345 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1346 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1347 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1348 $contactParams = array('contact_id' => $contactId);
1350 $greetingDetails = self
::getTokenDetails($contactParams,
1351 $greetingsReturnProperties,
1357 // again replace tokens
1358 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1367 // check if there are still any unevaluated tokens
1368 $remainingTokens = self
::getTokens($tokenString);
1370 // contact related $greetingTokens not empty, there are customized or hook tokens to replace
1371 if (!empty($remainingTokens['contact']) ) {
1372 // Fill the return properties array
1373 $greetingTokens = $remainingTokens['contact'];
1374 reset($greetingTokens);
1375 $greetingsReturnProperties = array();
1376 while(list($key) = each($greetingTokens)) {
1377 $props = array_flip(CRM_Utils_Array
::value($key, $greetingTokens));
1378 $props = array_fill_keys(array_keys($props), 1);
1379 $greetingsReturnProperties = $greetingsReturnProperties +
$props;
1381 $contactParams = array('contact_id' => $contactId);
1382 $greetingDetails = self
::getTokenDetails($contactParams,
1383 $greetingsReturnProperties,
1388 // Prepare variables for calling replaceHookTokens
1389 $categories = array_keys($greetingTokens);
1390 list($contact) = $greetingDetails;
1391 // Replace tokens defined in Hooks.
1392 $tokenString = CRM_Utils_Token
::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1402 public static function flattenTokens(&$tokens) {
1403 $flattenTokens = array();
1406 'html', 'text', 'subject') as $prop) {
1407 if (!isset($tokens[$prop])) {
1410 foreach ($tokens[$prop] as $type => $names) {
1411 if (!isset($flattenTokens[$type])) {
1412 $flattenTokens[$type] = array();
1414 foreach ($names as $name) {
1415 $flattenTokens[$type][$name] = 1;
1420 return $flattenTokens;
1424 * Replace all user tokens in $str
1426 * @param string $str The string with tokens to be replaced
1428 * @param null $knownTokens
1429 * @param bool $escapeSmarty
1431 * @return string The processed string
1434 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1436 if (!$knownTokens ||
1437 !isset($knownTokens[$key])
1442 $str = preg_replace_callback(
1443 self
::tokenRegex($key),
1444 function ($matches) use($escapeSmarty) {
1445 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1454 * @param bool $escapeSmarty
1458 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1461 list($objectName, $objectValue) = explode('-', $token, 2);
1463 switch ($objectName) {
1465 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1469 $value = CRM_Core_Permission
::roleEmails($objectValue);
1473 if ($escapeSmarty) {
1474 $value = self
::tokenEscapeSmarty($value);
1483 protected static function _buildContributionTokens() {
1484 $key = 'contribution';
1485 if (self
::$_tokens[$key] == NULL) {
1486 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1487 array('campaign', 'financial_type')
1493 * Store membership tokens on the static _tokens array
1495 protected static function _buildMembershipTokens() {
1496 $key = 'membership';
1497 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1498 $membershipTokens = array();
1499 $tokens = CRM_Core_SelectValues
::membershipTokens();
1500 foreach ($tokens as $token => $dontCare) {
1501 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1503 self
::$_tokens[$key] = $membershipTokens;
1508 * Replace tokens for an entity
1509 * @param string $entity
1510 * @param array $entityArray (e.g. in format from api)
1511 * @param string $str string to replace in
1512 * @param array $knownTokens array of tokens present
1513 * @param boolean $escapeSmarty
1514 * @return string string with replacements made
1516 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1517 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1521 $fn = 'get' . ucFirst($entity) . 'tokenReplacement';
1522 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1523 foreach ($knownTokens[$entity] as $token) {
1524 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1525 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1527 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1532 * Replace Contribution tokens in html
1534 * @param string $str
1535 * @param array $contribution
1536 * @param bool|string $html
1537 * @param string $knownTokens
1538 * @param bool|string $escapeSmarty
1540 * @return unknown|Ambigous <string, mixed>|mixed
1542 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1543 $key = 'contribution';
1544 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1545 return $str; //early return
1547 self
::_buildContributionTokens();
1549 // here we intersect with the list of pre-configured valid tokens
1550 // so that we remove anything we do not recognize
1551 // I hope to move this step out of here soon and
1552 // then we will just iterate on a list of tokens that are passed to us
1554 $str = preg_replace_callback(
1555 self
::tokenRegex($key),
1556 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1557 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1562 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1567 * We have a situation where we are rendering more than one token in each field because we are combining
1568 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1570 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1571 * it applies (other tokens are OK including date fields)
1573 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1574 * does - but the fields is already being formatted through a date function
1576 * @param string $separator
1577 * @param string $str
1578 * @param array $contribution
1579 * @param bool|string $html
1580 * @param string $knownTokens
1581 * @param bool|string $escapeSmarty
1583 * @return \Ambigous|mixed|string|\unknown
1585 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1586 if(empty($knownTokens['contribution'])) {
1590 if(in_array('receive_date', $knownTokens['contribution'])) {
1591 $formattedDates = array();
1592 $dates = explode($separator, $contribution['receive_date']);
1593 foreach ($dates as $date) {
1594 $formattedDates[] = CRM_Utils_Date
::customFormat($date, NULL, array('j', 'm', 'Y'));
1596 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1597 unset($knownTokens['contribution']['receive_date']);
1599 return self
::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1603 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1604 * - this is used by the pdfLetter task from membership search
1605 * @param string $token
1606 * @param array $membership an api result array for a single membership
1607 * @param boolean $escapeSmarty
1608 * @return string token replacement
1610 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1611 $entity = 'membership';
1612 self
::_buildMembershipTokens();
1615 $value = $membership['membership_name'];
1618 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1619 $value = $statuses[$membership['status_id']];
1623 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1625 catch (CiviCRM_API3_Exception
$e) {
1626 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1627 // api handles NULL (4.4)
1632 if (in_array($token, self
::$_tokens[$entity])) {
1633 $value = $membership[$token];
1637 $value = "{$entity}.{$token}";
1642 if ($escapeSmarty) {
1643 $value = self
::tokenEscapeSmarty($value);
1650 * @param $contribution
1652 * @param bool $escapeSmarty
1654 * @return mixed|string
1656 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1657 self
::_buildContributionTokens();
1660 case 'total_amount':
1663 case 'non_deductible_amount':
1664 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1667 case 'receive_date':
1668 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1669 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1673 if (!in_array($token, self
::$_tokens['contribution'])) {
1674 $value = "{contribution.$token}";
1677 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1683 if ($escapeSmarty) {
1684 $value = self
::tokenEscapeSmarty($value);
1690 * @return array: legacy_token => new_token
1692 public static function legacyContactTokens() {
1694 'individual_prefix' => 'prefix_id',
1695 'individual_suffix' => 'suffix_id',
1696 'gender' => 'gender_id',
1697 'communication_style' => 'communication_style_id',
1702 * Formats a token list for the select2 widget
1706 public static function formatTokensForDisplay($tokens) {
1707 $sorted = $output = array();
1709 // Sort in ascending order by ignoring word case
1710 natcasesort($tokens);
1712 // Attempt to place tokens into optgroups
1713 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1714 foreach ($tokens as $k => $v) {
1715 // Check to see if this token is already in a group e.g. for custom fields
1716 $split = explode(' :: ', $v);
1717 if (!empty($split[1])) {
1718 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1722 $split = explode('.', trim($k, '{}'));
1723 if (isset($split[1])) {
1724 $entity = array_key_exists($split[1], CRM_Core_DAO_Address
::export()) ?
'Address' : ucfirst($split[0]);
1727 $entity = 'Contact';
1729 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1734 foreach ($sorted as $k => $v) {
1735 $output[] = array('text' => $k, 'children' => $v);