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 * @return string The processed string
173 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
174 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
179 $value = self
::tokenEscapeSmarty($value);
181 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
186 * get< the regex for token replacement
188 * @param string $key a string indicating the the type of token to be used in the expression
190 * @return string regular expression sutiable for using in preg_replace
194 private static function tokenRegex($token_type) {
195 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
199 * escape the string so a malicious user cannot inject smarty code into the template
201 * @param string $string a string that needs to be escaped from smarty parsing
203 * @return string the escaped string
207 private static function tokenEscapeSmarty($string) {
208 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
209 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
214 * Replace all the domain-level tokens in $str
216 * @param string $str The string with tokens to be replaced
217 * @param object $domain The domain BAO
218 * @param boolean $html Replace tokens with HTML or plain text
220 * @return string The processed string
224 public static function &replaceDomainTokens(
229 $escapeSmarty = FALSE
233 !$knownTokens ||
empty($knownTokens[$key])) {
237 $str = preg_replace_callback(
238 self
::tokenRegex($key),
239 function ($matches) use(&$domain, $html, $escapeSmarty) {
240 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
247 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
248 // check if the token we were passed is valid
249 // we have to do this because this function is
250 // called only when we find a token in the string
252 $loc = &$domain->getLocationValues();
254 if (!in_array($token, self
::$_tokens['domain'])) {
255 $value = "{domain.$token}";
257 elseif ($token == 'address') {
258 static $addressCache = array();
260 $cache_key = $html ?
'address-html' : 'address-text';
261 if (array_key_exists($cache_key, $addressCache)) {
262 return $addressCache[$cache_key];
266 /* Construct the address token */
268 if (!empty($loc[$token])) {
270 $value = $loc[$token][1]['display'];
271 $value = str_replace("\n", '<br />', $value);
274 $value = $loc[$token][1]['display_text'];
276 $addressCache[$cache_key] = $value;
279 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
280 $value = $domain->$token;
282 elseif ($token == 'phone' ||
$token == 'email') {
283 /* Construct the phone and email tokens */
286 if (!empty($loc[$token])) {
287 foreach ($loc[$token] as $index => $entity) {
288 $value = $entity[$token];
295 $value = self
::tokenEscapeSmarty($value);
302 * Replace all the org-level tokens in $str
304 * @param string $str The string with tokens to be replaced
305 * @param object $org Associative array of org properties
306 * @param boolean $html Replace tokens with HTML or plain text
308 * @return string The processed string
312 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
313 self
::$_tokens['org'] =
315 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
316 array('address', 'display_name', 'checksum', 'contact_id')
320 foreach (self
::$_tokens['org'] as $token) {
321 // print "Getting token value for $token<br/><br/>";
326 /* If the string doesn't contain this token, skip it. */
328 if (!self
::token_match('org', $token, $str)) {
332 /* Construct value from $token and $contact */
336 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
337 // only generate cv if we need it
339 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
341 foreach ($cv as $cvFieldID => $value) {
342 if ($cvFieldID == $cfID) {
343 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
348 elseif ($token == 'checksum') {
349 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
352 elseif ($token == 'address') {
353 /* Build the location values array */
356 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
357 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
358 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
359 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
360 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
362 /* Construct the address token */
364 $value = CRM_Utils_Address
::format($loc);
366 $value = str_replace("\n", '<br />', $value);
370 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
373 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
380 * Replace all mailing tokens in $str
382 * @param string $str The string with tokens to be replaced
383 * @param object $mailing The mailing BAO, or null for validation
384 * @param boolean $html Replace tokens with HTML or plain text
386 * @return string The processed sstring
390 public static function &replaceMailingTokens(
395 $escapeSmarty = FALSE
398 if (!$knownTokens ||
!isset($knownTokens[$key])) {
402 $str = preg_replace_callback(
403 self
::tokenRegex($key),
404 function ($matches) use(&$mailing, $escapeSmarty) {
405 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
412 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
418 $value = $mailing ?
$mailing->id
: 'undefined';
422 $value = $mailing ?
$mailing->name
: 'Mailing Name';
426 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
427 $value = implode(', ', $groups);
431 $value = $mailing->subject
;
435 $mailingKey = $mailing->id
;
436 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
439 $value = CRM_Utils_System
::url('civicrm/mailing/view',
440 "reset=1&id={$mailingKey}",
441 TRUE, NULL, FALSE, TRUE
446 $value = CRM_Utils_System
::url('civicrm/mailing/send',
447 "reset=1&mid={$mailing->id}&continue=true",
448 TRUE, NULL, FALSE, TRUE
453 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
454 "reset=1&mid={$mailing->id}",
455 TRUE, NULL, FALSE, TRUE
460 $page = new CRM_Mailing_Page_View();
461 $value = $page->run($mailing->id
, NULL, FALSE, TRUE);
464 case 'approvalStatus':
465 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
469 $value = $mailing->approval_note
;
473 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
474 "reset=1&mid={$mailing->id}",
475 TRUE, NULL, FALSE, TRUE
480 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
484 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
488 $value = "{mailing.$token}";
493 $value = self
::tokenEscapeSmarty($value);
499 * Replace all action tokens in $str
501 * @param string $str The string with tokens to be replaced
502 * @param array $addresses Assoc. array of VERP event addresses
503 * @param array $urls Assoc. array of action URLs
504 * @param boolean $html Replace tokens with HTML or plain text
505 * @param array $knownTokens A list of tokens that are known to exist in the email body
507 * @return string The processed string
511 public static function &replaceActionTokens(
517 $escapeSmarty = FALSE
520 // here we intersect with the list of pre-configured valid tokens
521 // so that we remove anything we do not recognize
522 // I hope to move this step out of here soon and
523 // then we will just iterate on a list of tokens that are passed to us
524 if (!$knownTokens ||
empty($knownTokens[$key])) {
528 $str = preg_replace_callback(
529 self
::tokenRegex($key),
530 function ($matches) use(&$addresses, &$urls, $html, $escapeSmarty) {
531 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
538 public static function getActionTokenReplacement(
543 $escapeSmarty = FALSE
545 /* If the token is an email action, use it. Otherwise, find the
548 if (!in_array($token, self
::$_tokens['action'])) {
549 $value = "{action.$token}";
552 $value = CRM_Utils_Array
::value($token, $addresses);
554 if ($value == NULL) {
555 $value = CRM_Utils_Array
::value($token, $urls);
558 if ($value && $html) {
560 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
561 $value = "mailto:$value";
564 elseif ($value && !$html) {
565 $value = str_replace('&', '&', $value);
570 $value = self
::tokenEscapeSmarty($value);
576 * Replace all the contact-level tokens in $str with information from
579 * @param string $str The string with tokens to be replaced
580 * @param array $contact Associative array of contact properties
581 * @param boolean $html Replace tokens with HTML or plain text
582 * @param array $knownTokens A list of tokens that are known to exist in the email body
583 * @param boolean $returnBlankToken return unevaluated token if value is null
585 * @return string The processed string
589 public static function &replaceContactTokens(
594 $returnBlankToken = FALSE,
595 $escapeSmarty = FALSE
598 if (self
::$_tokens[$key] == NULL) {
599 /* This should come from UF */
601 self
::$_tokens[$key] =
603 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
604 array('checksum', 'contact_id')
608 // here we intersect with the list of pre-configured valid tokens
609 // so that we remove anything we do not recognize
610 // I hope to move this step out of here soon and
611 // then we will just iterate on a list of tokens that are passed to us
612 if (!$knownTokens ||
empty($knownTokens[$key])) {
616 $str = preg_replace_callback(
617 self
::tokenRegex($key),
618 function ($matches) use(&$contact, $html, $returnBlankToken, $escapeSmarty) {
619 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
624 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
628 public static function getContactTokenReplacement(
632 $returnBlankToken = FALSE,
633 $escapeSmarty = FALSE
635 if (self
::$_tokens['contact'] == NULL) {
636 /* This should come from UF */
638 self
::$_tokens['contact'] =
640 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
641 array('checksum', 'contact_id')
645 /* Construct value from $token and $contact */
650 // Support legacy tokens
651 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
653 // check if the token we were passed is valid
654 // we have to do this because this function is
655 // called only when we find a token in the string
657 if (!in_array($token, self
::$_tokens['contact'])) {
660 elseif ($token == 'checksum') {
661 $hash = CRM_Utils_Array
::value('hash', $contact);
662 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
663 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
671 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
673 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
674 if (is_array($value)) {
677 // Convert pseudoconstants using metadata
678 elseif ($value && is_numeric($value)) {
679 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
680 if (!empty($allFields[$token]['pseudoconstant'])) {
681 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
687 $value = str_replace('&', '&', $value);
690 // if null then return actual token
691 if ($returnBlankToken && !$value) {
696 $value = "{contact.$token}";
700 && !($returnBlankToken && $noReplace)) { // $returnBlankToken means the caller wants to do further attempts at processing unreplaced tokens -- so don't escape them yet in this case.
701 $value = self
::tokenEscapeSmarty($value);
708 * Replace all the hook tokens in $str with information from
711 * @param string $str The string with tokens to be replaced
712 * @param array $contact Associative array of contact properties (including hook token values)
713 * @param boolean $html Replace tokens with HTML or plain text
715 * @return string The processed string
719 public static function &replaceHookTokens(
724 $escapeSmarty = FALSE
726 foreach ($categories as $key) {
727 $str = preg_replace_callback(
728 self
::tokenRegex($key),
729 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
730 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
739 * Parse html through Smarty resolving any smarty functions
740 * @param string $tokenHtml
741 * @param array $entity
742 * @param string $entityType
743 * @return string html parsed through smarty
745 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
746 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
747 $smarty = CRM_Core_Smarty
::singleton();
748 // also add the tokens to the template
749 $smarty->assign_by_ref($entityType, $entity);
750 $tokenHtml = $smarty->fetch("string:$tokenHtml");
754 public static function getHookTokenReplacement(
759 $escapeSmarty = FALSE
761 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
763 if ($value && !$html) {
764 $value = str_replace('&', '&', $value);
768 $value = self
::tokenEscapeSmarty($value);
775 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
776 * for example {{token}} or \{token} will result in {token} in the final email
778 * this routine will remove the extra backslashes and braces
780 * @param $str ref to the string that will be scanned and modified
781 * @return void this function works directly on the string that is passed
785 public static function unescapeTokens(&$str) {
786 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
790 * Replace unsubscribe tokens
792 * @param string $str the string with tokens to be replaced
793 * @param object $domain The domain BAO
794 * @param array $groups The groups (if any) being unsubscribed
795 * @param boolean $html Replace tokens with html or plain text
796 * @param int $contact_id The contact ID
797 * @param string hash The security hash of the unsub event
799 * @return string The processed string
803 public static function &replaceUnsubscribeTokens(
811 if (self
::token_match('unsubscribe', 'group', $str)) {
812 if (!empty($groups)) {
813 $config = CRM_Core_Config
::singleton();
814 $base = CRM_Utils_System
::baseURL();
816 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
817 $dao = new CRM_Contact_DAO_Group();
819 while ($dao->fetch()) {
820 if (substr($dao->visibility
, 0, 6) == 'Public') {
821 $visibleGroups[] = $dao->id
;
824 $value = implode(', ', $groups);
825 self
::token_replace('unsubscribe', 'group', $value, $str);
832 * Replace resubscribe tokens
834 * @param string $str the string with tokens to be replaced
835 * @param object $domain The domain BAO
836 * @param array $groups The groups (if any) being resubscribed
837 * @param boolean $html Replace tokens with html or plain text
838 * @param int $contact_id The contact ID
839 * @param string hash The security hash of the resub event
841 * @return string The processed string
845 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
848 if (self
::token_match('resubscribe', 'group', $str)) {
849 if (!empty($groups)) {
850 $value = implode(', ', $groups);
851 self
::token_replace('resubscribe', 'group', $value, $str);
858 * Replace subscription-confirmation-request tokens
860 * @param string $str The string with tokens to be replaced
861 * @param string $group The name of the group being subscribed
862 * @param boolean $html Replace tokens with html or plain text
864 * @return string The processed string
868 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
869 if (self
::token_match('subscribe', 'group', $str)) {
870 self
::token_replace('subscribe', 'group', $group, $str);
872 if (self
::token_match('subscribe', 'url', $str)) {
873 self
::token_replace('subscribe', 'url', $url, $str);
879 * Replace subscription-invitation tokens
881 * @param string $str The string with tokens to be replaced
883 * @return string The processed string
887 public static function &replaceSubscribeInviteTokens($str) {
888 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
889 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
891 TRUE, NULL, TRUE, TRUE
893 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
896 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
897 foreach ($matches as $key => $value) {
898 $gid = substr($value, 21, -1);
899 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
900 "reset=1&gid={$gid}",
901 TRUE, NULL, TRUE, TRUE
903 $url = str_replace('&', '&', $url);
904 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
908 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
909 foreach ($matches as $key => $value) {
910 $gid = substr($value, 18, -1);
911 $config = CRM_Core_Config
::singleton();
912 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
913 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
914 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
915 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
922 * Replace welcome/confirmation tokens
924 * @param string $str The string with tokens to be replaced
925 * @param string $group The name of the group being subscribed
926 * @param boolean $html Replace tokens with html or plain text
928 * @return string The processed string
932 public static function &replaceWelcomeTokens($str, $group, $html) {
933 if (self
::token_match('welcome', 'group', $str)) {
934 self
::token_replace('welcome', 'group', $group, $str);
940 * Find unprocessed tokens (call this last)
942 * @param string $str The string to search
944 * @return array Array of tokens that weren't replaced
948 public static function &unmatchedTokens(&$str) {
949 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
950 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
955 * Find and replace tokens for each component
957 * @param string $str The string to search
958 * @param array $contact Associative array of contact properties
959 * @param array $components A list of tokens that are known to exist in the email body
961 * @return string The processed string
965 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
966 if (!is_array($components) ||
empty($contact)) {
970 foreach ($components as $name => $tokens) {
971 if (!is_array($tokens) ||
empty($tokens)) {
975 foreach ($tokens as $token) {
976 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
977 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
979 elseif (!$returnEmptyToken) {
980 //replacing empty token
981 self
::token_replace($name, $token, "", $str, $escapeSmarty);
989 * Get array of string tokens
991 * @param $string the input string to parse for tokens
993 * @return $tokens array of tokens mentioned in field
997 static function getTokens($string) {
1000 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1007 foreach ($matches[1] as $token) {
1008 list($type, $name) = preg_split('/\./', $token, 2);
1009 if ($name && $type) {
1010 if (!isset($tokens[$type])) {
1011 $tokens[$type] = array();
1013 $tokens[$type][] = $name;
1021 * gives required details of contacts in an indexed array format so we
1022 * can iterate in a nice loop and do token evaluation
1024 * @param array $contactIds of contacts
1025 * @param array $returnProperties of required properties
1026 * @param boolean $skipOnHold don't return on_hold contact info also.
1027 * @param boolean $skipDeceased don't return deceased contact info.
1028 * @param array $extraParams extra params
1029 * @param array $tokens the list of tokens we've extracted from the content
1030 * @param int $jobID the mailing list jobID - this is a legacy param
1036 static function getTokenDetails($contactIDs,
1037 $returnProperties = NULL,
1039 $skipDeceased = TRUE,
1040 $extraParams = NULL,
1045 if (empty($contactIDs)) {
1046 // putting a fatal here so we can track if/when this happens
1047 CRM_Core_Error
::fatal();
1051 foreach ($contactIDs as $key => $contactID) {
1053 CRM_Core_Form
::CB_PREFIX
. $contactID,
1059 if ($skipDeceased) {
1060 $params[] = array('is_deceased', '=', 0, 0, 0);
1065 $params[] = array('on_hold', '=', 0, 0, 0);
1069 $params = array_merge($params, $extraParams);
1072 // if return properties are not passed then get all return properties
1073 if (empty($returnProperties)) {
1074 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1075 array('display_name', 'checksum', 'contact_id')
1077 foreach ($fields as $key => $val) {
1078 $returnProperties[$val] = 1;
1083 foreach ($returnProperties as $name => $dontCare) {
1084 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1090 //get the total number of contacts to fetch from database.
1091 $numberofContacts = count($contactIDs);
1092 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1094 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1096 $contactDetails = &$details[0];
1098 foreach ($contactIDs as $key => $contactID) {
1099 if (array_key_exists($contactID, $contactDetails)) {
1100 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1101 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1103 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1105 // communication Prefferance
1106 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1107 $contactDetails[$contactID]['preferred_communication_method']
1110 foreach ($contactPcm as $key => $val) {
1112 $result[$val] = $pcm[$val];
1115 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1118 foreach ($custom as $cfID) {
1119 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1120 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1126 //special case for greeting replacement
1128 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1129 if (!empty($contactDetails[$contactID][$val])) {
1130 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1136 // also call a hook and get token details
1137 CRM_Utils_Hook
::tokenValues($details[0],
1147 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1148 * specific tokens to be rendered
1150 * @param array $contactIDs - this should always be array(0) or its not anonymous - left to keep signature same
1152 * @param string $returnProperties
1153 * @param boolean $skipOnHold
1154 * @param boolean $skipDeceased
1155 * @param string $extraParams
1156 * @param array $tokens
1157 * @param string $className sent as context to the hook
1158 * @param string $jobID
1159 * @return array contactDetails with hooks swapped out
1161 function getAnonymousTokenDetails($contactIDs = array(0),
1162 $returnProperties = NULL,
1164 $skipDeceased = TRUE,
1165 $extraParams = NULL,
1169 $details = array(0 => array());
1170 // also call a hook and get token details
1171 CRM_Utils_Hook
::tokenValues($details[0],
1180 * gives required details of contribuion in an indexed array format so we
1181 * can iterate in a nice loop and do token evaluation
1183 * @param array $contributionId one contribution id
1184 * @param array $returnProperties of required properties
1185 * @param boolean $skipOnHold don't return on_hold contact info.
1186 * @param boolean $skipDeceased don't return deceased contact info.
1187 * @param array $extraParams extra params
1188 * @param array $tokens the list of tokens we've extracted from the content
1194 static function getContributionTokenDetails($contributionIDs,
1195 $returnProperties = NULL,
1196 $extraParams = NULL,
1200 if (empty($contributionIDs)) {
1201 // putting a fatal here so we can track if/when this happens
1202 CRM_Core_Error
::fatal();
1207 // no apiQuery helper yet, so do a loop and find contribution by id
1208 foreach ($contributionIDs as $contributionID) {
1210 $dao = new CRM_Contribute_DAO_Contribution();
1211 $dao->id
= $contributionID;
1213 if ($dao->find(TRUE)) {
1215 $details[$dao->id
] = array();
1216 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1218 // do the necessary transformation
1219 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1220 $piId = $details[$dao->id
]['payment_instrument_id'];
1221 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1222 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1224 if (!empty($details[$dao->id
]['campaign_id'])) {
1225 $campaignId = $details[$dao->id
]['campaign_id'];
1226 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1227 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1230 if (!empty($details[$dao->id
]['financial_type_id'])) {
1231 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1232 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1233 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1236 // TODO: call a hook to get token contribution details
1244 * Get Membership Token Details
1245 * @param array $membershipIDs array of membership IDS
1247 static function getMembershipTokenDetails($membershipIDs) {
1248 $memberships = civicrm_api3('membership', 'get', array('options' => array('limit' => 200000), 'membership_id' => array('IN' => (array) $membershipIDs)));
1249 return $memberships['values'];
1252 * replace greeting tokens exists in message/subject
1256 static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1258 if (!$contactDetails && !$contactId) {
1262 // check if there are any tokens
1263 $greetingTokens = self
::getTokens($tokenString);
1265 if (!empty($greetingTokens)) {
1266 // first use the existing contact object for token replacement
1267 if (!empty($contactDetails)) {
1268 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1271 // check if there are any unevaluated tokens
1272 $greetingTokens = self
::getTokens($tokenString);
1274 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1275 // so retrieve it from database
1276 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1277 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1278 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1279 $contactParams = array('contact_id' => $contactId);
1281 $greetingDetails = self
::getTokenDetails($contactParams,
1282 $greetingsReturnProperties,
1288 // again replace tokens
1289 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1300 static function flattenTokens(&$tokens) {
1301 $flattenTokens = array();
1304 'html', 'text', 'subject') as $prop) {
1305 if (!isset($tokens[$prop])) {
1308 foreach ($tokens[$prop] as $type => $names) {
1309 if (!isset($flattenTokens[$type])) {
1310 $flattenTokens[$type] = array();
1312 foreach ($names as $name) {
1313 $flattenTokens[$type][$name] = 1;
1318 return $flattenTokens;
1322 * Replace all user tokens in $str
1324 * @param string $str The string with tokens to be replaced
1326 * @return string The processed string
1330 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1332 if (!$knownTokens ||
1333 !isset($knownTokens[$key])
1338 $str = preg_replace_callback(
1339 self
::tokenRegex($key),
1340 function ($matches) use($escapeSmarty) {
1341 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1348 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1351 list($objectName, $objectValue) = explode('-', $token, 2);
1353 switch ($objectName) {
1355 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1359 $value = CRM_Core_Permission
::roleEmails($objectValue);
1363 if ($escapeSmarty) {
1364 $value = self
::tokenEscapeSmarty($value);
1371 protected static function _buildContributionTokens() {
1372 $key = 'contribution';
1373 if (self
::$_tokens[$key] == NULL) {
1374 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1375 array('campaign', 'financial_type')
1381 * store membership tokens on the static _tokens array
1383 protected static function _buildMembershipTokens() {
1384 $key = 'membership';
1385 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1386 $membershipTokens = array();
1387 $tokens = CRM_Core_SelectValues
::membershipTokens();
1388 foreach ($tokens as $token => $dontCare) {
1389 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1391 self
::$_tokens[$key] = $membershipTokens;
1396 * Replace tokens for an entity
1397 * @param string $entity
1398 * @param array $entityArray (e.g. in format from api)
1399 * @param string $str string to replace in
1400 * @param array $knownTokens array of tokens present
1401 * @param boolean $escapeSmarty
1402 * @return string string with replacements made
1404 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1405 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1409 $fn = 'get' . ucFirst($entity) . 'tokenReplacement';
1410 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1411 foreach ($knownTokens[$entity] as $token) {
1412 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1413 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1415 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1419 public static function &replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1420 self
::_buildContributionTokens();
1422 // here we intersect with the list of pre-configured valid tokens
1423 // so that we remove anything we do not recognize
1424 // I hope to move this step out of here soon and
1425 // then we will just iterate on a list of tokens that are passed to us
1426 $key = 'contribution';
1427 if (!$knownTokens ||
empty($knownTokens[$key])) {
1431 $str = preg_replace_callback(
1432 self
::tokenRegex($key),
1433 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1434 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1439 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1444 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1445 * - this is used by the pdfLetter task from membership search
1446 * @param string $token
1447 * @param array $membership an api result array for a single membership
1448 * @param boolean $escapeSmarty
1449 * @return string token replacement
1451 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1452 $entity = 'membership';
1453 self
::_buildMembershipTokens();
1456 $value = $membership['membership_name'];
1459 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1460 $value = $statuses[$membership['status_id']];
1464 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1466 catch (CiviCRM_API3_Exception
$e) {
1467 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1468 // api handles NULL (4.4)
1473 if (in_array($token, self
::$_tokens[$entity])) {
1474 $value = $membership[$token];
1478 $value = "{$entity}.{$token}";
1483 if ($escapeSmarty) {
1484 $value = self
::tokenEscapeSmarty($value);
1489 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1490 self
::_buildContributionTokens();
1493 case 'total_amount':
1496 case 'non_deductible_amount':
1497 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1500 case 'receive_date':
1501 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1502 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1506 if (!in_array($token, self
::$_tokens['contribution'])) {
1507 $value = "{contribution.$token}";
1510 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1516 if ($escapeSmarty) {
1517 $value = self
::tokenEscapeSmarty($value);
1522 function getPermissionEmails($permissionName) {}
1524 function getRoleEmails($roleName) {}
1527 * @return array: legacy_token => new_token
1529 static function legacyContactTokens() {
1531 'individual_prefix' => 'prefix_id',
1532 'individual_suffix' => 'suffix_id',
1533 'gender' => 'gender_id',
1534 'communication_style' => 'communication_style_id',
1539 * Formats a token list for the select2 widget
1543 static function formatTokensForDisplay($tokens) {
1544 $sorted = $output = array();
1546 // Sort in ascending order by ignoring word case
1547 natcasesort($tokens);
1549 // Attempt to place tokens into optgroups
1550 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1551 foreach ($tokens as $k => $v) {
1552 // Check to see if this token is already in a group e.g. for custom fields
1553 $split = explode(' :: ', $v);
1554 if (!empty($split[1])) {
1555 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1559 $split = explode('.', trim($k, '{}'));
1560 $entity = isset($split[1]) ?
ucfirst($split[0]) : 'Contact';
1561 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1566 foreach ($sorted as $k => $v) {
1567 $output[] = array('text' => $k, 'children' => $v);