CRM-13296 deal with possibility minimum_fee is NULL
[civicrm-core.git] / CRM / Utils / Token.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id: $
33 *
34 */
35
36 /**
37 * Class to abstract token replacement
38 */
39 class CRM_Utils_Token {
40 static $_requiredTokens = NULL;
41
42 static $_tokens = array(
43 'action' => array(
44 'forward',
45 'optOut',
46 'optOutUrl',
47 'reply',
48 'unsubscribe',
49 'unsubscribeUrl',
50 'resubscribe',
51 'resubscribeUrl',
52 'subscribeUrl',
53 ),
54 'mailing' => array(
55 'id',
56 'name',
57 'group',
58 'subject',
59 'viewUrl',
60 'editUrl',
61 'scheduleUrl',
62 'approvalStatus',
63 'approvalNote',
64 'approveUrl',
65 'creator',
66 'creatorEmail',
67 ),
68 'user' => 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
72 'permission:',
73 'role:',
74 ),
75 // populate this dynamically
76 'contact' => NULL,
77 // populate this dynamically
78 'contribution' => NULL,
79 'domain' => array(
80 'name',
81 'phone',
82 'address',
83 'email',
84 'id',
85 'description',
86 ),
87 'subscribe' => array( 'group' ),
88 'unsubscribe' => array( 'group' ),
89 'resubscribe' => array( 'group' ),
90 'welcome' => array( 'group' ),
91 );
92
93 /**
94 * Check a string (mailing body) for required tokens.
95 *
96 * @param string $str The message
97 *
98 * @return true|array true if all required tokens are found,
99 * else an array of the missing tokens
100 * @access public
101 * @static
102 */
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' =>
108 array(
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."),
113 ),
114 );
115 }
116
117 $missing = array();
118 foreach (self::$_requiredTokens as $token => $value) {
119 if (!is_array($value)) {
120 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
121 $missing[$token] = $value;
122 }
123 }
124 else {
125 $present = FALSE;
126 $desc = NULL;
127 foreach ($value as $t => $d) {
128 $desc = $d;
129 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
130 $present = TRUE;
131 }
132 }
133 if (!$present) {
134 $missing[$token] = $desc;
135 }
136 }
137 }
138
139 if (empty($missing)) {
140 return TRUE;
141 }
142 return $missing;
143 }
144
145 /**
146 * Wrapper for token matching
147 *
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
151 *
152 * @return boolean Was there a match
153 * @access public
154 * @static
155 */
156 public static function token_match($type, $var, &$str) {
157 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
158 return preg_match("/(^|[^\{])$token/", $str);
159 }
160
161 /**
162 * Wrapper for token replacing
163 *
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
168 *
169 * @return string The processed string
170 * @access public
171 * @static
172 */
173 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
174 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
175 if (!$value) {
176 $value = '$3';
177 }
178 if ($escapeSmarty) {
179 $value = self::tokenEscapeSmarty($value);
180 }
181 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
182 return $str;
183 }
184
185 /**
186 * get< the regex for token replacement
187 *
188 * @param string $key a string indicating the the type of token to be used in the expression
189 *
190 * @return string regular expression sutiable for using in preg_replace
191 * @access private
192 * @static
193 */
194 private static function tokenRegex($token_type) {
195 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
196 }
197
198 /**
199 * escape the string so a malicious user cannot inject smarty code into the template
200 *
201 * @param string $string a string that needs to be escaped from smarty parsing
202 *
203 * @return string the escaped string
204 * @access private
205 * @static
206 */
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);
210 }
211
212 /**
213 /**
214 * Replace all the domain-level tokens in $str
215 *
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
219 *
220 * @return string The processed string
221 * @access public
222 * @static
223 */
224 public static function &replaceDomainTokens(
225 $str,
226 &$domain,
227 $html = FALSE,
228 $knownTokens = NULL,
229 $escapeSmarty = FALSE
230 ) {
231 $key = 'domain';
232 if (
233 !$knownTokens ||
234 !CRM_Utils_Array::value($key, $knownTokens)
235 ) {
236 return $str;
237 }
238
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);
243 },
244 $str
245 );
246 return $str;
247 }
248
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
253
254 $loc = &$domain->getLocationValues();
255
256 if (!in_array($token, self::$_tokens['domain'])) {
257 $value = "{domain.$token}";
258 }
259 elseif ($token == 'address') {
260 static $addressCache = array();
261
262 $cache_key = $html ? 'address-html' : 'address-text';
263 if (array_key_exists($cache_key, $addressCache)) {
264 return $addressCache[$cache_key];
265 }
266
267 $value = NULL;
268 /* Construct the address token */
269
270 if (CRM_Utils_Array::value($token, $loc)) {
271 if ($html) {
272 $value = $loc[$token][1]['display'];
273 $value = str_replace("\n", '<br />', $value);
274 }
275 else {
276 $value = $loc[$token][1]['display_text'];
277 }
278 $addressCache[$cache_key] = $value;
279 }
280 }
281 elseif ($token == 'name' || $token == 'id' || $token == 'description') {
282 $value = $domain->$token;
283 }
284 elseif ($token == 'phone' || $token == 'email') {
285 /* Construct the phone and email tokens */
286
287 $value = NULL;
288 if (CRM_Utils_Array::value($token, $loc)) {
289 foreach ($loc[$token] as $index => $entity) {
290 $value = $entity[$token];
291 break;
292 }
293 }
294 }
295
296 if ($escapeSmarty) {
297 $value = self::tokenEscapeSmarty($value);
298 }
299
300 return $value;
301 }
302
303 /**
304 * Replace all the org-level tokens in $str
305 *
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
309 *
310 * @return string The processed string
311 * @access public
312 * @static
313 */
314 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
315 self::$_tokens['org'] =
316 array_merge(
317 array_keys(CRM_Contact_BAO_Contact::importableFields('Organization')),
318 array('address', 'display_name', 'checksum', 'contact_id')
319 );
320
321 $cv = NULL;
322 foreach (self::$_tokens['org'] as $token) {
323 // print "Getting token value for $token<br/><br/>";
324 if ($token == '') {
325 continue;
326 }
327
328 /* If the string doesn't contain this token, skip it. */
329
330 if (!self::token_match('org', $token, $str)) {
331 continue;
332 }
333
334 /* Construct value from $token and $contact */
335
336 $value = NULL;
337
338 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($token)) {
339 // only generate cv if we need it
340 if ($cv === NULL) {
341 $cv = CRM_Core_BAO_CustomValue::getContactValues($org['contact_id']);
342 }
343 foreach ($cv as $cvFieldID => $value) {
344 if ($cvFieldID == $cfID) {
345 $value = CRM_Core_BAO_CustomOption::getOptionLabel($cfID, $value);
346 break;
347 }
348 }
349 }
350 elseif ($token == 'checksum') {
351 $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($org['contact_id']);
352 $value = "cs={$cs}";
353 }
354 elseif ($token == 'address') {
355 /* Build the location values array */
356
357 $loc = 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');
363
364 /* Construct the address token */
365
366 $value = CRM_Utils_Address::format($loc);
367 if ($html) {
368 $value = str_replace("\n", '<br />', $value);
369 }
370 }
371 else {
372 $value = CRM_Utils_Array::retrieveValueRecursive($org, $token);
373 }
374
375 self::token_replace('org', $token, $value, $str, $escapeSmarty);
376 }
377
378 return $str;
379 }
380
381 /**
382 * Replace all mailing tokens in $str
383 *
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
387 *
388 * @return string The processed sstring
389 * @access public
390 * @static
391 */
392 public static function &replaceMailingTokens(
393 $str,
394 &$mailing,
395 $html = FALSE,
396 $knownTokens = NULL,
397 $escapeSmarty = FALSE
398 ) {
399 $key = 'mailing';
400 if (!$knownTokens || !isset($knownTokens[$key])) {
401 return $str;
402 }
403
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);
408 },
409 $str
410 );
411 return $str;
412 }
413
414 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
415 $value = '';
416 switch ($token) {
417 // CRM-7663
418
419 case 'id':
420 $value = $mailing ? $mailing->id : 'undefined';
421 break;
422
423 case 'name':
424 $value = $mailing ? $mailing->name : 'Mailing Name';
425 break;
426
427 case 'group':
428 $groups = $mailing ? $mailing->getGroupNames() : array('Mailing Groups');
429 $value = implode(', ', $groups);
430 break;
431
432 case 'subject':
433 $value = $mailing->subject;
434 break;
435
436 case 'viewUrl':
437 $value = CRM_Utils_System::url('civicrm/mailing/view',
438 "reset=1&id={$mailing->id}",
439 TRUE, NULL, FALSE, TRUE
440 );
441 break;
442
443 case 'editUrl':
444 $value = CRM_Utils_System::url('civicrm/mailing/send',
445 "reset=1&mid={$mailing->id}&continue=true",
446 TRUE, NULL, FALSE, TRUE
447 );
448 break;
449
450 case 'scheduleUrl':
451 $value = CRM_Utils_System::url('civicrm/mailing/schedule',
452 "reset=1&mid={$mailing->id}",
453 TRUE, NULL, FALSE, TRUE
454 );
455 break;
456
457 case 'html':
458 $page = new CRM_Mailing_Page_View();
459 $value = $page->run($mailing->id, NULL, FALSE);
460 break;
461
462 case 'approvalStatus':
463 $value = CRM_Core_PseudoConstant::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id);
464 break;
465
466 case 'approvalNote':
467 $value = $mailing->approval_note;
468 break;
469
470 case 'approveUrl':
471 $value = CRM_Utils_System::url('civicrm/mailing/approve',
472 "reset=1&mid={$mailing->id}",
473 TRUE, NULL, FALSE, TRUE
474 );
475 break;
476
477 case 'creator':
478 $value = CRM_Contact_BAO_Contact::displayName($mailing->created_id);
479 break;
480
481 case 'creatorEmail':
482 $value = CRM_Contact_BAO_Contact::getPrimaryEmail($mailing->created_id);
483 break;
484
485 default:
486 $value = "{mailing.$token}";
487 break;
488 }
489
490 if ($escapeSmarty) {
491 $value = self::tokenEscapeSmarty($value);
492 }
493 return $value;
494 }
495
496 /**
497 * Replace all action tokens in $str
498 *
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
504 *
505 * @return string The processed string
506 * @access public
507 * @static
508 */
509 public static function &replaceActionTokens(
510 $str,
511 &$addresses,
512 &$urls,
513 $html = FALSE,
514 $knownTokens = NULL,
515 $escapeSmarty = FALSE
516 ) {
517 $key = 'action';
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)) {
523 return $str;
524 }
525
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);
530 },
531 $str
532 );
533 return $str;
534 }
535
536 public static function getActionTokenReplacement(
537 $token,
538 &$addresses,
539 &$urls,
540 $html = FALSE,
541 $escapeSmarty = FALSE
542 ) {
543 /* If the token is an email action, use it. Otherwise, find the
544 * appropriate URL */
545
546 if (!in_array($token, self::$_tokens['action'])) {
547 $value = "{action.$token}";
548 }
549 else {
550 $value = CRM_Utils_Array::value($token, $addresses);
551
552 if ($value == NULL) {
553 $value = CRM_Utils_Array::value($token, $urls);
554 }
555
556 if ($value && $html) {
557 //fix for CRM-2318
558 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
559 $value = "mailto:$value";
560 }
561 }
562 elseif ($value && !$html) {
563 $value = str_replace('&amp;', '&', $value);
564 }
565 }
566
567 if ($escapeSmarty) {
568 $value = self::tokenEscapeSmarty($value);
569 }
570 return $value;
571 }
572
573 /**
574 * Replace all the contact-level tokens in $str with information from
575 * $contact.
576 *
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
582 *
583 * @return string The processed string
584 * @access public
585 * @static
586 */
587 public static function &replaceContactTokens(
588 $str,
589 &$contact,
590 $html = FALSE,
591 $knownTokens = NULL,
592 $returnBlankToken = FALSE,
593 $escapeSmarty = FALSE
594 ) {
595 $key = 'contact';
596 if (self::$_tokens[$key] == NULL) {
597 /* This should come from UF */
598
599 self::$_tokens[$key] =
600 array_merge(
601 array_keys(CRM_Contact_BAO_Contact::exportableFields('All')),
602 array('checksum', 'contact_id')
603 );
604 }
605
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)) {
611 return $str;
612 }
613
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);
618 },
619 $str
620 );
621
622 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
623 return $str;
624 }
625
626 public static function getContactTokenReplacement(
627 $token,
628 &$contact,
629 $html = FALSE,
630 $returnBlankToken = FALSE,
631 $escapeSmarty = FALSE
632 ) {
633 if (self::$_tokens['contact'] == NULL) {
634 /* This should come from UF */
635
636 self::$_tokens['contact'] =
637 array_merge(
638 array_keys(CRM_Contact_BAO_Contact::exportableFields('All')),
639 array('checksum', 'contact_id')
640 );
641 }
642
643 /* Construct value from $token and $contact */
644
645 $value = NULL;
646
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
650
651 if (!in_array($token, self::$_tokens['contact'])) {
652 $value = "{contact.$token}";
653 }
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,
658 NULL,
659 NULL,
660 $hash
661 );
662 $value = "cs={$cs}";
663 }
664 else {
665 $value = CRM_Utils_Array::retrieveValueRecursive($contact, $token);
666
667 // note that incase of pseudoconstants we get array ( 0 => id, 1 => label )
668 if (is_array($value)) {
669 $value = $value[1];
670 }
671 }
672
673 if (!$html) {
674 $value = str_replace('&amp;', '&', $value);
675 }
676
677 // if null then return actual token
678 if ($returnBlankToken && !$value) {
679 $value = "{contact.$token}";
680 }
681
682 if ($escapeSmarty) {
683 $value = self::tokenEscapeSmarty($value);
684 }
685
686 return $value;
687 }
688
689 /**
690 * Replace all the hook tokens in $str with information from
691 * $contact.
692 *
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
696 *
697 * @return string The processed string
698 * @access public
699 * @static
700 */
701 public static function &replaceHookTokens(
702 $str,
703 &$contact,
704 &$categories,
705 $html = FALSE,
706 $escapeSmarty = FALSE
707 ) {
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);
713 },
714 $str
715 );
716 }
717 return $str;
718 }
719
720 /**
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
726 */
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");
733 }
734 return $tokenHtml;
735 }
736 public static function getHookTokenReplacement(
737 $token,
738 &$contact,
739 $category,
740 $html = FALSE,
741 $escapeSmarty = FALSE
742 ) {
743 $value = CRM_Utils_Array::value("{$category}.{$token}", $contact);
744
745 if ($value && !$html) {
746 $value = str_replace('&amp;', '&', $value);
747 }
748
749 if ($escapeSmarty) {
750 $value = self::tokenEscapeSmarty($value);
751 }
752
753 return $value;
754 }
755
756 /**
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
759 *
760 * this routine will remove the extra backslashes and braces
761 *
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
764 * @access public
765 * @static
766 */
767 public static function unescapeTokens(&$str) {
768 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
769 }
770
771 /**
772 * Replace unsubscribe tokens
773 *
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
780 *
781 * @return string The processed string
782 * @access public
783 * @static
784 */
785 public static function &replaceUnsubscribeTokens(
786 $str,
787 &$domain,
788 &$groups,
789 $html,
790 $contact_id,
791 $hash
792 ) {
793 if (self::token_match('unsubscribe', 'group', $str)) {
794 if (!empty($groups)) {
795 $config = CRM_Core_Config::singleton();
796 $base = CRM_Utils_System::baseURL();
797
798 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
799 $dao = new CRM_Contact_DAO_Group();
800 $dao->find();
801 while ($dao->fetch()) {
802 if (substr($dao->visibility, 0, 6) == 'Public') {
803 $visibleGroups[] = $dao->id;
804 }
805 }
806 $value = implode(', ', $groups);
807 self::token_replace('unsubscribe', 'group', $value, $str);
808 }
809 }
810 return $str;
811 }
812
813 /**
814 * Replace resubscribe tokens
815 *
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
822 *
823 * @return string The processed string
824 * @access public
825 * @static
826 */
827 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
828 $contact_id, $hash
829 ) {
830 if (self::token_match('resubscribe', 'group', $str)) {
831 if (!empty($groups)) {
832 $value = implode(', ', $groups);
833 self::token_replace('resubscribe', 'group', $value, $str);
834 }
835 }
836 return $str;
837 }
838
839 /**
840 * Replace subscription-confirmation-request tokens
841 *
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
845 *
846 * @return string The processed string
847 * @access public
848 * @static
849 */
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);
853 }
854 if (self::token_match('subscribe', 'url', $str)) {
855 self::token_replace('subscribe', 'url', $url, $str);
856 }
857 return $str;
858 }
859
860 /**
861 * Replace subscription-invitation tokens
862 *
863 * @param string $str The string with tokens to be replaced
864 *
865 * @return string The processed string
866 * @access public
867 * @static
868 */
869 public static function &replaceSubscribeInviteTokens($str) {
870 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
871 $url = CRM_Utils_System::url('civicrm/mailing/subscribe',
872 'reset=1',
873 TRUE, NULL, TRUE, TRUE
874 );
875 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
876 }
877
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
884 );
885 $url = str_replace('&amp;', '&', $url);
886 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
887 }
888 }
889
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);
898 }
899 }
900 return $str;
901 }
902
903 /**
904 * Replace welcome/confirmation tokens
905 *
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
909 *
910 * @return string The processed string
911 * @access public
912 * @static
913 */
914 public static function &replaceWelcomeTokens($str, $group, $html) {
915 if (self::token_match('welcome', 'group', $str)) {
916 self::token_replace('welcome', 'group', $group, $str);
917 }
918 return $str;
919 }
920
921 /**
922 * Find unprocessed tokens (call this last)
923 *
924 * @param string $str The string to search
925 *
926 * @return array Array of tokens that weren't replaced
927 * @access public
928 * @static
929 */
930 public static function &unmatchedTokens(&$str) {
931 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
932 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
933 return $match[1];
934 }
935
936 /**
937 * Find and replace tokens for each component
938 *
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
942 *
943 * @return string The processed string
944 * @access public
945 * @static
946 */
947 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
948 if (!is_array($components) || empty($contact)) {
949 return $str;
950 }
951
952 foreach ($components as $name => $tokens) {
953 if (!is_array($tokens) || empty($tokens)) {
954 continue;
955 }
956
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);
960 }
961 elseif (!$returnEmptyToken) {
962 //replacing empty token
963 self::token_replace($name, $token, "", $str, $escapeSmarty);
964 }
965 }
966 }
967 return $str;
968 }
969
970 /**
971 * Get array of string tokens
972 *
973 * @param $string the input string to parse for tokens
974 *
975 * @return $tokens array of tokens mentioned in field
976 * @access public
977 * @static
978 */
979 static function getTokens($string) {
980 $matches = array();
981 $tokens = array();
982 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
983 $string,
984 $matches,
985 PREG_PATTERN_ORDER
986 );
987
988 if ($matches[1]) {
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();
994 }
995 $tokens[$type][] = $name;
996 }
997 }
998 }
999 return $tokens;
1000 }
1001
1002 /**
1003 * gives required details of contacts in an indexed array format so we
1004 * can iterate in a nice loop and do token evaluation
1005 *
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
1013 *
1014 * @return array
1015 * @access public
1016 * @static
1017 */
1018 static function getTokenDetails($contactIDs,
1019 $returnProperties = NULL,
1020 $skipOnHold = TRUE,
1021 $skipDeceased = TRUE,
1022 $extraParams = NULL,
1023 $tokens = array(),
1024 $className = NULL,
1025 $jobID = NULL
1026 ) {
1027 if (empty($contactIDs)) {
1028 // putting a fatal here so we can track if/when this happens
1029 CRM_Core_Error::fatal();
1030 }
1031
1032 $params = array();
1033 foreach ($contactIDs as $key => $contactID) {
1034 $params[] = array(
1035 CRM_Core_Form::CB_PREFIX . $contactID,
1036 '=', 1, 0, 0,
1037 );
1038 }
1039
1040 // fix for CRM-2613
1041 if ($skipDeceased) {
1042 $params[] = array('is_deceased', '=', 0, 0, 0);
1043 }
1044
1045 //fix for CRM-3798
1046 if ($skipOnHold) {
1047 $params[] = array('on_hold', '=', 0, 0, 0);
1048 }
1049
1050 if ($extraParams) {
1051 $params = array_merge($params, $extraParams);
1052 }
1053
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')
1058 );
1059 foreach ($fields as $key => $val) {
1060 $returnProperties[$val] = 1;
1061 }
1062 }
1063
1064 $custom = array();
1065 foreach ($returnProperties as $name => $dontCare) {
1066 $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
1067 if ($cfID) {
1068 $custom[] = $cfID;
1069 }
1070 }
1071
1072 //get the total number of contacts to fetch from database.
1073 $numberofContacts = count($contactIDs);
1074 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1075
1076 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1077
1078 $contactDetails = &$details[0];
1079
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])
1084 ) {
1085 $pcm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1086
1087 // communication Prefferance
1088 $contactPcm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1089 $contactDetails[$contactID]['preferred_communication_method']
1090 );
1091 $result = array();
1092 foreach ($contactPcm as $key => $val) {
1093 if ($val) {
1094 $result[$val] = $pcm[$val];
1095 }
1096 }
1097 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1098 }
1099
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}"],
1103 $cfID, $details[1]
1104 );
1105 }
1106 }
1107
1108 //special case for greeting replacement
1109 foreach (array(
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"];
1113 }
1114 }
1115 }
1116 }
1117
1118 // also call a hook and get token details
1119 CRM_Utils_Hook::tokenValues($details[0],
1120 $contactIDs,
1121 $jobID,
1122 $tokens,
1123 $className
1124 );
1125 return $details;
1126 }
1127
1128 /**
1129 * gives required details of contribuion in an indexed array format so we
1130 * can iterate in a nice loop and do token evaluation
1131 *
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
1138 *
1139 * @return array
1140 * @access public
1141 * @static
1142 */
1143 static function getContributionTokenDetails($contributionIDs,
1144 $returnProperties = NULL,
1145 $extraParams = NULL,
1146 $tokens = array(),
1147 $className = NULL
1148 ) {
1149 if (empty($contributionIDs)) {
1150 // putting a fatal here so we can track if/when this happens
1151 CRM_Core_Error::fatal();
1152 }
1153
1154 $details = array();
1155
1156 // no apiQuery helper yet, so do a loop and find contribution by id
1157 foreach ($contributionIDs as $contributionID) {
1158
1159 $dao = new CRM_Contribute_DAO_Contribution();
1160 $dao->id = $contributionID;
1161
1162 if ($dao->find(TRUE)) {
1163
1164 $details[$dao->id] = array();
1165 CRM_Core_DAO::storeValues($dao, $details[$dao->id]);
1166
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];
1172 }
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];
1177 }
1178
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];
1183 }
1184
1185 // TODO: call a hook to get token contribution details
1186 }
1187 }
1188
1189 return $details;
1190 }
1191
1192 /**
1193 * Get Membership Token Details
1194 * @param array $membershipIDs array of membership IDS
1195 */
1196 static function getMembershipTokenDetails($membershipIDs) {
1197 $memberships = civicrm_api3('membership', 'get', array('membership_id' => array('IN' => (array) $membershipIDs)));
1198 return $memberships['values'];
1199 }
1200 /**
1201 * replace greeting tokens exists in message/subject
1202 *
1203 * @access public
1204 */
1205 static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL) {
1206
1207 if (!$contactDetails && !$contactId) {
1208 return;
1209 }
1210
1211 // check if there are any tokens
1212 $greetingTokens = self::getTokens($tokenString);
1213
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]);
1220 }
1221 $tokenString = CRM_Utils_Token::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE);
1222 }
1223
1224 // check if there are any unevaluated tokens
1225 $greetingTokens = self::getTokens($tokenString);
1226
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);
1233
1234 $greetingDetails = self::getTokenDetails($contactParams,
1235 $greetingsReturnProperties,
1236 FALSE, FALSE, NULL,
1237 $greetingTokens,
1238 $className
1239 );
1240
1241 // again replace tokens
1242 $tokenString = CRM_Utils_Token::replaceContactTokens($tokenString,
1243 $greetingDetails,
1244 TRUE,
1245 $greetingTokens
1246 );
1247 }
1248 }
1249 }
1250
1251 static function flattenTokens(&$tokens) {
1252 $flattenTokens = array();
1253
1254 foreach (array(
1255 'html', 'text', 'subject') as $prop) {
1256 if (!isset($tokens[$prop])) {
1257 continue;
1258 }
1259 foreach ($tokens[$prop] as $type => $names) {
1260 if (!isset($flattenTokens[$type])) {
1261 $flattenTokens[$type] = array();
1262 }
1263 foreach ($names as $name) {
1264 $flattenTokens[$type][$name] = 1;
1265 }
1266 }
1267 }
1268
1269 return $flattenTokens;
1270 }
1271
1272 /**
1273 * Replace all user tokens in $str
1274 *
1275 * @param string $str The string with tokens to be replaced
1276 *
1277 * @return string The processed string
1278 * @access public
1279 * @static
1280 */
1281 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1282 $key = 'user';
1283 if (!$knownTokens ||
1284 !isset($knownTokens[$key])
1285 ) {
1286 return $str;
1287 }
1288
1289 $str = preg_replace_callback(
1290 self::tokenRegex($key),
1291 function ($matches) use($escapeSmarty) {
1292 return CRM_Utils_Token::getUserTokenReplacement($matches[1], $escapeSmarty);
1293 },
1294 $str
1295 );
1296 return $str;
1297 }
1298
1299 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1300 $value = '';
1301
1302 list($objectName, $objectValue) = explode('-', $token, 2);
1303
1304 switch ($objectName) {
1305 case 'permission':
1306 $value = CRM_Core_Permission::permissionEmails($objectValue);
1307 break;
1308
1309 case 'role':
1310 $value = CRM_Core_Permission::roleEmails($objectValue);
1311 break;
1312 }
1313
1314 if ($escapeSmarty) {
1315 $value = self::tokenEscapeSmarty($value);
1316 }
1317
1318 return $value;
1319 }
1320
1321
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')
1327 ));
1328 }
1329 }
1330
1331 /**
1332 * store membership tokens on the static _tokens array
1333 */
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);
1341 }
1342 self::$_tokens[$key] = $membershipTokens;
1343 }
1344 }
1345
1346 /**
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
1354 */
1355 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1356 if (!$knownTokens || !CRM_Utils_Array::value($entity, $knownTokens)) {
1357 return $str;
1358 }
1359
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);
1365 }
1366 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1367 return $str;
1368 }
1369
1370 public static function &replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1371 self::_buildContributionTokens();
1372
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)) {
1379 return $str;
1380 }
1381
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);
1386 },
1387 $str
1388 );
1389
1390 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1391 return $str;
1392 }
1393
1394 /**
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
1401 */
1402 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1403 $entity = 'membership';
1404 self::_buildMembershipTokens();
1405 switch ($token) {
1406 case 'type':
1407 $value = $membership['membership_name'];
1408 break;
1409 case 'status':
1410 $statuses = CRM_Member_BAO_Membership::buildOptions('status_id');
1411 $value = $statuses[$membership['status_id']];
1412 break;
1413 case 'fee':
1414 try{
1415 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1416 }
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)
1420 $value = 0;
1421 }
1422 break;
1423 default:
1424 if (in_array($token, self::$_tokens[$entity])) {
1425 $value = $membership[$token];
1426 }
1427 else {
1428 //ie unchanged
1429 $value = "{$entity}.{$token}";
1430 }
1431 break;
1432 }
1433
1434 if ($escapeSmarty) {
1435 $value = self::tokenEscapeSmarty($value);
1436 }
1437 return $value;
1438 }
1439
1440 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1441 self::_buildContributionTokens();
1442
1443 switch ($token) {
1444 case 'total_amount':
1445 case 'net_amount':
1446 case 'fee_amount':
1447 case 'non_deductible_amount':
1448 $value = CRM_Utils_Money::format(CRM_Utils_Array::retrieveValueRecursive($contribution, $token));
1449 break;
1450
1451 case 'receive_date':
1452 $value = CRM_Utils_Array::retrieveValueRecursive($contribution, $token);
1453 $value = CRM_Utils_Date::customFormat($value, NULL, array('j', 'm', 'Y'));
1454 break;
1455
1456 default:
1457 if (!in_array($token, self::$_tokens['contribution'])) {
1458 $value = "{contribution.$token}";
1459 }
1460 else {
1461 $value = CRM_Utils_Array::retrieveValueRecursive($contribution, $token);
1462 }
1463 break;
1464 }
1465
1466
1467 if ($escapeSmarty) {
1468 $value = self::tokenEscapeSmarty($value);
1469 }
1470 return $value;
1471 }
1472
1473 function getPermissionEmails($permissionName) {}
1474
1475 function getRoleEmails($roleName) {}
1476 }