3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
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 $value = CRM_Utils_System
::url('civicrm/mailing/view',
436 "reset=1&id={$mailing->id}",
437 TRUE, NULL, FALSE, TRUE
442 $value = CRM_Utils_System
::url('civicrm/mailing/send',
443 "reset=1&mid={$mailing->id}&continue=true",
444 TRUE, NULL, FALSE, TRUE
449 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
450 "reset=1&mid={$mailing->id}",
451 TRUE, NULL, FALSE, TRUE
456 $page = new CRM_Mailing_Page_View();
457 $value = $page->run($mailing->id
, NULL, FALSE);
460 case 'approvalStatus':
461 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
465 $value = $mailing->approval_note
;
469 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
470 "reset=1&mid={$mailing->id}",
471 TRUE, NULL, FALSE, TRUE
476 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
480 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
484 $value = "{mailing.$token}";
489 $value = self
::tokenEscapeSmarty($value);
495 * Replace all action tokens in $str
497 * @param string $str The string with tokens to be replaced
498 * @param array $addresses Assoc. array of VERP event addresses
499 * @param array $urls Assoc. array of action URLs
500 * @param boolean $html Replace tokens with HTML or plain text
501 * @param array $knownTokens A list of tokens that are known to exist in the email body
503 * @return string The processed string
507 public static function &replaceActionTokens(
513 $escapeSmarty = FALSE
516 // here we intersect with the list of pre-configured valid tokens
517 // so that we remove anything we do not recognize
518 // I hope to move this step out of here soon and
519 // then we will just iterate on a list of tokens that are passed to us
520 if (!$knownTokens ||
empty($knownTokens[$key])) {
524 $str = preg_replace_callback(
525 self
::tokenRegex($key),
526 function ($matches) use(&$addresses, &$urls, $html, $escapeSmarty) {
527 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
534 public static function getActionTokenReplacement(
539 $escapeSmarty = FALSE
541 /* If the token is an email action, use it. Otherwise, find the
544 if (!in_array($token, self
::$_tokens['action'])) {
545 $value = "{action.$token}";
548 $value = CRM_Utils_Array
::value($token, $addresses);
550 if ($value == NULL) {
551 $value = CRM_Utils_Array
::value($token, $urls);
554 if ($value && $html) {
556 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
557 $value = "mailto:$value";
560 elseif ($value && !$html) {
561 $value = str_replace('&', '&', $value);
566 $value = self
::tokenEscapeSmarty($value);
572 * Replace all the contact-level tokens in $str with information from
575 * @param string $str The string with tokens to be replaced
576 * @param array $contact Associative array of contact properties
577 * @param boolean $html Replace tokens with HTML or plain text
578 * @param array $knownTokens A list of tokens that are known to exist in the email body
579 * @param boolean $returnBlankToken return unevaluated token if value is null
581 * @return string The processed string
585 public static function &replaceContactTokens(
590 $returnBlankToken = FALSE,
591 $escapeSmarty = FALSE
594 if (self
::$_tokens[$key] == NULL) {
595 /* This should come from UF */
597 self
::$_tokens[$key] =
599 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
600 array('checksum', 'contact_id')
604 // here we intersect with the list of pre-configured valid tokens
605 // so that we remove anything we do not recognize
606 // I hope to move this step out of here soon and
607 // then we will just iterate on a list of tokens that are passed to us
608 if (!$knownTokens ||
empty($knownTokens[$key])) {
612 $str = preg_replace_callback(
613 self
::tokenRegex($key),
614 function ($matches) use(&$contact, $html, $returnBlankToken, $escapeSmarty) {
615 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
620 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
624 public static function getContactTokenReplacement(
628 $returnBlankToken = FALSE,
629 $escapeSmarty = FALSE
631 if (self
::$_tokens['contact'] == NULL) {
632 /* This should come from UF */
634 self
::$_tokens['contact'] =
636 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
637 array('checksum', 'contact_id')
641 /* Construct value from $token and $contact */
646 // Support legacy tokens
647 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
649 // check if the token we were passed is valid
650 // we have to do this because this function is
651 // called only when we find a token in the string
653 if (!in_array($token, self
::$_tokens['contact'])) {
656 elseif ($token == 'checksum') {
657 $hash = CRM_Utils_Array
::value('hash', $contact);
658 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
659 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
667 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
669 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
670 if (is_array($value)) {
673 // Convert pseudoconstants using metadata
674 elseif ($value && is_numeric($value)) {
675 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
676 if (!empty($allFields[$token]['pseudoconstant'])) {
677 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
683 $value = str_replace('&', '&', $value);
686 // if null then return actual token
687 if ($returnBlankToken && !$value) {
692 $value = "{contact.$token}";
696 && !($returnBlankToken && $noReplace)) { // $returnBlankToken means the caller wants to do further attempts at processing unreplaced tokens -- so don't escape them yet in this case.
697 $value = self
::tokenEscapeSmarty($value);
704 * Replace all the hook tokens in $str with information from
707 * @param string $str The string with tokens to be replaced
708 * @param array $contact Associative array of contact properties (including hook token values)
709 * @param boolean $html Replace tokens with HTML or plain text
711 * @return string The processed string
715 public static function &replaceHookTokens(
720 $escapeSmarty = FALSE
722 foreach ($categories as $key) {
723 $str = preg_replace_callback(
724 self
::tokenRegex($key),
725 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
726 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
735 * Parse html through Smarty resolving any smarty functions
736 * @param string $tokenHtml
737 * @param array $entity
738 * @param string $entityType
739 * @return string html parsed through smarty
741 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
742 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
743 $smarty = CRM_Core_Smarty
::singleton();
744 // also add the tokens to the template
745 $smarty->assign_by_ref($entityType, $entity);
746 $tokenHtml = $smarty->fetch("string:$tokenHtml");
750 public static function getHookTokenReplacement(
755 $escapeSmarty = FALSE
757 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
759 if ($value && !$html) {
760 $value = str_replace('&', '&', $value);
764 $value = self
::tokenEscapeSmarty($value);
771 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
772 * for example {{token}} or \{token} will result in {token} in the final email
774 * this routine will remove the extra backslashes and braces
776 * @param $str ref to the string that will be scanned and modified
777 * @return void this function works directly on the string that is passed
781 public static function unescapeTokens(&$str) {
782 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
786 * Replace unsubscribe tokens
788 * @param string $str the string with tokens to be replaced
789 * @param object $domain The domain BAO
790 * @param array $groups The groups (if any) being unsubscribed
791 * @param boolean $html Replace tokens with html or plain text
792 * @param int $contact_id The contact ID
793 * @param string hash The security hash of the unsub event
795 * @return string The processed string
799 public static function &replaceUnsubscribeTokens(
807 if (self
::token_match('unsubscribe', 'group', $str)) {
808 if (!empty($groups)) {
809 $config = CRM_Core_Config
::singleton();
810 $base = CRM_Utils_System
::baseURL();
812 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
813 $dao = new CRM_Contact_DAO_Group();
815 while ($dao->fetch()) {
816 if (substr($dao->visibility
, 0, 6) == 'Public') {
817 $visibleGroups[] = $dao->id
;
820 $value = implode(', ', $groups);
821 self
::token_replace('unsubscribe', 'group', $value, $str);
828 * Replace resubscribe tokens
830 * @param string $str the string with tokens to be replaced
831 * @param object $domain The domain BAO
832 * @param array $groups The groups (if any) being resubscribed
833 * @param boolean $html Replace tokens with html or plain text
834 * @param int $contact_id The contact ID
835 * @param string hash The security hash of the resub event
837 * @return string The processed string
841 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
844 if (self
::token_match('resubscribe', 'group', $str)) {
845 if (!empty($groups)) {
846 $value = implode(', ', $groups);
847 self
::token_replace('resubscribe', 'group', $value, $str);
854 * Replace subscription-confirmation-request tokens
856 * @param string $str The string with tokens to be replaced
857 * @param string $group The name of the group being subscribed
858 * @param boolean $html Replace tokens with html or plain text
860 * @return string The processed string
864 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
865 if (self
::token_match('subscribe', 'group', $str)) {
866 self
::token_replace('subscribe', 'group', $group, $str);
868 if (self
::token_match('subscribe', 'url', $str)) {
869 self
::token_replace('subscribe', 'url', $url, $str);
875 * Replace subscription-invitation tokens
877 * @param string $str The string with tokens to be replaced
879 * @return string The processed string
883 public static function &replaceSubscribeInviteTokens($str) {
884 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
885 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
887 TRUE, NULL, TRUE, TRUE
889 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
892 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
893 foreach ($matches as $key => $value) {
894 $gid = substr($value, 21, -1);
895 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
896 "reset=1&gid={$gid}",
897 TRUE, NULL, TRUE, TRUE
899 $url = str_replace('&', '&', $url);
900 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
904 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
905 foreach ($matches as $key => $value) {
906 $gid = substr($value, 18, -1);
907 $config = CRM_Core_Config
::singleton();
908 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
909 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
910 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
911 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
918 * Replace welcome/confirmation tokens
920 * @param string $str The string with tokens to be replaced
921 * @param string $group The name of the group being subscribed
922 * @param boolean $html Replace tokens with html or plain text
924 * @return string The processed string
928 public static function &replaceWelcomeTokens($str, $group, $html) {
929 if (self
::token_match('welcome', 'group', $str)) {
930 self
::token_replace('welcome', 'group', $group, $str);
936 * Find unprocessed tokens (call this last)
938 * @param string $str The string to search
940 * @return array Array of tokens that weren't replaced
944 public static function &unmatchedTokens(&$str) {
945 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
946 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
951 * Find and replace tokens for each component
953 * @param string $str The string to search
954 * @param array $contact Associative array of contact properties
955 * @param array $components A list of tokens that are known to exist in the email body
957 * @return string The processed string
961 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
962 if (!is_array($components) ||
empty($contact)) {
966 foreach ($components as $name => $tokens) {
967 if (!is_array($tokens) ||
empty($tokens)) {
971 foreach ($tokens as $token) {
972 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
973 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
975 elseif (!$returnEmptyToken) {
976 //replacing empty token
977 self
::token_replace($name, $token, "", $str, $escapeSmarty);
985 * Get array of string tokens
987 * @param $string the input string to parse for tokens
989 * @return $tokens array of tokens mentioned in field
993 static function getTokens($string) {
996 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1003 foreach ($matches[1] as $token) {
1004 list($type, $name) = preg_split('/\./', $token, 2);
1005 if ($name && $type) {
1006 if (!isset($tokens[$type])) {
1007 $tokens[$type] = array();
1009 $tokens[$type][] = $name;
1017 * gives required details of contacts in an indexed array format so we
1018 * can iterate in a nice loop and do token evaluation
1020 * @param array $contactIds of contacts
1021 * @param array $returnProperties of required properties
1022 * @param boolean $skipOnHold don't return on_hold contact info also.
1023 * @param boolean $skipDeceased don't return deceased contact info.
1024 * @param array $extraParams extra params
1025 * @param array $tokens the list of tokens we've extracted from the content
1026 * @param int $jobID the mailing list jobID - this is a legacy param
1032 static function getTokenDetails($contactIDs,
1033 $returnProperties = NULL,
1035 $skipDeceased = TRUE,
1036 $extraParams = NULL,
1041 if (empty($contactIDs)) {
1042 // putting a fatal here so we can track if/when this happens
1043 CRM_Core_Error
::fatal();
1047 foreach ($contactIDs as $key => $contactID) {
1049 CRM_Core_Form
::CB_PREFIX
. $contactID,
1055 if ($skipDeceased) {
1056 $params[] = array('is_deceased', '=', 0, 0, 0);
1061 $params[] = array('on_hold', '=', 0, 0, 0);
1065 $params = array_merge($params, $extraParams);
1068 // if return properties are not passed then get all return properties
1069 if (empty($returnProperties)) {
1070 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1071 array('display_name', 'checksum', 'contact_id')
1073 foreach ($fields as $key => $val) {
1074 $returnProperties[$val] = 1;
1079 foreach ($returnProperties as $name => $dontCare) {
1080 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1086 //get the total number of contacts to fetch from database.
1087 $numberofContacts = count($contactIDs);
1088 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1090 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1092 $contactDetails = &$details[0];
1094 foreach ($contactIDs as $key => $contactID) {
1095 if (array_key_exists($contactID, $contactDetails)) {
1096 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1097 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1099 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1101 // communication Prefferance
1102 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1103 $contactDetails[$contactID]['preferred_communication_method']
1106 foreach ($contactPcm as $key => $val) {
1108 $result[$val] = $pcm[$val];
1111 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1114 foreach ($custom as $cfID) {
1115 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1116 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1122 //special case for greeting replacement
1124 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1125 if (!empty($contactDetails[$contactID][$val])) {
1126 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1132 // also call a hook and get token details
1133 CRM_Utils_Hook
::tokenValues($details[0],
1143 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1144 * specific tokens to be rendered
1146 * @param array $contactIDs - this should always be array(0) or its not anonymous - left to keep signature same
1148 * @param string $returnProperties
1149 * @param boolean $skipOnHold
1150 * @param boolean $skipDeceased
1151 * @param string $extraParams
1152 * @param array $tokens
1153 * @param string $className sent as context to the hook
1154 * @param string $jobID
1155 * @return array contactDetails with hooks swapped out
1157 function getAnonymousTokenDetails($contactIDs = array(0),
1158 $returnProperties = NULL,
1160 $skipDeceased = TRUE,
1161 $extraParams = NULL,
1165 $details = array(0 => array());
1166 // also call a hook and get token details
1167 CRM_Utils_Hook
::tokenValues($details[0],
1176 * gives required details of contribuion in an indexed array format so we
1177 * can iterate in a nice loop and do token evaluation
1179 * @param array $contributionId one contribution id
1180 * @param array $returnProperties of required properties
1181 * @param boolean $skipOnHold don't return on_hold contact info.
1182 * @param boolean $skipDeceased don't return deceased contact info.
1183 * @param array $extraParams extra params
1184 * @param array $tokens the list of tokens we've extracted from the content
1190 static function getContributionTokenDetails($contributionIDs,
1191 $returnProperties = NULL,
1192 $extraParams = NULL,
1196 if (empty($contributionIDs)) {
1197 // putting a fatal here so we can track if/when this happens
1198 CRM_Core_Error
::fatal();
1203 // no apiQuery helper yet, so do a loop and find contribution by id
1204 foreach ($contributionIDs as $contributionID) {
1206 $dao = new CRM_Contribute_DAO_Contribution();
1207 $dao->id
= $contributionID;
1209 if ($dao->find(TRUE)) {
1211 $details[$dao->id
] = array();
1212 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1214 // do the necessary transformation
1215 if (!empty($details[$dao->id
]['payment_instrument_id'])) {
1216 $piId = $details[$dao->id
]['payment_instrument_id'];
1217 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1218 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1220 if (!empty($details[$dao->id
]['campaign_id'])) {
1221 $campaignId = $details[$dao->id
]['campaign_id'];
1222 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1223 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1226 if (!empty($details[$dao->id
]['financial_type_id'])) {
1227 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1228 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1229 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1232 // TODO: call a hook to get token contribution details
1240 * Get Membership Token Details
1241 * @param array $membershipIDs array of membership IDS
1243 static function getMembershipTokenDetails($membershipIDs) {
1244 $memberships = civicrm_api3('membership', 'get', array('options' => array('limit' => 200000), 'membership_id' => array('IN' => (array) $membershipIDs)));
1245 return $memberships['values'];
1248 * replace greeting tokens exists in message/subject
1252 static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1254 if (!$contactDetails && !$contactId) {
1258 // check if there are any tokens
1259 $greetingTokens = self
::getTokens($tokenString);
1261 if (!empty($greetingTokens)) {
1262 // first use the existing contact object for token replacement
1263 if (!empty($contactDetails)) {
1264 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1267 // check if there are any unevaluated tokens
1268 $greetingTokens = self
::getTokens($tokenString);
1270 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1271 // so retrieve it from database
1272 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1273 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1274 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1275 $contactParams = array('contact_id' => $contactId);
1277 $greetingDetails = self
::getTokenDetails($contactParams,
1278 $greetingsReturnProperties,
1284 // again replace tokens
1285 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1296 static function flattenTokens(&$tokens) {
1297 $flattenTokens = array();
1300 'html', 'text', 'subject') as $prop) {
1301 if (!isset($tokens[$prop])) {
1304 foreach ($tokens[$prop] as $type => $names) {
1305 if (!isset($flattenTokens[$type])) {
1306 $flattenTokens[$type] = array();
1308 foreach ($names as $name) {
1309 $flattenTokens[$type][$name] = 1;
1314 return $flattenTokens;
1318 * Replace all user tokens in $str
1320 * @param string $str The string with tokens to be replaced
1322 * @return string The processed string
1326 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1328 if (!$knownTokens ||
1329 !isset($knownTokens[$key])
1334 $str = preg_replace_callback(
1335 self
::tokenRegex($key),
1336 function ($matches) use($escapeSmarty) {
1337 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1344 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1347 list($objectName, $objectValue) = explode('-', $token, 2);
1349 switch ($objectName) {
1351 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1355 $value = CRM_Core_Permission
::roleEmails($objectValue);
1359 if ($escapeSmarty) {
1360 $value = self
::tokenEscapeSmarty($value);
1367 protected static function _buildContributionTokens() {
1368 $key = 'contribution';
1369 if (self
::$_tokens[$key] == NULL) {
1370 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1371 array('campaign', 'financial_type')
1377 * store membership tokens on the static _tokens array
1379 protected static function _buildMembershipTokens() {
1380 $key = 'membership';
1381 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1382 $membershipTokens = array();
1383 $tokens = CRM_Core_SelectValues
::membershipTokens();
1384 foreach ($tokens as $token => $dontCare) {
1385 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1387 self
::$_tokens[$key] = $membershipTokens;
1392 * Replace tokens for an entity
1393 * @param string $entity
1394 * @param array $entityArray (e.g. in format from api)
1395 * @param string $str string to replace in
1396 * @param array $knownTokens array of tokens present
1397 * @param boolean $escapeSmarty
1398 * @return string string with replacements made
1400 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1401 if (!$knownTokens ||
empty($knownTokens[$entity])) {
1405 $fn = 'get' . ucFirst($entity) . 'tokenReplacement';
1406 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1407 foreach ($knownTokens[$entity] as $token) {
1408 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1409 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1411 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1415 public static function &replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1416 self
::_buildContributionTokens();
1418 // here we intersect with the list of pre-configured valid tokens
1419 // so that we remove anything we do not recognize
1420 // I hope to move this step out of here soon and
1421 // then we will just iterate on a list of tokens that are passed to us
1422 $key = 'contribution';
1423 if (!$knownTokens ||
empty($knownTokens[$key])) {
1427 $str = preg_replace_callback(
1428 self
::tokenRegex($key),
1429 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1430 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1435 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1440 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1441 * - this is used by the pdfLetter task from membership search
1442 * @param string $token
1443 * @param array $membership an api result array for a single membership
1444 * @param boolean $escapeSmarty
1445 * @return string token replacement
1447 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1448 $entity = 'membership';
1449 self
::_buildMembershipTokens();
1452 $value = $membership['membership_name'];
1455 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1456 $value = $statuses[$membership['status_id']];
1460 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1462 catch (CiviCRM_API3_Exception
$e) {
1463 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1464 // api handles NULL (4.4)
1469 if (in_array($token, self
::$_tokens[$entity])) {
1470 $value = $membership[$token];
1474 $value = "{$entity}.{$token}";
1479 if ($escapeSmarty) {
1480 $value = self
::tokenEscapeSmarty($value);
1485 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1486 self
::_buildContributionTokens();
1489 case 'total_amount':
1492 case 'non_deductible_amount':
1493 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1496 case 'receive_date':
1497 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1498 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1502 if (!in_array($token, self
::$_tokens['contribution'])) {
1503 $value = "{contribution.$token}";
1506 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1512 if ($escapeSmarty) {
1513 $value = self
::tokenEscapeSmarty($value);
1518 function getPermissionEmails($permissionName) {}
1520 function getRoleEmails($roleName) {}
1523 * @return array: legacy_token => new_token
1525 static function legacyContactTokens() {
1527 'individual_prefix' => 'prefix_id',
1528 'individual_suffix' => 'suffix_id',
1529 'gender' => 'gender_id',
1530 'communication_style' => 'communication_style_id',