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);
667 // note that incase of pseudoconstants we get array ( 0 => id, 1 => label )
668 if (is_array($value)) {
674 $value = str_replace('&', '&', $value);
677 // if null then return actual token
678 if ($returnBlankToken && !$value) {
679 $value = "{contact.$token}";
683 $value = self
::tokenEscapeSmarty($value);
690 * Replace all the hook tokens in $str with information from
693 * @param string $str The string with tokens to be replaced
694 * @param array $contact Associative array of contact properties (including hook token values)
695 * @param boolean $html Replace tokens with HTML or plain text
697 * @return string The processed string
701 public static function &replaceHookTokens(
706 $escapeSmarty = FALSE
708 foreach ($categories as $key) {
709 $str = preg_replace_callback(
710 self
::tokenRegex($key),
711 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
712 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
721 * Parse html through Smarty resolving any smarty functions
722 * @param string $tokenHtml
723 * @param array $entity
724 * @param string $entityType
725 * @return string html parsed through smarty
727 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
728 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
729 $smarty = CRM_Core_Smarty
::singleton();
730 // also add the tokens to the template
731 $smarty->assign_by_ref($entityType, $entity);
732 $tokenHtml = $smarty->fetch("string:$tokenHtml");
736 public static function getHookTokenReplacement(
741 $escapeSmarty = FALSE
743 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
745 if ($value && !$html) {
746 $value = str_replace('&', '&', $value);
750 $value = self
::tokenEscapeSmarty($value);
757 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
758 * for example {{token}} or \{token} will result in {token} in the final email
760 * this routine will remove the extra backslashes and braces
762 * @param $str ref to the string that will be scanned and modified
763 * @return void this function works directly on the string that is passed
767 public static function unescapeTokens(&$str) {
768 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
772 * Replace unsubscribe tokens
774 * @param string $str the string with tokens to be replaced
775 * @param object $domain The domain BAO
776 * @param array $groups The groups (if any) being unsubscribed
777 * @param boolean $html Replace tokens with html or plain text
778 * @param int $contact_id The contact ID
779 * @param string hash The security hash of the unsub event
781 * @return string The processed string
785 public static function &replaceUnsubscribeTokens(
793 if (self
::token_match('unsubscribe', 'group', $str)) {
794 if (!empty($groups)) {
795 $config = CRM_Core_Config
::singleton();
796 $base = CRM_Utils_System
::baseURL();
798 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
799 $dao = new CRM_Contact_DAO_Group();
801 while ($dao->fetch()) {
802 if (substr($dao->visibility
, 0, 6) == 'Public') {
803 $visibleGroups[] = $dao->id
;
806 $value = implode(', ', $groups);
807 self
::token_replace('unsubscribe', 'group', $value, $str);
814 * Replace resubscribe tokens
816 * @param string $str the string with tokens to be replaced
817 * @param object $domain The domain BAO
818 * @param array $groups The groups (if any) being resubscribed
819 * @param boolean $html Replace tokens with html or plain text
820 * @param int $contact_id The contact ID
821 * @param string hash The security hash of the resub event
823 * @return string The processed string
827 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
830 if (self
::token_match('resubscribe', 'group', $str)) {
831 if (!empty($groups)) {
832 $value = implode(', ', $groups);
833 self
::token_replace('resubscribe', 'group', $value, $str);
840 * Replace subscription-confirmation-request tokens
842 * @param string $str The string with tokens to be replaced
843 * @param string $group The name of the group being subscribed
844 * @param boolean $html Replace tokens with html or plain text
846 * @return string The processed string
850 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
851 if (self
::token_match('subscribe', 'group', $str)) {
852 self
::token_replace('subscribe', 'group', $group, $str);
854 if (self
::token_match('subscribe', 'url', $str)) {
855 self
::token_replace('subscribe', 'url', $url, $str);
861 * Replace subscription-invitation tokens
863 * @param string $str The string with tokens to be replaced
865 * @return string The processed string
869 public static function &replaceSubscribeInviteTokens($str) {
870 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
871 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
873 TRUE, NULL, TRUE, TRUE
875 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
878 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
879 foreach ($matches as $key => $value) {
880 $gid = substr($value, 21, -1);
881 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
882 "reset=1&gid={$gid}",
883 TRUE, NULL, TRUE, TRUE
885 $url = str_replace('&', '&', $url);
886 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
890 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
891 foreach ($matches as $key => $value) {
892 $gid = substr($value, 18, -1);
893 $config = CRM_Core_Config
::singleton();
894 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
895 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
896 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
897 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
904 * Replace welcome/confirmation tokens
906 * @param string $str The string with tokens to be replaced
907 * @param string $group The name of the group being subscribed
908 * @param boolean $html Replace tokens with html or plain text
910 * @return string The processed string
914 public static function &replaceWelcomeTokens($str, $group, $html) {
915 if (self
::token_match('welcome', 'group', $str)) {
916 self
::token_replace('welcome', 'group', $group, $str);
922 * Find unprocessed tokens (call this last)
924 * @param string $str The string to search
926 * @return array Array of tokens that weren't replaced
930 public static function &unmatchedTokens(&$str) {
931 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
932 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
937 * Find and replace tokens for each component
939 * @param string $str The string to search
940 * @param array $contact Associative array of contact properties
941 * @param array $components A list of tokens that are known to exist in the email body
943 * @return string The processed string
947 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
948 if (!is_array($components) ||
empty($contact)) {
952 foreach ($components as $name => $tokens) {
953 if (!is_array($tokens) ||
empty($tokens)) {
957 foreach ($tokens as $token) {
958 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
959 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
961 elseif (!$returnEmptyToken) {
962 //replacing empty token
963 self
::token_replace($name, $token, "", $str, $escapeSmarty);
971 * Get array of string tokens
973 * @param $string the input string to parse for tokens
975 * @return $tokens array of tokens mentioned in field
979 static function getTokens($string) {
982 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
989 foreach ($matches[1] as $token) {
990 list($type, $name) = preg_split('/\./', $token, 2);
991 if ($name && $type) {
992 if (!isset($tokens[$type])) {
993 $tokens[$type] = array();
995 $tokens[$type][] = $name;
1003 * gives required details of contacts in an indexed array format so we
1004 * can iterate in a nice loop and do token evaluation
1006 * @param array $contactIds of contacts
1007 * @param array $returnProperties of required properties
1008 * @param boolean $skipOnHold don't return on_hold contact info also.
1009 * @param boolean $skipDeceased don't return deceased contact info.
1010 * @param array $extraParams extra params
1011 * @param array $tokens the list of tokens we've extracted from the content
1012 * @param int $jobID the mailing list jobID - this is a legacy param
1018 static function getTokenDetails($contactIDs,
1019 $returnProperties = NULL,
1021 $skipDeceased = TRUE,
1022 $extraParams = NULL,
1027 if (empty($contactIDs)) {
1028 // putting a fatal here so we can track if/when this happens
1029 CRM_Core_Error
::fatal();
1033 foreach ($contactIDs as $key => $contactID) {
1035 CRM_Core_Form
::CB_PREFIX
. $contactID,
1041 if ($skipDeceased) {
1042 $params[] = array('is_deceased', '=', 0, 0, 0);
1047 $params[] = array('on_hold', '=', 0, 0, 0);
1051 $params = array_merge($params, $extraParams);
1054 // if return properties are not passed then get all return properties
1055 if (empty($returnProperties)) {
1056 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1057 array('display_name', 'checksum', 'contact_id')
1059 foreach ($fields as $key => $val) {
1060 $returnProperties[$val] = 1;
1065 foreach ($returnProperties as $name => $dontCare) {
1066 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1072 //get the total number of contacts to fetch from database.
1073 $numberofContacts = count($contactIDs);
1074 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1076 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1078 $contactDetails = &$details[0];
1080 foreach ($contactIDs as $key => $contactID) {
1081 if (array_key_exists($contactID, $contactDetails)) {
1082 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1083 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1085 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1087 // communication Prefferance
1088 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1089 $contactDetails[$contactID]['preferred_communication_method']
1092 foreach ($contactPcm as $key => $val) {
1094 $result[$val] = $pcm[$val];
1097 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1100 foreach ($custom as $cfID) {
1101 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1102 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1108 //special case for greeting replacement
1110 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1111 if (CRM_Utils_Array
::value($val, $contactDetails[$contactID])) {
1112 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1118 // also call a hook and get token details
1119 CRM_Utils_Hook
::tokenValues($details[0],
1129 * gives required details of contribuion in an indexed array format so we
1130 * can iterate in a nice loop and do token evaluation
1132 * @param array $contributionId one contribution id
1133 * @param array $returnProperties of required properties
1134 * @param boolean $skipOnHold don't return on_hold contact info.
1135 * @param boolean $skipDeceased don't return deceased contact info.
1136 * @param array $extraParams extra params
1137 * @param array $tokens the list of tokens we've extracted from the content
1143 static function getContributionTokenDetails($contributionIDs,
1144 $returnProperties = NULL,
1145 $extraParams = NULL,
1149 if (empty($contributionIDs)) {
1150 // putting a fatal here so we can track if/when this happens
1151 CRM_Core_Error
::fatal();
1156 // no apiQuery helper yet, so do a loop and find contribution by id
1157 foreach ($contributionIDs as $contributionID) {
1159 $dao = new CRM_Contribute_DAO_Contribution();
1160 $dao->id
= $contributionID;
1162 if ($dao->find(TRUE)) {
1164 $details[$dao->id
] = array();
1165 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1167 // do the necessary transformation
1168 if (CRM_Utils_Array
::value('payment_instrument_id', $details[$dao->id
])) {
1169 $piId = $details[$dao->id
]['payment_instrument_id'];
1170 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1171 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1173 if (CRM_Utils_Array
::value('campaign_id', $details[$dao->id
])) {
1174 $campaignId = $details[$dao->id
]['campaign_id'];
1175 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1176 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1179 if (CRM_Utils_Array
::value('financial_type_id', $details[$dao->id
])) {
1180 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1181 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1182 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1185 // TODO: call a hook to get token contribution details
1193 * Get Membership Token Details
1194 * @param array $membershipIDs array of membership IDS
1196 static function getMembershipTokenDetails($membershipIDs) {
1197 $memberships = civicrm_api3('membership', 'get', array('membership_id' => array('IN' => (array) $membershipIDs)));
1198 return $memberships['values'];
1201 * replace greeting tokens exists in message/subject
1205 static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL) {
1207 if (!$contactDetails && !$contactId) {
1211 // check if there are any tokens
1212 $greetingTokens = self
::getTokens($tokenString);
1214 if (!empty($greetingTokens)) {
1215 // first use the existing contact object for token replacement
1216 if (!empty($contactDetails)) {
1217 // unset id's to get labels for the pseudoconstants
1218 foreach ( array('individual_prefix', 'individual_suffix', 'gender') as $field ) {
1219 unset($contactDetails[0][$contactId][$field]);
1221 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE);
1224 // check if there are any unevaluated tokens
1225 $greetingTokens = self
::getTokens($tokenString);
1227 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1228 // so retrieve it from database
1229 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1230 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1231 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1232 $contactParams = array('contact_id' => $contactId);
1234 $greetingDetails = self
::getTokenDetails($contactParams,
1235 $greetingsReturnProperties,
1241 // again replace tokens
1242 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1251 static function flattenTokens(&$tokens) {
1252 $flattenTokens = array();
1255 'html', 'text', 'subject') as $prop) {
1256 if (!isset($tokens[$prop])) {
1259 foreach ($tokens[$prop] as $type => $names) {
1260 if (!isset($flattenTokens[$type])) {
1261 $flattenTokens[$type] = array();
1263 foreach ($names as $name) {
1264 $flattenTokens[$type][$name] = 1;
1269 return $flattenTokens;
1273 * Replace all user tokens in $str
1275 * @param string $str The string with tokens to be replaced
1277 * @return string The processed string
1281 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1283 if (!$knownTokens ||
1284 !isset($knownTokens[$key])
1289 $str = preg_replace_callback(
1290 self
::tokenRegex($key),
1291 function ($matches) use($escapeSmarty) {
1292 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1299 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1302 list($objectName, $objectValue) = explode('-', $token, 2);
1304 switch ($objectName) {
1306 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1310 $value = CRM_Core_Permission
::roleEmails($objectValue);
1314 if ($escapeSmarty) {
1315 $value = self
::tokenEscapeSmarty($value);
1322 protected static function _buildContributionTokens() {
1323 $key = 'contribution';
1324 if (self
::$_tokens[$key] == NULL) {
1325 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1326 array('campaign', 'financial_type')
1332 * store membership tokens on the static _tokens array
1334 protected static function _buildMembershipTokens() {
1335 $key = 'membership';
1336 if (self
::$_tokens[$key] == NULL) {
1337 $membershipTokens = array();
1338 $tokens = CRM_Core_SelectValues
::membershipTokens();
1339 foreach ($tokens as $token => $dontCare) {
1340 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1342 self
::$_tokens[$key] = $membershipTokens;
1347 * Replace tokens for an entity
1348 * @param string $entity
1349 * @param array $entityArray (e.g. in format from api)
1350 * @param string $str string to replace in
1351 * @param array $knownTokens array of tokens present
1352 * @param boolean $escapeSmarty
1353 * @return string string with replacements made
1355 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1356 if (!$knownTokens ||
!CRM_Utils_Array
::value($entity, $knownTokens)) {
1360 $fn = 'get' . ucFirst($entity) . 'tokenReplacement';
1361 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1362 foreach ($knownTokens[$entity] as $token) {
1363 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1364 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1366 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1370 public static function &replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1371 self
::_buildContributionTokens();
1373 // here we intersect with the list of pre-configured valid tokens
1374 // so that we remove anything we do not recognize
1375 // I hope to move this step out of here soon and
1376 // then we will just iterate on a list of tokens that are passed to us
1377 $key = 'contribution';
1378 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1382 $str = preg_replace_callback(
1383 self
::tokenRegex($key),
1384 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1385 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1390 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1395 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1396 * - this is used by the pdfLetter task from membership search
1397 * @param string $token
1398 * @param array $membership an api result array for a single membership
1399 * @param boolean $escapeSmarty
1400 * @return string token replacement
1402 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1403 $entity = 'membership';
1404 self
::_buildMembershipTokens();
1407 $value = $membership['membership_name'];
1410 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1411 $value = $statuses[$membership['status_id']];
1415 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1417 catch (CiviCRM_API3_Exception
$e) {
1418 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1419 // api handles NULL (4.4)
1424 if (in_array($token, self
::$_tokens[$entity])) {
1425 $value = $membership[$token];
1429 $value = "{$entity}.{$token}";
1434 if ($escapeSmarty) {
1435 $value = self
::tokenEscapeSmarty($value);
1440 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1441 self
::_buildContributionTokens();
1444 case 'total_amount':
1447 case 'non_deductible_amount':
1448 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1451 case 'receive_date':
1452 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1453 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1457 if (!in_array($token, self
::$_tokens['contribution'])) {
1458 $value = "{contribution.$token}";
1461 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1467 if ($escapeSmarty) {
1468 $value = self
::tokenEscapeSmarty($value);
1473 function getPermissionEmails($permissionName) {}
1475 function getRoleEmails($roleName) {}