3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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.subscribeUrl' =>
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.unsubscribe' => 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 $mailApprovalStatus = CRM_Mailing_PseudoConstant
::approvalStatus();
464 $value = $mailApprovalStatus[$mailing->approval_status_id
];
468 $value = $mailing->approval_note
;
472 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
473 "reset=1&mid={$mailing->id}",
474 TRUE, NULL, FALSE, TRUE
479 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
483 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
487 $value = "{mailing.$token}";
492 $value = self
::tokenEscapeSmarty($value);
498 * Replace all action tokens in $str
500 * @param string $str The string with tokens to be replaced
501 * @param array $addresses Assoc. array of VERP event addresses
502 * @param array $urls Assoc. array of action URLs
503 * @param boolean $html Replace tokens with HTML or plain text
504 * @param array $knownTokens A list of tokens that are known to exist in the email body
506 * @return string The processed string
510 public static function &replaceActionTokens(
516 $escapeSmarty = FALSE
519 // here we intersect with the list of pre-configured valid tokens
520 // so that we remove anything we do not recognize
521 // I hope to move this step out of here soon and
522 // then we will just iterate on a list of tokens that are passed to us
523 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
527 $str = preg_replace_callback(
528 self
::tokenRegex($key),
529 function ($matches) use(&$addresses, &$urls, $html, $escapeSmarty) {
530 return CRM_Utils_Token
::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
537 public static function getActionTokenReplacement(
542 $escapeSmarty = FALSE
544 /* If the token is an email action, use it. Otherwise, find the
547 if (!in_array($token, self
::$_tokens['action'])) {
548 $value = "{action.$token}";
551 $value = CRM_Utils_Array
::value($token, $addresses);
553 if ($value == NULL) {
554 $value = CRM_Utils_Array
::value($token, $urls);
557 if ($value && $html) {
559 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
560 $value = "mailto:$value";
563 elseif ($value && !$html) {
564 $value = str_replace('&', '&', $value);
569 $value = self
::tokenEscapeSmarty($value);
575 * Replace all the contact-level tokens in $str with information from
578 * @param string $str The string with tokens to be replaced
579 * @param array $contact Associative array of contact properties
580 * @param boolean $html Replace tokens with HTML or plain text
581 * @param array $knownTokens A list of tokens that are known to exist in the email body
582 * @param boolean $returnBlankToken return unevaluated token if value is null
584 * @return string The processed string
588 public static function &replaceContactTokens(
593 $returnBlankToken = FALSE,
594 $escapeSmarty = FALSE
597 if (self
::$_tokens[$key] == NULL) {
598 /* This should come from UF */
600 self
::$_tokens[$key] =
602 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
603 array('checksum', 'contact_id')
607 // here we intersect with the list of pre-configured valid tokens
608 // so that we remove anything we do not recognize
609 // I hope to move this step out of here soon and
610 // then we will just iterate on a list of tokens that are passed to us
611 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
615 $str = preg_replace_callback(
616 self
::tokenRegex($key),
617 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
618 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
623 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
627 public static function getContactTokenReplacement(
631 $returnBlankToken = FALSE,
632 $escapeSmarty = FALSE
634 if (self
::$_tokens['contact'] == NULL) {
635 /* This should come from UF */
637 self
::$_tokens['contact'] =
639 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
640 array('checksum', 'contact_id')
644 /* Construct value from $token and $contact */
648 // check if the token we were passed is valid
649 // we have to do this because this function is
650 // called only when we find a token in the string
652 if (!in_array($token, self
::$_tokens['contact'])) {
653 $value = "{contact.$token}";
655 elseif ($token == 'checksum') {
656 $hash = CRM_Utils_Array
::value('hash', $contact);
657 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
658 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
666 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
670 $value = str_replace('&', '&', $value);
673 // if null then return actual token
674 if ($returnBlankToken && !$value) {
675 $value = "{contact.$token}";
679 $value = self
::tokenEscapeSmarty($value);
686 * Replace all the hook tokens in $str with information from
689 * @param string $str The string with tokens to be replaced
690 * @param array $contact Associative array of contact properties (including hook token values)
691 * @param boolean $html Replace tokens with HTML or plain text
693 * @return string The processed string
697 public static function &replaceHookTokens(
702 $escapeSmarty = FALSE
704 foreach ($categories as $key) {
705 $str = preg_replace_callback(
706 self
::tokenRegex($key),
707 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
708 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
716 public static function getHookTokenReplacement(
721 $escapeSmarty = FALSE
723 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
725 if ($value && !$html) {
726 $value = str_replace('&', '&', $value);
730 $value = self
::tokenEscapeSmarty($value);
737 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
738 * for example {{token}} or \{token} will result in {token} in the final email
740 * this routine will remove the extra backslashes and braces
742 * @param $str ref to the string that will be scanned and modified
743 * @return void this function works directly on the string that is passed
747 public static function unescapeTokens(&$str) {
748 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
752 * Replace unsubscribe tokens
754 * @param string $str the string with tokens to be replaced
755 * @param object $domain The domain BAO
756 * @param array $groups The groups (if any) being unsubscribed
757 * @param boolean $html Replace tokens with html or plain text
758 * @param int $contact_id The contact ID
759 * @param string hash The security hash of the unsub event
761 * @return string The processed string
765 public static function &replaceUnsubscribeTokens(
773 if (self
::token_match('unsubscribe', 'group', $str)) {
774 if (!empty($groups)) {
775 $config = CRM_Core_Config
::singleton();
776 $base = CRM_Utils_System
::baseURL();
778 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
779 $dao = new CRM_Contact_DAO_Group();
781 while ($dao->fetch()) {
782 if (substr($dao->visibility
, 0, 6) == 'Public') {
783 $visibleGroups[] = $dao->id
;
786 $value = implode(', ', $groups);
787 self
::token_replace('unsubscribe', 'group', $value, $str);
794 * Replace resubscribe tokens
796 * @param string $str the string with tokens to be replaced
797 * @param object $domain The domain BAO
798 * @param array $groups The groups (if any) being resubscribed
799 * @param boolean $html Replace tokens with html or plain text
800 * @param int $contact_id The contact ID
801 * @param string hash The security hash of the resub event
803 * @return string The processed string
807 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
810 if (self
::token_match('resubscribe', 'group', $str)) {
811 if (!empty($groups)) {
812 $value = implode(', ', $groups);
813 self
::token_replace('resubscribe', 'group', $value, $str);
820 * Replace subscription-confirmation-request tokens
822 * @param string $str The string with tokens to be replaced
823 * @param string $group The name of the group being subscribed
824 * @param boolean $html Replace tokens with html or plain text
826 * @return string The processed string
830 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
831 if (self
::token_match('subscribe', 'group', $str)) {
832 self
::token_replace('subscribe', 'group', $group, $str);
834 if (self
::token_match('subscribe', 'url', $str)) {
835 self
::token_replace('subscribe', 'url', $url, $str);
841 * Replace subscription-invitation tokens
843 * @param string $str The string with tokens to be replaced
845 * @return string The processed string
849 public static function &replaceSubscribeInviteTokens($str) {
850 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
851 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
853 TRUE, NULL, TRUE, TRUE
855 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
858 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
859 foreach ($matches as $key => $value) {
860 $gid = substr($value, 21, -1);
861 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
862 "reset=1&gid={$gid}",
863 TRUE, NULL, TRUE, TRUE
865 $url = str_replace('&', '&', $url);
866 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
870 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
871 foreach ($matches as $key => $value) {
872 $gid = substr($value, 18, -1);
873 $config = CRM_Core_Config
::singleton();
874 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
875 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
876 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
877 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
884 * Replace welcome/confirmation tokens
886 * @param string $str The string with tokens to be replaced
887 * @param string $group The name of the group being subscribed
888 * @param boolean $html Replace tokens with html or plain text
890 * @return string The processed string
894 public static function &replaceWelcomeTokens($str, $group, $html) {
895 if (self
::token_match('welcome', 'group', $str)) {
896 self
::token_replace('welcome', 'group', $group, $str);
902 * Find unprocessed tokens (call this last)
904 * @param string $str The string to search
906 * @return array Array of tokens that weren't replaced
910 public static function &unmatchedTokens(&$str) {
911 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
912 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
917 * Find and replace tokens for each component
919 * @param string $str The string to search
920 * @param array $contact Associative array of contact properties
921 * @param array $components A list of tokens that are known to exist in the email body
923 * @return string The processed string
927 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
928 if (!is_array($components) ||
empty($contact)) {
932 foreach ($components as $name => $tokens) {
933 if (!is_array($tokens) ||
empty($tokens)) {
937 foreach ($tokens as $token) {
938 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
939 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
941 elseif (!$returnEmptyToken) {
942 //replacing empty token
943 self
::token_replace($name, $token, "", $str, $escapeSmarty);
951 * Get array of string tokens
953 * @param $string the input string to parse for tokens
955 * @return $tokens array of tokens mentioned in field
959 static function getTokens($string) {
962 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
969 foreach ($matches[1] as $token) {
970 list($type, $name) = preg_split('/\./', $token, 2);
971 if ($name && $type) {
972 if (!isset($tokens[$type])) {
973 $tokens[$type] = array();
975 $tokens[$type][] = $name;
983 * gives required details of contacts in an indexed array format so we
984 * can iterate in a nice loop and do token evaluation
986 * @param array $contactIds of contacts
987 * @param array $returnProperties of required properties
988 * @param boolean $skipOnHold don't return on_hold contact info also.
989 * @param boolean $skipDeceased don't return deceased contact info.
990 * @param array $extraParams extra params
991 * @param array $tokens the list of tokens we've extracted from the content
992 * @param int $jobID the mailing list jobID - this is a legacy param
998 static function getTokenDetails($contactIDs,
999 $returnProperties = NULL,
1001 $skipDeceased = TRUE,
1002 $extraParams = NULL,
1007 if (empty($contactIDs)) {
1008 // putting a fatal here so we can track if/when this happens
1009 CRM_Core_Error
::fatal();
1013 foreach ($contactIDs as $key => $contactID) {
1015 CRM_Core_Form
::CB_PREFIX
. $contactID,
1021 if ($skipDeceased) {
1022 $params[] = array('is_deceased', '=', 0, 0, 0);
1027 $params[] = array('on_hold', '=', 0, 0, 0);
1031 $params = array_merge($params, $extraParams);
1034 // if return properties are not passed then get all return properties
1035 if (empty($returnProperties)) {
1036 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1037 array('display_name', 'checksum', 'contact_id')
1039 foreach ($fields as $key => $val) {
1040 $returnProperties[$val] = 1;
1045 foreach ($returnProperties as $name => $dontCare) {
1046 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1052 //get the total number of contacts to fetch from database.
1053 $numberofContacts = count($contactIDs);
1054 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1056 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1058 $contactDetails = &$details[0];
1060 foreach ($contactIDs as $key => $contactID) {
1061 if (array_key_exists($contactID, $contactDetails)) {
1062 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1063 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1065 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1067 // communication Prefferance
1068 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1069 $contactDetails[$contactID]['preferred_communication_method']
1072 foreach ($contactPcm as $key => $val) {
1074 $result[$val] = $pcm[$val];
1077 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1080 foreach ($custom as $cfID) {
1081 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1082 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1088 //special case for greeting replacement
1090 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1091 if (CRM_Utils_Array
::value($val, $contactDetails[$contactID])) {
1092 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1098 // also call a hook and get token details
1099 CRM_Utils_Hook
::tokenValues($details[0],
1109 * gives required details of contribuion in an indexed array format so we
1110 * can iterate in a nice loop and do token evaluation
1112 * @param array $contributionId one contribution id
1113 * @param array $returnProperties of required properties
1114 * @param boolean $skipOnHold don't return on_hold contact info.
1115 * @param boolean $skipDeceased don't return deceased contact info.
1116 * @param array $extraParams extra params
1117 * @param array $tokens the list of tokens we've extracted from the content
1123 static function getContributionTokenDetails($contributionIDs,
1124 $returnProperties = NULL,
1125 $extraParams = NULL,
1129 if (empty($contributionIDs)) {
1130 // putting a fatal here so we can track if/when this happens
1131 CRM_Core_Error
::fatal();
1136 // no apiQuery helper yet, so do a loop and find contribution by id
1137 foreach ($contributionIDs as $contributionID) {
1139 $dao = new CRM_Contribute_DAO_Contribution();
1140 $dao->id
= $contributionID;
1142 if ($dao->find(TRUE)) {
1144 $details[$dao->id
] = array();
1145 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1147 // do the necessary transformation
1148 if (CRM_Utils_Array
::value('payment_instrument_id', $details[$dao->id
])) {
1149 $piId = $details[$dao->id
]['payment_instrument_id'];
1150 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1151 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1153 if (CRM_Utils_Array
::value('campaign_id', $details[$dao->id
])) {
1154 $campaignId = $details[$dao->id
]['campaign_id'];
1155 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1156 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1159 // TODO: call a hook to get token contribution details
1167 * replace greeting tokens exists in message/subject
1171 static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL) {
1173 if (!$contactDetails && !$contactId) {
1177 // check if there are any tokens
1178 $greetingTokens = self
::getTokens($tokenString);
1180 if (!empty($greetingTokens)) {
1181 // first use the existing contact object for token replacement
1182 if (!empty($contactDetails)) {
1183 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE);
1186 // check if there are any unevaluated tokens
1187 $greetingTokens = self
::getTokens($tokenString);
1189 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1190 // so retrieve it from database
1191 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1192 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1193 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1194 $contactParams = array('contact_id' => $contactId);
1196 $greetingDetails = self
::getTokenDetails($contactParams,
1197 $greetingsReturnProperties,
1203 // again replace tokens
1204 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1213 static function flattenTokens(&$tokens) {
1214 $flattenTokens = array();
1217 'html', 'text', 'subject') as $prop) {
1218 if (!isset($tokens[$prop])) {
1221 foreach ($tokens[$prop] as $type => $names) {
1222 if (!isset($flattenTokens[$type])) {
1223 $flattenTokens[$type] = array();
1225 foreach ($names as $name) {
1226 $flattenTokens[$type][$name] = 1;
1231 return $flattenTokens;
1235 * Replace all user tokens in $str
1237 * @param string $str The string with tokens to be replaced
1239 * @return string The processed string
1243 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1245 if (!$knownTokens ||
1246 !isset($knownTokens[$key])
1251 $str = preg_replace_callback(
1252 self
::tokenRegex($key),
1253 function ($matches) use($escapeSmarty) {
1254 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1261 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1264 list($objectName, $objectValue) = explode('-', $token, 2);
1266 switch ($objectName) {
1268 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1272 $value = CRM_Core_Permission
::roleEmails($objectValue);
1276 if ($escapeSmarty) {
1277 $value = self
::tokenEscapeSmarty($value);
1284 protected static function _buildContributionTokens() {
1285 $key = 'contribution';
1286 if (self
::$_tokens[$key] == NULL) {
1287 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1288 array('campaign', 'financial_type')
1293 public static function &replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1294 self
::_buildContributionTokens();
1296 // here we intersect with the list of pre-configured valid tokens
1297 // so that we remove anything we do not recognize
1298 // I hope to move this step out of here soon and
1299 // then we will just iterate on a list of tokens that are passed to us
1300 $key = 'contribution';
1301 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1305 $str = preg_replace_callback(
1306 self
::tokenRegex($key),
1307 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1308 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1313 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1317 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1318 self
::_buildContributionTokens();
1321 case 'total_amount':
1324 case 'non_deductible_amount':
1325 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1328 case 'receive_date':
1329 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1330 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1334 if (!in_array($token, self
::$_tokens['contribution'])) {
1335 $value = "{contribution.$token}";
1338 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1344 if ($escapeSmarty) {
1345 $value = self
::tokenEscapeSmarty($value);
1350 function getPermissionEmails($permissionName) {}
1352 function getRoleEmails($roleName) {}