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.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]+)?)\}(?!\})/e';
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)
240 self
::tokenRegex($key),
241 'self::getDomainTokenReplacement(\'\\1\',$domain,$html)',
247 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
248 // check if the token we were passed is valid
249 // we have to do this because this function is
250 // called only when we find a token in the string
252 $loc = &$domain->getLocationValues();
254 if (!in_array($token, self
::$_tokens['domain'])) {
255 $value = "{domain.$token}";
257 elseif ($token == 'address') {
258 static $addressCache = array();
260 $cache_key = $html ?
'address-html' : 'address-text';
261 if (array_key_exists($cache_key, $addressCache)) {
262 return $addressCache[$cache_key];
266 /* Construct the address token */
268 if (CRM_Utils_Array
::value($token, $loc)) {
270 $value = $loc[$token][1]['display'];
271 $value = str_replace("\n", '<br />', $value);
274 $value = $loc[$token][1]['display_text'];
276 $addressCache[$cache_key] = $value;
279 elseif ($token == 'name' ||
$token == 'id' ||
$token == 'description') {
280 $value = $domain->$token;
282 elseif ($token == 'phone' ||
$token == 'email') {
283 /* Construct the phone and email tokens */
286 if (CRM_Utils_Array
::value($token, $loc)) {
287 foreach ($loc[$token] as $index => $entity) {
288 $value = $entity[$token];
295 $value = self
::tokenEscapeSmarty($value);
302 * Replace all the org-level tokens in $str
304 * @param string $str The string with tokens to be replaced
305 * @param object $org Associative array of org properties
306 * @param boolean $html Replace tokens with HTML or plain text
308 * @return string The processed string
312 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
313 self
::$_tokens['org'] =
315 array_keys(CRM_Contact_BAO_Contact
::importableFields('Organization')),
316 array('address', 'display_name', 'checksum', 'contact_id')
320 foreach (self
::$_tokens['org'] as $token) {
321 // print "Getting token value for $token<br/><br/>";
326 /* If the string doesn't contain this token, skip it. */
328 if (!self
::token_match('org', $token, $str)) {
332 /* Construct value from $token and $contact */
336 if ($cfID = CRM_Core_BAO_CustomField
::getKeyID($token)) {
337 // only generate cv if we need it
339 $cv = CRM_Core_BAO_CustomValue
::getContactValues($org['contact_id']);
341 foreach ($cv as $cvFieldID => $value) {
342 if ($cvFieldID == $cfID) {
343 $value = CRM_Core_BAO_CustomOption
::getOptionLabel($cfID, $value);
348 elseif ($token == 'checksum') {
349 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($org['contact_id']);
352 elseif ($token == 'address') {
353 /* Build the location values array */
356 $loc['display_name'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'display_name');
357 $loc['street_address'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'street_address');
358 $loc['city'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'city');
359 $loc['state_province'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'state_province');
360 $loc['postal_code'] = CRM_Utils_Array
::retrieveValueRecursive($org, 'postal_code');
362 /* Construct the address token */
364 $value = CRM_Utils_Address
::format($loc);
366 $value = str_replace("\n", '<br />', $value);
370 $value = CRM_Utils_Array
::retrieveValueRecursive($org, $token);
373 self
::token_replace('org', $token, $value, $str, $escapeSmarty);
380 * Replace all mailing tokens in $str
382 * @param string $str The string with tokens to be replaced
383 * @param object $mailing The mailing BAO, or null for validation
384 * @param boolean $html Replace tokens with HTML or plain text
386 * @return string The processed sstring
390 public static function &replaceMailingTokens(
395 $escapeSmarty = FALSE
398 if (!$knownTokens ||
!isset($knownTokens[$key])) {
403 self
::tokenRegex($key),
404 'self::getMailingTokenReplacement(\'\\1\',$mailing,$escapeSmarty)', $str
409 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
415 $value = $mailing ?
$mailing->id
: 'undefined';
419 $value = $mailing ?
$mailing->name
: 'Mailing Name';
423 $groups = $mailing ?
$mailing->getGroupNames() : array('Mailing Groups');
424 $value = implode(', ', $groups);
428 $value = $mailing->subject
;
432 $value = CRM_Utils_System
::url('civicrm/mailing/view',
433 "reset=1&id={$mailing->id}",
434 TRUE, NULL, FALSE, TRUE
439 $value = CRM_Utils_System
::url('civicrm/mailing/send',
440 "reset=1&mid={$mailing->id}&continue=true",
441 TRUE, NULL, FALSE, TRUE
446 $value = CRM_Utils_System
::url('civicrm/mailing/schedule',
447 "reset=1&mid={$mailing->id}",
448 TRUE, NULL, FALSE, TRUE
453 $page = new CRM_Mailing_Page_View();
454 $value = $page->run($mailing->id
, NULL, FALSE);
457 case 'approvalStatus':
458 $mailApprovalStatus = CRM_Mailing_PseudoConstant
::approvalStatus();
459 $value = $mailApprovalStatus[$mailing->approval_status_id
];
463 $value = $mailing->approval_note
;
467 $value = CRM_Utils_System
::url('civicrm/mailing/approve',
468 "reset=1&mid={$mailing->id}",
469 TRUE, NULL, FALSE, TRUE
474 $value = CRM_Contact_BAO_Contact
::displayName($mailing->created_id
);
478 $value = CRM_Contact_BAO_Contact
::getPrimaryEmail($mailing->created_id
);
482 $value = "{mailing.$token}";
487 $value = self
::tokenEscapeSmarty($value);
493 * Replace all action tokens in $str
495 * @param string $str The string with tokens to be replaced
496 * @param array $addresses Assoc. array of VERP event addresses
497 * @param array $urls Assoc. array of action URLs
498 * @param boolean $html Replace tokens with HTML or plain text
499 * @param array $knownTokens A list of tokens that are known to exist in the email body
501 * @return string The processed string
505 public static function &replaceActionTokens(
511 $escapeSmarty = FALSE
514 // here we intersect with the list of pre-configured valid tokens
515 // so that we remove anything we do not recognize
516 // I hope to move this step out of here soon and
517 // then we will just iterate on a list of tokens that are passed to us
518 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
522 $str = preg_replace(self
::tokenRegex($key),
523 'self::getActionTokenReplacement(\'\\1\',$addresses,$urls,$escapeSmarty)',
529 public static function getActionTokenReplacement(
534 $escapeSmarty = FALSE
536 /* If the token is an email action, use it. Otherwise, find the
539 if (!in_array($token, self
::$_tokens['action'])) {
540 $value = "{action.$token}";
543 $value = CRM_Utils_Array
::value($token, $addresses);
545 if ($value == NULL) {
546 $value = CRM_Utils_Array
::value($token, $urls);
549 if ($value && $html) {
551 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
552 $value = "mailto:$value";
555 elseif ($value && !$html) {
556 $value = str_replace('&', '&', $value);
561 $value = self
::tokenEscapeSmarty($value);
567 * Replace all the contact-level tokens in $str with information from
570 * @param string $str The string with tokens to be replaced
571 * @param array $contact Associative array of contact properties
572 * @param boolean $html Replace tokens with HTML or plain text
573 * @param array $knownTokens A list of tokens that are known to exist in the email body
574 * @param boolean $returnBlankToken return unevaluated token if value is null
576 * @return string The processed string
580 public static function &replaceContactTokens(
585 $returnBlankToken = FALSE,
586 $escapeSmarty = FALSE
589 if (self
::$_tokens[$key] == NULL) {
590 /* This should come from UF */
592 self
::$_tokens[$key] =
594 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
595 array('checksum', 'contact_id')
599 // here we intersect with the list of pre-configured valid tokens
600 // so that we remove anything we do not recognize
601 // I hope to move this step out of here soon and
602 // then we will just iterate on a list of tokens that are passed to us
603 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
608 self
::tokenRegex($key),
609 'self::getContactTokenReplacement(\'\\1\', $contact, $html, $returnBlankToken, $escapeSmarty)',
613 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
617 public static function getContactTokenReplacement(
621 $returnBlankToken = FALSE,
622 $escapeSmarty = FALSE
624 if (self
::$_tokens['contact'] == NULL) {
625 /* This should come from UF */
627 self
::$_tokens['contact'] =
629 array_keys(CRM_Contact_BAO_Contact
::exportableFields('All')),
630 array('checksum', 'contact_id')
634 /* Construct value from $token and $contact */
638 // check if the token we were passed is valid
639 // we have to do this because this function is
640 // called only when we find a token in the string
642 if (!in_array($token, self
::$_tokens['contact'])) {
643 $value = "{contact.$token}";
645 elseif ($token == 'checksum') {
646 $hash = CRM_Utils_Array
::value('hash', $contact);
647 $contactID = CRM_Utils_Array
::retrieveValueRecursive($contact, 'contact_id');
648 $cs = CRM_Contact_BAO_Contact_Utils
::generateChecksum($contactID,
656 $value = CRM_Utils_Array
::retrieveValueRecursive($contact, $token);
660 $value = str_replace('&', '&', $value);
663 // if null then return actual token
664 if ($returnBlankToken && !$value) {
665 $value = "{contact.$token}";
669 $value = self
::tokenEscapeSmarty($value);
676 * Replace all the hook tokens in $str with information from
679 * @param string $str The string with tokens to be replaced
680 * @param array $contact Associative array of contact properties (including hook token values)
681 * @param boolean $html Replace tokens with HTML or plain text
683 * @return string The processed string
687 public static function &replaceHookTokens(
692 $escapeSmarty = FALSE
694 foreach ($categories as $key) {
696 self
::tokenRegex($key),
697 'self::getHookTokenReplacement(\'\\1\', $contact, $key, $html, $escapeSmarty)',
704 public static function getHookTokenReplacement(
709 $escapeSmarty = FALSE
711 $value = CRM_Utils_Array
::value("{$category}.{$token}", $contact);
713 if ($value && !$html) {
714 $value = str_replace('&', '&', $value);
718 $value = self
::tokenEscapeSmarty($value);
725 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
726 * for example {{token}} or \{token} will result in {token} in the final email
728 * this routine will remove the extra backslashes and braces
730 * @param $str ref to the string that will be scanned and modified
731 * @return void this function works directly on the string that is passed
735 public static function unescapeTokens(&$str) {
736 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
740 * Replace unsubscribe tokens
742 * @param string $str the string with tokens to be replaced
743 * @param object $domain The domain BAO
744 * @param array $groups The groups (if any) being unsubscribed
745 * @param boolean $html Replace tokens with html or plain text
746 * @param int $contact_id The contact ID
747 * @param string hash The security hash of the unsub event
749 * @return string The processed string
753 public static function &replaceUnsubscribeTokens(
761 if (self
::token_match('unsubscribe', 'group', $str)) {
762 if (!empty($groups)) {
763 $config = CRM_Core_Config
::singleton();
764 $base = CRM_Utils_System
::baseURL();
766 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
767 $dao = new CRM_Contact_DAO_Group();
769 while ($dao->fetch()) {
770 if (substr($dao->visibility
, 0, 6) == 'Public') {
771 $visibleGroups[] = $dao->id
;
774 $value = implode(', ', $groups);
775 self
::token_replace('unsubscribe', 'group', $value, $str);
782 * Replace resubscribe 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 resubscribed
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 resub event
791 * @return string The processed string
795 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
798 if (self
::token_match('resubscribe', 'group', $str)) {
799 if (!empty($groups)) {
800 $value = implode(', ', $groups);
801 self
::token_replace('resubscribe', 'group', $value, $str);
808 * Replace subscription-confirmation-request tokens
810 * @param string $str The string with tokens to be replaced
811 * @param string $group The name of the group being subscribed
812 * @param boolean $html Replace tokens with html or plain text
814 * @return string The processed string
818 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
819 if (self
::token_match('subscribe', 'group', $str)) {
820 self
::token_replace('subscribe', 'group', $group, $str);
822 if (self
::token_match('subscribe', 'url', $str)) {
823 self
::token_replace('subscribe', 'url', $url, $str);
829 * Replace subscription-invitation tokens
831 * @param string $str The string with tokens to be replaced
833 * @return string The processed string
837 public static function &replaceSubscribeInviteTokens($str) {
838 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
839 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
841 TRUE, NULL, TRUE, TRUE
843 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
846 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
847 foreach ($matches as $key => $value) {
848 $gid = substr($value, 21, -1);
849 $url = CRM_Utils_System
::url('civicrm/mailing/subscribe',
850 "reset=1&gid={$gid}",
851 TRUE, NULL, TRUE, TRUE
853 $url = str_replace('&', '&', $url);
854 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
858 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
859 foreach ($matches as $key => $value) {
860 $gid = substr($value, 18, -1);
861 $config = CRM_Core_Config
::singleton();
862 $domain = CRM_Core_BAO_MailSettings
::defaultDomain();
863 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
864 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
865 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
872 * Replace welcome/confirmation tokens
874 * @param string $str The string with tokens to be replaced
875 * @param string $group The name of the group being subscribed
876 * @param boolean $html Replace tokens with html or plain text
878 * @return string The processed string
882 public static function &replaceWelcomeTokens($str, $group, $html) {
883 if (self
::token_match('welcome', 'group', $str)) {
884 self
::token_replace('welcome', 'group', $group, $str);
890 * Find unprocessed tokens (call this last)
892 * @param string $str The string to search
894 * @return array Array of tokens that weren't replaced
898 public static function &unmatchedTokens(&$str) {
899 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
900 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
905 * Find and replace tokens for each component
907 * @param string $str The string to search
908 * @param array $contact Associative array of contact properties
909 * @param array $components A list of tokens that are known to exist in the email body
911 * @return string The processed string
915 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
916 if (!is_array($components) ||
empty($contact)) {
920 foreach ($components as $name => $tokens) {
921 if (!is_array($tokens) ||
empty($tokens)) {
925 foreach ($tokens as $token) {
926 if (self
::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
927 self
::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
929 elseif (!$returnEmptyToken) {
930 //replacing empty token
931 self
::token_replace($name, $token, "", $str, $escapeSmarty);
939 * Get array of string tokens
941 * @param $string the input string to parse for tokens
943 * @return $tokens array of tokens mentioned in field
947 static function getTokens($string) {
950 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
957 foreach ($matches[1] as $token) {
958 list($type, $name) = preg_split('/\./', $token, 2);
959 if ($name && $type) {
960 if (!isset($tokens[$type])) {
961 $tokens[$type] = array();
963 $tokens[$type][] = $name;
971 * gives required details of contacts in an indexed array format so we
972 * can iterate in a nice loop and do token evaluation
974 * @param array $contactIds of contacts
975 * @param array $returnProperties of required properties
976 * @param boolean $skipOnHold don't return on_hold contact info also.
977 * @param boolean $skipDeceased don't return deceased contact info.
978 * @param array $extraParams extra params
979 * @param array $tokens the list of tokens we've extracted from the content
980 * @param int $jobID the mailing list jobID - this is a legacy param
986 static function getTokenDetails($contactIDs,
987 $returnProperties = NULL,
989 $skipDeceased = TRUE,
995 if (empty($contactIDs)) {
996 // putting a fatal here so we can track if/when this happens
997 CRM_Core_Error
::fatal();
1001 foreach ($contactIDs as $key => $contactID) {
1003 CRM_Core_Form
::CB_PREFIX
. $contactID,
1009 if ($skipDeceased) {
1010 $params[] = array('is_deceased', '=', 0, 0, 0);
1015 $params[] = array('on_hold', '=', 0, 0, 0);
1019 $params = array_merge($params, $extraParams);
1022 // if return properties are not passed then get all return properties
1023 if (empty($returnProperties)) {
1024 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact
::exportableFields()),
1025 array('display_name', 'checksum', 'contact_id')
1027 foreach ($fields as $key => $val) {
1028 $returnProperties[$val] = 1;
1033 foreach ($returnProperties as $name => $dontCare) {
1034 $cfID = CRM_Core_BAO_CustomField
::getKeyID($name);
1040 //get the total number of contacts to fetch from database.
1041 $numberofContacts = count($contactIDs);
1042 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1044 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1046 $contactDetails = &$details[0];
1048 foreach ($contactIDs as $key => $contactID) {
1049 if (array_key_exists($contactID, $contactDetails)) {
1050 if (CRM_Utils_Array
::value('preferred_communication_method', $returnProperties) == 1
1051 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1053 $pcm = CRM_Core_PseudoConstant
::pcm();
1055 // communication Prefferance
1056 $contactPcm = explode(CRM_Core_DAO
::VALUE_SEPARATOR
,
1057 $contactDetails[$contactID]['preferred_communication_method']
1060 foreach ($contactPcm as $key => $val) {
1062 $result[$val] = $pcm[$val];
1065 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1068 foreach ($custom as $cfID) {
1069 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1070 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField
::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1076 //special case for greeting replacement
1078 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1079 if (CRM_Utils_Array
::value($val, $contactDetails[$contactID])) {
1080 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1086 // also call a hook and get token details
1087 CRM_Utils_Hook
::tokenValues($details[0],
1097 * gives required details of contribuion in an indexed array format so we
1098 * can iterate in a nice loop and do token evaluation
1100 * @param array $contributionId one contribution id
1101 * @param array $returnProperties of required properties
1102 * @param boolean $skipOnHold don't return on_hold contact info.
1103 * @param boolean $skipDeceased don't return deceased contact info.
1104 * @param array $extraParams extra params
1105 * @param array $tokens the list of tokens we've extracted from the content
1111 static function getContributionTokenDetails($contributionIDs,
1112 $returnProperties = NULL,
1113 $extraParams = NULL,
1117 if (empty($contributionIDs)) {
1118 // putting a fatal here so we can track if/when this happens
1119 CRM_Core_Error
::fatal();
1124 // no apiQuery helper yet, so do a loop and find contribution by id
1125 foreach ($contributionIDs as $contributionID) {
1127 $dao = new CRM_Contribute_DAO_Contribution();
1128 $dao->id
= $contributionID;
1130 if ($dao->find(TRUE)) {
1132 $details[$dao->id
] = array();
1133 CRM_Core_DAO
::storeValues($dao, $details[$dao->id
]);
1135 // do the necessary transformation
1136 if (CRM_Utils_Array
::value('payment_instrument_id', $details[$dao->id
])) {
1137 $piId = $details[$dao->id
]['payment_instrument_id'];
1138 $pis = CRM_Contribute_PseudoConstant
::paymentInstrument();
1139 $details[$dao->id
]['payment_instrument'] = $pis[$piId];
1141 if (CRM_Utils_Array
::value('campaign_id', $details[$dao->id
])) {
1142 $campaignId = $details[$dao->id
]['campaign_id'];
1143 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1144 $details[$dao->id
]['campaign'] = $campaigns[$campaignId];
1147 // TODO: call a hook to get token contribution details
1155 * replace greeting tokens exists in message/subject
1159 static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL) {
1161 if (!$contactDetails && !$contactId) {
1165 // check if there are any tokens
1166 $greetingTokens = self
::getTokens($tokenString);
1168 if (!empty($greetingTokens)) {
1169 // first use the existing contact object for token replacement
1170 if (!empty($contactDetails)) {
1171 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE);
1174 // check if there are any unevaluated tokens
1175 $greetingTokens = self
::getTokens($tokenString);
1177 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1178 // so retrieve it from database
1179 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1180 $greetingsReturnProperties = array_flip(CRM_Utils_Array
::value('contact', $greetingTokens));
1181 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1182 $contactParams = array('contact_id' => $contactId);
1184 $greetingDetails = self
::getTokenDetails($contactParams,
1185 $greetingsReturnProperties,
1191 // again replace tokens
1192 $tokenString = CRM_Utils_Token
::replaceContactTokens($tokenString,
1201 static function flattenTokens(&$tokens) {
1202 $flattenTokens = array();
1205 'html', 'text', 'subject') as $prop) {
1206 if (!isset($tokens[$prop])) {
1209 foreach ($tokens[$prop] as $type => $names) {
1210 if (!isset($flattenTokens[$type])) {
1211 $flattenTokens[$type] = array();
1213 foreach ($names as $name) {
1214 $flattenTokens[$type][$name] = 1;
1219 return $flattenTokens;
1223 * Replace all user tokens in $str
1225 * @param string $str The string with tokens to be replaced
1227 * @return string The processed string
1231 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1233 if (!$knownTokens ||
1234 !isset($knownTokens[$key])
1239 $str = preg_replace(self
::tokenRegex($key),
1240 'self::getUserTokenReplacement(\'\\1\',$escapeSmarty)', $str
1245 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1248 list($objectName, $objectValue) = explode('-', $token, 2);
1250 switch ($objectName) {
1252 $value = CRM_Core_Permission
::permissionEmails($objectValue);
1256 $value = CRM_Core_Permission
::roleEmails($objectValue);
1260 if ($escapeSmarty) {
1261 $value = self
::tokenEscapeSmarty($value);
1268 protected static function _buildContributionTokens() {
1269 $key = 'contribution';
1270 if (self
::$_tokens[$key] == NULL) {
1271 self
::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution
::exportableFields('All'),
1272 array('campaign', 'financial_type')
1277 public static function &replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1278 self
::_buildContributionTokens();
1280 // here we intersect with the list of pre-configured valid tokens
1281 // so that we remove anything we do not recognize
1282 // I hope to move this step out of here soon and
1283 // then we will just iterate on a list of tokens that are passed to us
1284 $key = 'contribution';
1285 if (!$knownTokens ||
!CRM_Utils_Array
::value($key, $knownTokens)) {
1289 $str = preg_replace(self
::tokenRegex($key),
1290 'self::getContributionTokenReplacement(\'\\1\', $contribution, $html, $escapeSmarty)',
1294 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1298 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1299 self
::_buildContributionTokens();
1302 case 'total_amount':
1305 case 'non_deductible_amount':
1306 $value = CRM_Utils_Money
::format(CRM_Utils_Array
::retrieveValueRecursive($contribution, $token));
1309 case 'receive_date':
1310 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1311 $value = CRM_Utils_Date
::customFormat($value, NULL, array('j', 'm', 'Y'));
1315 if (!in_array($token, self
::$_tokens['contribution'])) {
1316 $value = "{contribution.$token}";
1319 $value = CRM_Utils_Array
::retrieveValueRecursive($contribution, $token);
1325 if ($escapeSmarty) {
1326 $value = self
::tokenEscapeSmarty($value);
1331 function getPermissionEmails($permissionName) {}
1333 function getRoleEmails($roleName) {}