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 // Support legacy tokens
648 $token = CRM_Utils_Array
::value($token, self
::legacyContactTokens(), $token);
650 // check if the token we were passed is valid
651 // we have to do this because this function is
652 // called only when we find a token in the string
654 if (!in_array($token, self
::$_tokens['contact'])) {
655 $value = "{contact.$token}";
657 elseif ($token == 'checksum') {
658 $hash = CRM_Utils_Array
::value('hash', $contact);
659 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
660 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
668 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
670 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
671 if (is_array($value)) {
674 // Convert pseudoconstants using metadata
675 elseif ($value && is_numeric($value)) {
676 $allFields = CRM_Contact_BAO_Contact
::exportableFields('All');
677 if (!empty($allFields[$token]['pseudoconstant'])) {
678 $value = CRM_Core_PseudoConstant
::getLabel('CRM_Contact_BAO_Contact', $token, $value);
684 $value = str_replace('&', '&', $value);
687 // if null then return actual token
688 if ($returnBlankToken && !$value) {
689 $value = "{contact.$token}";
693 $value = self
::tokenEscapeSmarty($value);
700 * Replace all the hook tokens in $str with information from
703 * @param string $str The string with tokens to be replaced
704 * @param array $contact Associative array of contact properties (including hook token values)
705 * @param boolean $html Replace tokens with HTML or plain text
707 * @return string The processed string
711 public static function &replaceHookTokens(
716 $escapeSmarty = FALSE
718 foreach ($categories as $key) {
719 $str = preg_replace_callback(
720 self
::tokenRegex($key),
721 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
722 return CRM_Utils_Token
::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
731 * Parse html through Smarty resolving any smarty functions
732 * @param string $tokenHtml
733 * @param array $entity
734 * @param string $entityType
735 * @return string html parsed through smarty
737 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
738 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
) {
739 $smarty = CRM_Core_Smarty
::singleton();
740 // also add the tokens to the template
741 $smarty->assign_by_ref($entityType, $entity);
742 $tokenHtml = $smarty->fetch("string:$tokenHtml");
746 public static function getHookTokenReplacement(
751 $escapeSmarty = FALSE
753 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
755 if ($value && !$html) {
756 $value = str_replace('&', '&', $value);
760 $value = self
::tokenEscapeSmarty($value);
767 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
768 * for example {{token}} or \{token} will result in {token} in the final email
770 * this routine will remove the extra backslashes and braces
772 * @param $str ref to the string that will be scanned and modified
773 * @return void this function works directly on the string that is passed
777 public static function unescapeTokens(&$str) {
778 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
782 * Replace unsubscribe tokens
784 * @param string $str the string with tokens to be replaced
785 * @param object $domain The domain BAO
786 * @param array $groups The groups (if any) being unsubscribed
787 * @param boolean $html Replace tokens with html or plain text
788 * @param int $contact_id The contact ID
789 * @param string hash The security hash of the unsub event
791 * @return string The processed string
795 public static function &replaceUnsubscribeTokens(
803 if (self
::token_match('unsubscribe', 'group', $str)) {
804 if (!empty($groups)) {
805 $config = CRM_Core_Config
::singleton();
806 $base = CRM_Utils_System
::baseURL();
808 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
809 $dao = new CRM_Contact_DAO_Group();
811 while ($dao->fetch()) {
812 if (substr($dao->visibility
, 0, 6) == 'Public') {
813 $visibleGroups[] = $dao->id
;
816 $value = implode(', ', $groups);
817 self
::token_replace('unsubscribe', 'group', $value, $str);
824 * Replace resubscribe tokens
826 * @param string $str the string with tokens to be replaced
827 * @param object $domain The domain BAO
828 * @param array $groups The groups (if any) being resubscribed
829 * @param boolean $html Replace tokens with html or plain text
830 * @param int $contact_id The contact ID
831 * @param string hash The security hash of the resub event
833 * @return string The processed string
837 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
840 if (self
::token_match('resubscribe', 'group', $str)) {
841 if (!empty($groups)) {
842 $value = implode(', ', $groups);
843 self
::token_replace('resubscribe', 'group', $value, $str);
850 * Replace subscription-confirmation-request tokens
852 * @param string $str The string with tokens to be replaced
853 * @param string $group The name of the group being subscribed
854 * @param boolean $html Replace tokens with html or plain text
856 * @return string The processed string
860 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
861 if (self
::token_match('subscribe', 'group', $str)) {
862 self
::token_replace('subscribe', 'group', $group, $str);
864 if (self
::token_match('subscribe', 'url', $str)) {
865 self
::token_replace('subscribe', 'url', $url, $str);
871 * Replace subscription-invitation tokens
873 * @param string $str The string with tokens to be replaced
875 * @return string The processed string
879 public static function &replaceSubscribeInviteTokens($str) {
880 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
881 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
883 TRUE, NULL, TRUE, TRUE
885 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
888 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
889 foreach ($matches as $key => $value) {
890 $gid = substr($value, 21, -1);
891 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
892 "reset=1&gid={$gid}",
893 TRUE, NULL, TRUE, TRUE
895 $url = str_replace('&', '&', $url);
896 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
900 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
901 foreach ($matches as $key => $value) {
902 $gid = substr($value, 18, -1);
903 $config = CRM_Core_Config
::singleton();
904 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
905 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
906 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
907 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
914 * Replace welcome/confirmation tokens
916 * @param string $str The string with tokens to be replaced
917 * @param string $group The name of the group being subscribed
918 * @param boolean $html Replace tokens with html or plain text
920 * @return string The processed string
924 public static function &replaceWelcomeTokens($str, $group, $html) {
925 if (self
::token_match('welcome', 'group', $str)) {
926 self
::token_replace('welcome', 'group', $group, $str);
932 * Find unprocessed tokens (call this last)
934 * @param string $str The string to search
936 * @return array Array of tokens that weren't replaced
940 public static function &unmatchedTokens(&$str) {
941 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
942 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
947 * Find and replace tokens for each component
949 * @param string $str The string to search
950 * @param array $contact Associative array of contact properties
951 * @param array $components A list of tokens that are known to exist in the email body
953 * @return string The processed string
957 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
958 if (!is_array($components) ||
empty($contact)) {
962 foreach ($components as $name => $tokens) {
963 if (!is_array($tokens) ||
empty($tokens)) {
967 foreach ($tokens as $token) {
968 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
969 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
971 elseif (!$returnEmptyToken) {
972 //replacing empty token
973 self
::token_replace($name, $token, "", $str, $escapeSmarty);
981 * Get array of string tokens
983 * @param $string the input string to parse for tokens
985 * @return $tokens array of tokens mentioned in field
989 static function getTokens($string) {
992 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
999 foreach ($matches[1] as $token) {
1000 list($type, $name) = preg_split('/\./', $token, 2);
1001 if ($name && $type) {
1002 if (!isset($tokens[$type])) {
1003 $tokens[$type] = array();
1005 $tokens[$type][] = $name;
1013 * gives required details of contacts in an indexed array format so we
1014 * can iterate in a nice loop and do token evaluation
1016 * @param array $contactIds of contacts
1017 * @param array $returnProperties of required properties
1018 * @param boolean $skipOnHold don't return on_hold contact info also.
1019 * @param boolean $skipDeceased don't return deceased contact info.
1020 * @param array $extraParams extra params
1021 * @param array $tokens the list of tokens we've extracted from the content
1022 * @param int $jobID the mailing list jobID - this is a legacy param
1028 static function getTokenDetails($contactIDs,
1029 $returnProperties = NULL,
1031 $skipDeceased = TRUE,
1032 $extraParams = NULL,
1037 if (empty($contactIDs)) {
1038 // putting a fatal here so we can track if/when this happens
1039 CRM_Core_Error
::fatal();
1043 foreach ($contactIDs as $key => $contactID) {
1045 CRM_Core_Form
::CB_PREFIX
. $contactID,
1051 if ($skipDeceased) {
1052 $params[] = array('is_deceased', '=', 0, 0, 0);
1057 $params[] = array('on_hold', '=', 0, 0, 0);
1061 $params = array_merge($params, $extraParams);
1064 // if return properties are not passed then get all return properties
1065 if (empty($returnProperties)) {
1066 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1067 array('display_name', 'checksum', 'contact_id')
1069 foreach ($fields as $key => $val) {
1070 $returnProperties[$val] = 1;
1075 foreach ($returnProperties as $name => $dontCare) {
1076 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1082 //get the total number of contacts to fetch from database.
1083 $numberofContacts = count($contactIDs);
1084 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1086 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1088 $contactDetails = &$details[0];
1090 foreach ($contactIDs as $key => $contactID) {
1091 if (array_key_exists($contactID, $contactDetails)) {
1092 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1093 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1095 $pcm = CRM_Core_PseudoConstant
::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1097 // communication Prefferance
1098 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1099 $contactDetails[$contactID]['preferred_communication_method']
1102 foreach ($contactPcm as $key => $val) {
1104 $result[$val] = $pcm[$val];
1107 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1110 foreach ($custom as $cfID) {
1111 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1112 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1118 //special case for greeting replacement
1120 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1121 if (CRM_Utils_Array
::value($val, $contactDetails[$contactID])) {
1122 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1128 // also call a hook and get token details
1129 CRM_Utils_Hook
::tokenValues($details[0],
1139 * gives required details of contribuion in an indexed array format so we
1140 * can iterate in a nice loop and do token evaluation
1142 * @param array $contributionId one contribution id
1143 * @param array $returnProperties of required properties
1144 * @param boolean $skipOnHold don't return on_hold contact info.
1145 * @param boolean $skipDeceased don't return deceased contact info.
1146 * @param array $extraParams extra params
1147 * @param array $tokens the list of tokens we've extracted from the content
1153 static function getContributionTokenDetails($contributionIDs,
1154 $returnProperties = NULL,
1155 $extraParams = NULL,
1159 if (empty($contributionIDs)) {
1160 // putting a fatal here so we can track if/when this happens
1161 CRM_Core_Error
::fatal();
1166 // no apiQuery helper yet, so do a loop and find contribution by id
1167 foreach ($contributionIDs as $contributionID) {
1169 $dao = new CRM_Contribute_DAO_Contribution();
1170 $dao->id
= $contributionID;
1172 if ($dao->find(TRUE)) {
1174 $details[$dao->id
] = array();
1175 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1177 // do the necessary transformation
1178 if (CRM_Utils_Array
::value('payment_instrument_id', $details[$dao->id
])) {
1179 $piId = $details[$dao->id
]['payment_instrument_id'];
1180 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1181 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1183 if (CRM_Utils_Array
::value('campaign_id', $details[$dao->id
])) {
1184 $campaignId = $details[$dao->id
]['campaign_id'];
1185 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1186 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1189 if (CRM_Utils_Array
::value('financial_type_id', $details[$dao->id
])) {
1190 $financialtypeId = $details[$dao->id
]['financial_type_id'];
1191 $ftis = CRM_Contribute_PseudoConstant
::financialType();
1192 $details[$dao->id
]['financial_type'] = $ftis[$financialtypeId];
1195 // TODO: call a hook to get token contribution details
1203 * Get Membership Token Details
1204 * @param array $membershipIDs array of membership IDS
1206 static function getMembershipTokenDetails($membershipIDs) {
1207 $memberships = civicrm_api3('membership', 'get', array('options' => array('limit' => 200000), 'membership_id' => array('IN' => (array) $membershipIDs)));
1208 return $memberships['values'];
1211 * replace greeting tokens exists in message/subject
1215 static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL) {
1217 if (!$contactDetails && !$contactId) {
1221 // check if there are any tokens
1222 $greetingTokens = self
::getTokens($tokenString);
1224 if (!empty($greetingTokens)) {
1225 // first use the existing contact object for token replacement
1226 if (!empty($contactDetails)) {
1227 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE);
1230 // check if there are any unevaluated tokens
1231 $greetingTokens = self
::getTokens($tokenString);
1233 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1234 // so retrieve it from database
1235 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1236 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1237 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1238 $contactParams = array('contact_id' => $contactId);
1240 $greetingDetails = self
::getTokenDetails($contactParams,
1241 $greetingsReturnProperties,
1247 // again replace tokens
1248 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1257 static function flattenTokens(&$tokens) {
1258 $flattenTokens = array();
1261 'html', 'text', 'subject') as $prop) {
1262 if (!isset($tokens[$prop])) {
1265 foreach ($tokens[$prop] as $type => $names) {
1266 if (!isset($flattenTokens[$type])) {
1267 $flattenTokens[$type] = array();
1269 foreach ($names as $name) {
1270 $flattenTokens[$type][$name] = 1;
1275 return $flattenTokens;
1279 * Replace all user tokens in $str
1281 * @param string $str The string with tokens to be replaced
1283 * @return string The processed string
1287 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1289 if (!$knownTokens ||
1290 !isset($knownTokens[$key])
1295 $str = preg_replace_callback(
1296 self
::tokenRegex($key),
1297 function ($matches) use($escapeSmarty) {
1298 return CRM_Utils_Token
::getUserTokenReplacement($matches[1], $escapeSmarty);
1305 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1308 list($objectName, $objectValue) = explode('-', $token, 2);
1310 switch ($objectName) {
1312 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1316 $value = CRM_Core_Permission
::roleEmails($objectValue);
1320 if ($escapeSmarty) {
1321 $value = self
::tokenEscapeSmarty($value);
1328 protected static function _buildContributionTokens() {
1329 $key = 'contribution';
1330 if (self
::$_tokens[$key] == NULL) {
1331 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1332 array('campaign', 'financial_type')
1338 * store membership tokens on the static _tokens array
1340 protected static function _buildMembershipTokens() {
1341 $key = 'membership';
1342 if (!isset(self
::$_tokens[$key]) || self
::$_tokens[$key] == NULL) {
1343 $membershipTokens = array();
1344 $tokens = CRM_Core_SelectValues
::membershipTokens();
1345 foreach ($tokens as $token => $dontCare) {
1346 $membershipTokens[] = substr($token, (strpos($token, '.') +
1), -1);
1348 self
::$_tokens[$key] = $membershipTokens;
1353 * Replace tokens for an entity
1354 * @param string $entity
1355 * @param array $entityArray (e.g. in format from api)
1356 * @param string $str string to replace in
1357 * @param array $knownTokens array of tokens present
1358 * @param boolean $escapeSmarty
1359 * @return string string with replacements made
1361 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1362 if (!$knownTokens ||
!CRM_Utils_Array
::value($entity, $knownTokens)) {
1366 $fn = 'get' . ucFirst($entity) . 'tokenReplacement';
1367 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1368 foreach ($knownTokens[$entity] as $token) {
1369 $replaceMent = CRM_Utils_Token
::$fn($token, $entityArray, $escapeSmarty);
1370 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1372 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1376 public static function &replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1377 self
::_buildContributionTokens();
1379 // here we intersect with the list of pre-configured valid tokens
1380 // so that we remove anything we do not recognize
1381 // I hope to move this step out of here soon and
1382 // then we will just iterate on a list of tokens that are passed to us
1383 $key = 'contribution';
1384 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1388 $str = preg_replace_callback(
1389 self
::tokenRegex($key),
1390 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1391 return CRM_Utils_Token
::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1396 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1401 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1402 * - this is used by the pdfLetter task from membership search
1403 * @param string $token
1404 * @param array $membership an api result array for a single membership
1405 * @param boolean $escapeSmarty
1406 * @return string token replacement
1408 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1409 $entity = 'membership';
1410 self
::_buildMembershipTokens();
1413 $value = $membership['membership_name'];
1416 $statuses = CRM_Member_BAO_Membership
::buildOptions('status_id');
1417 $value = $statuses[$membership['status_id']];
1421 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1423 catch (CiviCRM_API3_Exception
$e) {
1424 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1425 // api handles NULL (4.4)
1430 if (in_array($token, self
::$_tokens[$entity])) {
1431 $value = $membership[$token];
1435 $value = "{$entity}.{$token}";
1440 if ($escapeSmarty) {
1441 $value = self
::tokenEscapeSmarty($value);
1446 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1447 self
::_buildContributionTokens();
1450 case 'total_amount':
1453 case 'non_deductible_amount':
1454 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1457 case 'receive_date':
1458 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1459 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1463 if (!in_array($token, self
::$_tokens['contribution'])) {
1464 $value = "{contribution.$token}";
1467 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1473 if ($escapeSmarty) {
1474 $value = self
::tokenEscapeSmarty($value);
1479 function getPermissionEmails($permissionName) {}
1481 function getRoleEmails($roleName) {}
1484 * @return array: legacy_token => new_token
1486 static function legacyContactTokens() {
1488 'individual_prefix' => 'prefix_id',
1489 'individual_suffix' => 'suffix_id',
1490 'gender' => 'gender_id',