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
234 !CRM_Utils_Array
::value($key, $knownTokens)
239 $str = preg_replace_callback(
240 self
::tokenRegex($key),
241 function ($matches) use(&$domain, $html, $escapeSmarty) {
242 return CRM_Utils_Token
::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
249 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
250 // check if the token we were passed is valid
251 // we have to do this because this function is
252 // called only when we find a token in the string
254 $loc = &$domain->getLocationValues();
256 if (!in_array($token, self
::$_tokens['domain'])) {
257 $value = "{domain.$token}";
259 elseif ($token == 'address') {
260 static $addressCache = array();
262 $cache_key = $html ?
'address-html' : 'address-text';
263 if (array_key_exists($cache_key, $addressCache)) {
264 return $addressCache[$cache_key];
268 /* Construct the address token */
270 if (CRM_Utils_Array
::value($token, $loc)) {
272 $value = $loc[$token][1]['display'];
273 $value = str_replace("\n", '<br />', $value);
276 $value = $loc[$token][1]['display_text'];
278 $addressCache[$cache_key] = $value;
281 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
282 $value = $domain->$token;
284 elseif ($token == 'phone' ||
$token == 'email') {
285 /* Construct the phone and email tokens */
288 if (CRM_Utils_Array
::value($token, $loc)) {
289 foreach ($loc[$token] as $index => $entity) {
290 $value = $entity[$token];
297 $value = self
::tokenEscapeSmarty($value);
304 * Replace all the org-level tokens in $str
306 * @param string $str The string with tokens to be replaced
307 * @param object $org Associative array of org properties
308 * @param boolean $html Replace tokens with HTML or plain text
310 * @return string The processed string
314 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
315 self
::$_tokens['org'] =
317 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
318 array('address', 'display_name', 'checksum', 'contact_id')
322 foreach (self
::$_tokens['org'] as $token) {
323 // print "Getting token value for $token<br/><br/>";
328 /* If the string doesn't contain this token, skip it. */
330 if (!self
::token_match('org', $token, $str)) {
334 /* Construct value from $token and $contact */
338 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
339 // only generate cv if we need it
341 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
343 foreach ($cv as $cvFieldID => $value) {
344 if ($cvFieldID == $cfID) {
345 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
350 elseif ($token == 'checksum') {
351 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
354 elseif ($token == 'address') {
355 /* Build the location values array */
358 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
359 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
360 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
361 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
362 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
364 /* Construct the address token */
366 $value = CRM_Utils_Address
::format($loc);
368 $value = str_replace("\n", '<br />', $value);
372 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
375 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
382 * Replace all mailing tokens in $str
384 * @param string $str The string with tokens to be replaced
385 * @param object $mailing The mailing BAO, or null for validation
386 * @param boolean $html Replace tokens with HTML or plain text
388 * @return string The processed sstring
392 public static function &replaceMailingTokens(
397 $escapeSmarty = FALSE
400 if (!$knownTokens ||
!isset($knownTokens[$key])) {
404 $str = preg_replace_callback(
405 self
::tokenRegex($key),
406 function ($matches) use(&$mailing, $escapeSmarty) {
407 return CRM_Utils_Token
::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
414 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
420 $value = $mailing ?
$mailing->id
: 'undefined';
424 $value = $mailing ?
$mailing->name
: 'Mailing Name';
428 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
429 $value = implode(', ', $groups);
433 $value = $mailing->subject
;
437 $value = CRM_Utils_System
::url('civicrm/mailing/view',
438 "reset=1&id={$mailing->id}",
439 TRUE, NULL, FALSE, TRUE
444 $value = CRM_Utils_System
::url('civicrm/mailing/send',
445 "reset=1&mid={$mailing->id}&continue=true",
446 TRUE, NULL, FALSE, TRUE
451 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
452 "reset=1&mid={$mailing->id}",
453 TRUE, NULL, FALSE, TRUE
458 $page = new CRM_Mailing_Page_View();
459 $value = $page->run($mailing->id
, NULL, FALSE);
462 case 'approvalStatus':
463 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id
);
467 $value = $mailing->approval_note
;
471 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
472 "reset=1&mid={$mailing->id}",
473 TRUE, NULL, FALSE, TRUE
478 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
482 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
486 $value = "{mailing.$token}";
491 $value = self
::tokenEscapeSmarty($value);
497 * Replace all action tokens in $str
499 * @param string $str The string with tokens to be replaced
500 * @param array $addresses Assoc. array of VERP event addresses
501 * @param array $urls Assoc. array of action URLs
502 * @param boolean $html Replace tokens with HTML or plain text
503 * @param array $knownTokens A list of tokens that are known to exist in the email body
505 * @return string The processed string
509 public static function &replaceActionTokens(
515 $escapeSmarty = FALSE
518 // here we intersect with the list of pre-configured valid tokens
519 // so that we remove anything we do not recognize
520 // I hope to move this step out of here soon and
521 // then we will just iterate on a list of tokens that are passed to us
522 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
526 $str = preg_replace_callback(
527 self
::tokenRegex($key),
528 function ($matches) use(&$addresses, &$urls, $html, $escapeSmarty) {
529 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
536 public static function getActionTokenReplacement(
541 $escapeSmarty = FALSE
543 /* If the token is an email action, use it. Otherwise, find the
546 if (!in_array($token, self
::$_tokens['action'])) {
547 $value = "{action.$token}";
550 $value = CRM_Utils_Array
::value($token, $addresses);
552 if ($value == NULL) {
553 $value = CRM_Utils_Array
::value($token, $urls);
556 if ($value && $html) {
558 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
559 $value = "mailto:$value";
562 elseif ($value && !$html) {
563 $value = str_replace('&', '&', $value);
568 $value = self
::tokenEscapeSmarty($value);
574 * Replace all the contact-level tokens in $str with information from
577 * @param string $str The string with tokens to be replaced
578 * @param array $contact Associative array of contact properties
579 * @param boolean $html Replace tokens with HTML or plain text
580 * @param array $knownTokens A list of tokens that are known to exist in the email body
581 * @param boolean $returnBlankToken return unevaluated token if value is null
583 * @return string The processed string
587 public static function &replaceContactTokens(
592 $returnBlankToken = FALSE,
593 $escapeSmarty = FALSE
596 if (self
::$_tokens[$key] == NULL) {
597 /* This should come from UF */
599 self
::$_tokens[$key] =
601 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
602 array('checksum', 'contact_id')
606 // here we intersect with the list of pre-configured valid tokens
607 // so that we remove anything we do not recognize
608 // I hope to move this step out of here soon and
609 // then we will just iterate on a list of tokens that are passed to us
610 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
614 $str = preg_replace_callback(
615 self
::tokenRegex($key),
616 function ($matches) use(&$contact, $html, $returnBlankToken, $escapeSmarty) {
617 return CRM_Utils_Token
::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
622 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
626 public static function getContactTokenReplacement(
630 $returnBlankToken = FALSE,
631 $escapeSmarty = FALSE
633 if (self
::$_tokens['contact'] == NULL) {
634 /* This should come from UF */
636 self
::$_tokens['contact'] =
638 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
639 array('checksum', 'contact_id')
643 /* Construct value from $token and $contact */
647 // check if the token we were passed is valid
648 // we have to do this because this function is
649 // called only when we find a token in the string
651 if (!in_array($token, self
::$_tokens['contact'])) {
652 $value = "{contact.$token}";
654 elseif ($token == 'checksum') {
655 $hash = CRM_Utils_Array
::value('hash', $contact);
656 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
657 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
665 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
669 $value = str_replace('&', '&', $value);
672 // if null then return actual token
673 if ($returnBlankToken && !$value) {
674 $value = "{contact.$token}";
678 $value = self
::tokenEscapeSmarty($value);
685 * Replace all the hook tokens in $str with information from
688 * @param string $str The string with tokens to be replaced
689 * @param array $contact Associative array of contact properties (including hook token values)
690 * @param boolean $html Replace tokens with HTML or plain text
692 * @return string The processed string
696 public static function &replaceHookTokens(
701 $escapeSmarty = FALSE
703 foreach ($categories as $key) {
704 $str = preg_replace_callback(
705 self
::tokenRegex($key),
706 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
707 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
715 public static function getHookTokenReplacement(
720 $escapeSmarty = FALSE
722 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
724 if ($value && !$html) {
725 $value = str_replace('&', '&', $value);
729 $value = self
::tokenEscapeSmarty($value);
736 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
737 * for example {{token}} or \{token} will result in {token} in the final email
739 * this routine will remove the extra backslashes and braces
741 * @param $str ref to the string that will be scanned and modified
742 * @return void this function works directly on the string that is passed
746 public static function unescapeTokens(&$str) {
747 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
751 * Replace unsubscribe tokens
753 * @param string $str the string with tokens to be replaced
754 * @param object $domain The domain BAO
755 * @param array $groups The groups (if any) being unsubscribed
756 * @param boolean $html Replace tokens with html or plain text
757 * @param int $contact_id The contact ID
758 * @param string hash The security hash of the unsub event
760 * @return string The processed string
764 public static function &replaceUnsubscribeTokens(
772 if (self
::token_match('unsubscribe', 'group', $str)) {
773 if (!empty($groups)) {
774 $config = CRM_Core_Config
::singleton();
775 $base = CRM_Utils_System
::baseURL();
777 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
778 $dao = new CRM_Contact_DAO_Group();
780 while ($dao->fetch()) {
781 if (substr($dao->visibility
, 0, 6) == 'Public') {
782 $visibleGroups[] = $dao->id
;
785 $value = implode(', ', $groups);
786 self
::token_replace('unsubscribe', 'group', $value, $str);
793 * Replace resubscribe tokens
795 * @param string $str the string with tokens to be replaced
796 * @param object $domain The domain BAO
797 * @param array $groups The groups (if any) being resubscribed
798 * @param boolean $html Replace tokens with html or plain text
799 * @param int $contact_id The contact ID
800 * @param string hash The security hash of the resub event
802 * @return string The processed string
806 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
809 if (self
::token_match('resubscribe', 'group', $str)) {
810 if (!empty($groups)) {
811 $value = implode(', ', $groups);
812 self
::token_replace('resubscribe', 'group', $value, $str);
819 * Replace subscription-confirmation-request tokens
821 * @param string $str The string with tokens to be replaced
822 * @param string $group The name of the group being subscribed
823 * @param boolean $html Replace tokens with html or plain text
825 * @return string The processed string
829 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
830 if (self
::token_match('subscribe', 'group', $str)) {
831 self
::token_replace('subscribe', 'group', $group, $str);
833 if (self
::token_match('subscribe', 'url', $str)) {
834 self
::token_replace('subscribe', 'url', $url, $str);
840 * Replace subscription-invitation tokens
842 * @param string $str The string with tokens to be replaced
844 * @return string The processed string
848 public static function &replaceSubscribeInviteTokens($str) {
849 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
850 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
852 TRUE, NULL, TRUE, TRUE
854 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
857 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
858 foreach ($matches as $key => $value) {
859 $gid = substr($value, 21, -1);
860 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
861 "reset=1&gid={$gid}",
862 TRUE, NULL, TRUE, TRUE
864 $url = str_replace('&', '&', $url);
865 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
869 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
870 foreach ($matches as $key => $value) {
871 $gid = substr($value, 18, -1);
872 $config = CRM_Core_Config
::singleton();
873 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
874 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
875 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
876 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
883 * Replace welcome/confirmation tokens
885 * @param string $str The string with tokens to be replaced
886 * @param string $group The name of the group being subscribed
887 * @param boolean $html Replace tokens with html or plain text
889 * @return string The processed string
893 public static function &replaceWelcomeTokens($str, $group, $html) {
894 if (self
::token_match('welcome', 'group', $str)) {
895 self
::token_replace('welcome', 'group', $group, $str);
901 * Find unprocessed tokens (call this last)
903 * @param string $str The string to search
905 * @return array Array of tokens that weren't replaced
909 public static function &unmatchedTokens(&$str) {
910 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
911 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
916 * Find and replace tokens for each component
918 * @param string $str The string to search
919 * @param array $contact Associative array of contact properties
920 * @param array $components A list of tokens that are known to exist in the email body
922 * @return string The processed string
926 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
927 if (!is_array($components) ||
empty($contact)) {
931 foreach ($components as $name => $tokens) {
932 if (!is_array($tokens) ||
empty($tokens)) {
936 foreach ($tokens as $token) {
937 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
938 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
940 elseif (!$returnEmptyToken) {
941 //replacing empty token
942 self
::token_replace($name, $token, "", $str, $escapeSmarty);
950 * Get array of string tokens
952 * @param $string the input string to parse for tokens
954 * @return $tokens array of tokens mentioned in field
958 static function getTokens($string) {
961 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
968 foreach ($matches[1] as $token) {
969 list($type, $name) = preg_split('/\./', $token, 2);
970 if ($name && $type) {
971 if (!isset($tokens[$type])) {
972 $tokens[$type] = array();
974 $tokens[$type][] = $name;
982 * gives required details of contacts in an indexed array format so we
983 * can iterate in a nice loop and do token evaluation
985 * @param array $contactIds of contacts
986 * @param array $returnProperties of required properties
987 * @param boolean $skipOnHold don't return on_hold contact info also.
988 * @param boolean $skipDeceased don't return deceased contact info.
989 * @param array $extraParams extra params
990 * @param array $tokens the list of tokens we've extracted from the content
991 * @param int $jobID the mailing list jobID - this is a legacy param
997 static function getTokenDetails($contactIDs,
998 $returnProperties = NULL,
1000 $skipDeceased = TRUE,
1001 $extraParams = NULL,
1006 if (empty($contactIDs)) {
1007 // putting a fatal here so we can track if/when this happens
1008 CRM_Core_Error
::fatal();
1012 foreach ($contactIDs as $key => $contactID) {
1014 CRM_Core_Form
::CB_PREFIX
. $contactID,
1020 if ($skipDeceased) {
1021 $params[] = array('is_deceased', '=', 0, 0, 0);
1026 $params[] = array('on_hold', '=', 0, 0, 0);
1030 $params = array_merge($params, $extraParams);
1033 // if return properties are not passed then get all return properties
1034 if (empty($returnProperties)) {
1035 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1036 array('display_name', 'checksum', 'contact_id')
1038 foreach ($fields as $key => $val) {
1039 $returnProperties[$val] = 1;
1044 foreach ($returnProperties as $name => $dontCare) {
1045 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1051 //get the total number of contacts to fetch from database.
1052 $numberofContacts = count($contactIDs);
1053 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1055 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1057 $contactDetails = &$details[0];
1059 foreach ($contactIDs as $key => $contactID) {
1060 if (array_key_exists($contactID, $contactDetails)) {
1061 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1062 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1064 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1066 // communication Prefferance
1067 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1068 $contactDetails[$contactID]['preferred_communication_method']
1071 foreach ($contactPcm as $key => $val) {
1073 $result[$val] = $pcm[$val];
1076 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1079 foreach ($custom as $cfID) {
1080 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1081 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1087 //special case for greeting replacement
1089 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1090 if (CRM_Utils_Array
::value($val, $contactDetails[$contactID])) {
1091 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1097 // also call a hook and get token details
1098 CRM_Utils_Hook
::tokenValues($details[0],
1108 * gives required details of contribuion in an indexed array format so we
1109 * can iterate in a nice loop and do token evaluation
1111 * @param array $contributionId one contribution id
1112 * @param array $returnProperties of required properties
1113 * @param boolean $skipOnHold don't return on_hold contact info.
1114 * @param boolean $skipDeceased don't return deceased contact info.
1115 * @param array $extraParams extra params
1116 * @param array $tokens the list of tokens we've extracted from the content
1122 static function getContributionTokenDetails($contributionIDs,
1123 $returnProperties = NULL,
1124 $extraParams = NULL,
1128 if (empty($contributionIDs)) {
1129 // putting a fatal here so we can track if/when this happens
1130 CRM_Core_Error
::fatal();
1135 // no apiQuery helper yet, so do a loop and find contribution by id
1136 foreach ($contributionIDs as $contributionID) {
1138 $dao = new CRM_Contribute_DAO_Contribution();
1139 $dao->id
= $contributionID;
1141 if ($dao->find(TRUE)) {
1143 $details[$dao->id
] = array();
1144 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1146 // do the necessary transformation
1147 if (CRM_Utils_Array
::value('payment_instrument_id', $details[$dao->id
])) {
1148 $piId = $details[$dao->id
]['payment_instrument_id'];
1149 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1150 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1152 if (CRM_Utils_Array
::value('campaign_id', $details[$dao->id
])) {
1153 $campaignId = $details[$dao->id
]['campaign_id'];
1154 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1155 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1158 if (CRM_Utils_Array
::value('financial_type_id', $details[$dao->id
])) {
1159 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1160 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1161 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1164 // TODO: call a hook to get token contribution details
1172 * replace greeting tokens exists in message/subject
1176 static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL) {
1178 if (!$contactDetails && !$contactId) {
1182 // check if there are any tokens
1183 $greetingTokens = self
::getTokens($tokenString);
1185 if (!empty($greetingTokens)) {
1186 // first use the existing contact object for token replacement
1187 if (!empty($contactDetails)) {
1188 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE);
1191 // check if there are any unevaluated tokens
1192 $greetingTokens = self
::getTokens($tokenString);
1194 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1195 // so retrieve it from database
1196 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1197 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1198 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1199 $contactParams = array('contact_id' => $contactId);
1201 $greetingDetails = self
::getTokenDetails($contactParams,
1202 $greetingsReturnProperties,
1208 // again replace tokens
1209 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1218 static function flattenTokens(&$tokens) {
1219 $flattenTokens = array();
1222 'html', 'text', 'subject') as $prop) {
1223 if (!isset($tokens[$prop])) {
1226 foreach ($tokens[$prop] as $type => $names) {
1227 if (!isset($flattenTokens[$type])) {
1228 $flattenTokens[$type] = array();
1230 foreach ($names as $name) {
1231 $flattenTokens[$type][$name] = 1;
1236 return $flattenTokens;
1240 * Replace all user tokens in $str
1242 * @param string $str The string with tokens to be replaced
1244 * @return string The processed string
1248 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1250 if (!$knownTokens ||
1251 !isset($knownTokens[$key])
1256 $str = preg_replace_callback(
1257 self
::tokenRegex($key),
1258 function ($matches) use($escapeSmarty) {
1259 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1266 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1269 list($objectName, $objectValue) = explode('-', $token, 2);
1271 switch ($objectName) {
1273 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1277 $value = CRM_Core_Permission
::roleEmails($objectValue);
1281 if ($escapeSmarty) {
1282 $value = self
::tokenEscapeSmarty($value);
1289 protected static function _buildContributionTokens() {
1290 $key = 'contribution';
1291 if (self
::$_tokens[$key] == NULL) {
1292 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1293 array('campaign', 'financial_type')
1298 public static function &replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1299 self
::_buildContributionTokens();
1301 // here we intersect with the list of pre-configured valid tokens
1302 // so that we remove anything we do not recognize
1303 // I hope to move this step out of here soon and
1304 // then we will just iterate on a list of tokens that are passed to us
1305 $key = 'contribution';
1306 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1310 $str = preg_replace_callback(
1311 self
::tokenRegex($key),
1312 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1313 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1318 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1322 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1323 self
::_buildContributionTokens();
1326 case 'total_amount':
1329 case 'non_deductible_amount':
1330 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1333 case 'receive_date':
1334 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1335 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1339 if (!in_array($token, self
::$_tokens['contribution'])) {
1340 $value = "{contribution.$token}";
1343 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1349 if ($escapeSmarty) {
1350 $value = self
::tokenEscapeSmarty($value);
1355 function getPermissionEmails($permissionName) {}
1357 function getRoleEmails($roleName) {}