Merge pull request #1433 from totten/master-validate-messages
[civicrm-core.git] / CRM / Utils / Token.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.3 |
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 */
39class 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',
e3470b79 84 'id',
85 'description',
6a488035
TO
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."),
d72434db 107 'action.optOutUrl or action.unsubscribeUrl' =>
6a488035
TO
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."),
d72434db 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."),
6a488035
TO
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('}');
93f087c7 158 return preg_match("/(^|[^\{])$token/", $str);
6a488035
TO
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) {
8bab0eb0 195 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
6a488035
TO
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 */
21bb6c7b
DL
224 public static function &replaceDomainTokens(
225 $str,
226 &$domain,
227 $html = FALSE,
228 $knownTokens = NULL,
229 $escapeSmarty = FALSE
230 ) {
6a488035 231 $key = 'domain';
21bb6c7b
DL
232 if (
233 !$knownTokens ||
6a488035
TO
234 !CRM_Utils_Array::value($key, $knownTokens)
235 ) {
236 return $str;
237 }
238
8bab0eb0 239 $str = preg_replace_callback(
21bb6c7b 240 self::tokenRegex($key),
8bab0eb0
DL
241 function ($matches) use(&$domain, $html, $escapeSmarty) {
242 return CRM_Utils_Token::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
243 },
21bb6c7b
DL
244 $str
245 );
6a488035
TO
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 }
e3470b79 281 elseif ($token == 'name' || $token == 'id' || $token == 'description') {
6a488035
TO
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) {
21bb6c7b
DL
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 );
6a488035
TO
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 */
21bb6c7b
DL
392 public static function &replaceMailingTokens(
393 $str,
394 &$mailing,
395 $html = FALSE,
396 $knownTokens = NULL,
397 $escapeSmarty = FALSE
398 ) {
6a488035
TO
399 $key = 'mailing';
400 if (!$knownTokens || !isset($knownTokens[$key])) {
401 return $str;
402 }
403
8bab0eb0 404 $str = preg_replace_callback(
6a488035 405 self::tokenRegex($key),
8bab0eb0
DL
406 function ($matches) use(&$mailing, $escapeSmarty) {
407 return CRM_Utils_Token::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
408 },
409 $str
6a488035
TO
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':
a8c23526 463 $value = CRM_Core_PseudoConstant::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id);
6a488035
TO
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
8bab0eb0
DL
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 },
6a488035
TO
531 $str
532 );
533 return $str;
534 }
535
21bb6c7b
DL
536 public static function getActionTokenReplacement(
537 $token,
538 &$addresses,
539 &$urls,
540 $html = FALSE,
541 $escapeSmarty = FALSE
542 ) {
6a488035
TO
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 */
21bb6c7b
DL
587 public static function &replaceContactTokens(
588 $str,
589 &$contact,
590 $html = FALSE,
591 $knownTokens = NULL,
592 $returnBlankToken = FALSE,
593 $escapeSmarty = FALSE
6a488035
TO
594 ) {
595 $key = 'contact';
596 if (self::$_tokens[$key] == NULL) {
597 /* This should come from UF */
598
21bb6c7b
DL
599 self::$_tokens[$key] =
600 array_merge(
601 array_keys(CRM_Contact_BAO_Contact::exportableFields('All')),
602 array('checksum', 'contact_id')
603 );
6a488035
TO
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
8bab0eb0 614 $str = preg_replace_callback(
21bb6c7b 615 self::tokenRegex($key),
6d3c1eb9
OB
616 function ($matches) use(&$contact, $html, $returnBlankToken, $escapeSmarty) {
617 return CRM_Utils_Token::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
8bab0eb0 618 },
6a488035
TO
619 $str
620 );
621
622 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
623 return $str;
624 }
625
21bb6c7b
DL
626 public static function getContactTokenReplacement(
627 $token,
628 &$contact,
629 $html = FALSE,
630 $returnBlankToken = FALSE,
631 $escapeSmarty = FALSE
6a488035
TO
632 ) {
633 if (self::$_tokens['contact'] == NULL) {
634 /* This should come from UF */
635
21bb6c7b
DL
636 self::$_tokens['contact'] =
637 array_merge(
638 array_keys(CRM_Contact_BAO_Contact::exportableFields('All')),
639 array('checksum', 'contact_id')
640 );
6a488035
TO
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
668 if (!$html) {
669 $value = str_replace('&amp;', '&', $value);
670 }
671
672 // if null then return actual token
673 if ($returnBlankToken && !$value) {
674 $value = "{contact.$token}";
675 }
676
677 if ($escapeSmarty) {
678 $value = self::tokenEscapeSmarty($value);
679 }
680
681 return $value;
682 }
683
684 /**
685 * Replace all the hook tokens in $str with information from
686 * $contact.
687 *
688 * @param string $str The string with tokens to be replaced
689 * @param array $contact Associative array of contact properties (including hook token values)
690 * @param boolean $html Replace tokens with HTML or plain text
691 *
692 * @return string The processed string
693 * @access public
694 * @static
695 */
21bb6c7b
DL
696 public static function &replaceHookTokens(
697 $str,
698 &$contact,
699 &$categories,
700 $html = FALSE,
701 $escapeSmarty = FALSE
702 ) {
6a488035 703 foreach ($categories as $key) {
8bab0eb0 704 $str = preg_replace_callback(
21bb6c7b 705 self::tokenRegex($key),
8bab0eb0
DL
706 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
707 return CRM_Utils_Token::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
708 },
6a488035
TO
709 $str
710 );
711 }
712 return $str;
713 }
714
21bb6c7b
DL
715 public static function getHookTokenReplacement(
716 $token,
717 &$contact,
718 $category,
719 $html = FALSE,
720 $escapeSmarty = FALSE
721 ) {
6a488035
TO
722 $value = CRM_Utils_Array::value("{$category}.{$token}", $contact);
723
21bb6c7b 724 if ($value && !$html) {
6a488035
TO
725 $value = str_replace('&amp;', '&', $value);
726 }
727
728 if ($escapeSmarty) {
729 $value = self::tokenEscapeSmarty($value);
730 }
731
732 return $value;
733 }
734
735 /**
736 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
737 * for example {{token}} or \{token} will result in {token} in the final email
738 *
739 * this routine will remove the extra backslashes and braces
740 *
741 * @param $str ref to the string that will be scanned and modified
742 * @return void this function works directly on the string that is passed
743 * @access public
744 * @static
745 */
746 public static function unescapeTokens(&$str) {
747 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
748 }
749
750 /**
751 * Replace unsubscribe tokens
752 *
753 * @param string $str the string with tokens to be replaced
754 * @param object $domain The domain BAO
755 * @param array $groups The groups (if any) being unsubscribed
756 * @param boolean $html Replace tokens with html or plain text
757 * @param int $contact_id The contact ID
758 * @param string hash The security hash of the unsub event
759 *
760 * @return string The processed string
761 * @access public
762 * @static
763 */
764 public static function &replaceUnsubscribeTokens(
765 $str,
766 &$domain,
767 &$groups,
768 $html,
769 $contact_id,
770 $hash
771 ) {
772 if (self::token_match('unsubscribe', 'group', $str)) {
773 if (!empty($groups)) {
774 $config = CRM_Core_Config::singleton();
775 $base = CRM_Utils_System::baseURL();
776
777 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
778 $dao = new CRM_Contact_DAO_Group();
779 $dao->find();
780 while ($dao->fetch()) {
781 if (substr($dao->visibility, 0, 6) == 'Public') {
782 $visibleGroups[] = $dao->id;
783 }
784 }
785 $value = implode(', ', $groups);
786 self::token_replace('unsubscribe', 'group', $value, $str);
787 }
788 }
789 return $str;
790 }
791
792 /**
793 * Replace resubscribe tokens
794 *
795 * @param string $str the string with tokens to be replaced
796 * @param object $domain The domain BAO
797 * @param array $groups The groups (if any) being resubscribed
798 * @param boolean $html Replace tokens with html or plain text
799 * @param int $contact_id The contact ID
800 * @param string hash The security hash of the resub event
801 *
802 * @return string The processed string
803 * @access public
804 * @static
805 */
806 public static function &replaceResubscribeTokens($str, &$domain, &$groups, $html,
807 $contact_id, $hash
808 ) {
809 if (self::token_match('resubscribe', 'group', $str)) {
810 if (!empty($groups)) {
811 $value = implode(', ', $groups);
812 self::token_replace('resubscribe', 'group', $value, $str);
813 }
814 }
815 return $str;
816 }
817
818 /**
819 * Replace subscription-confirmation-request tokens
820 *
821 * @param string $str The string with tokens to be replaced
822 * @param string $group The name of the group being subscribed
823 * @param boolean $html Replace tokens with html or plain text
824 *
825 * @return string The processed string
826 * @access public
827 * @static
828 */
829 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
830 if (self::token_match('subscribe', 'group', $str)) {
831 self::token_replace('subscribe', 'group', $group, $str);
832 }
833 if (self::token_match('subscribe', 'url', $str)) {
834 self::token_replace('subscribe', 'url', $url, $str);
835 }
836 return $str;
837 }
838
839 /**
840 * Replace subscription-invitation tokens
841 *
842 * @param string $str The string with tokens to be replaced
843 *
844 * @return string The processed string
845 * @access public
846 * @static
847 */
848 public static function &replaceSubscribeInviteTokens($str) {
849 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
850 $url = CRM_Utils_System::url('civicrm/mailing/subscribe',
851 'reset=1',
852 TRUE, NULL, TRUE, TRUE
853 );
854 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
855 }
856
857 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
858 foreach ($matches as $key => $value) {
859 $gid = substr($value, 21, -1);
860 $url = CRM_Utils_System::url('civicrm/mailing/subscribe',
861 "reset=1&gid={$gid}",
862 TRUE, NULL, TRUE, TRUE
863 );
864 $url = str_replace('&amp;', '&', $url);
865 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
866 }
867 }
868
869 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
870 foreach ($matches as $key => $value) {
871 $gid = substr($value, 18, -1);
872 $config = CRM_Core_Config::singleton();
873 $domain = CRM_Core_BAO_MailSettings::defaultDomain();
874 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
875 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
876 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
877 }
878 }
879 return $str;
880 }
881
882 /**
883 * Replace welcome/confirmation tokens
884 *
885 * @param string $str The string with tokens to be replaced
886 * @param string $group The name of the group being subscribed
887 * @param boolean $html Replace tokens with html or plain text
888 *
889 * @return string The processed string
890 * @access public
891 * @static
892 */
893 public static function &replaceWelcomeTokens($str, $group, $html) {
894 if (self::token_match('welcome', 'group', $str)) {
895 self::token_replace('welcome', 'group', $group, $str);
896 }
897 return $str;
898 }
899
900 /**
901 * Find unprocessed tokens (call this last)
902 *
903 * @param string $str The string to search
904 *
905 * @return array Array of tokens that weren't replaced
906 * @access public
907 * @static
908 */
909 public static function &unmatchedTokens(&$str) {
910 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
911 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
912 return $match[1];
913 }
914
915 /**
916 * Find and replace tokens for each component
917 *
918 * @param string $str The string to search
919 * @param array $contact Associative array of contact properties
920 * @param array $components A list of tokens that are known to exist in the email body
921 *
922 * @return string The processed string
923 * @access public
924 * @static
925 */
926 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
927 if (!is_array($components) || empty($contact)) {
928 return $str;
929 }
930
931 foreach ($components as $name => $tokens) {
932 if (!is_array($tokens) || empty($tokens)) {
933 continue;
934 }
935
936 foreach ($tokens as $token) {
937 if (self::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
938 self::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
939 }
940 elseif (!$returnEmptyToken) {
941 //replacing empty token
942 self::token_replace($name, $token, "", $str, $escapeSmarty);
943 }
944 }
945 }
946 return $str;
947 }
948
949 /**
950 * Get array of string tokens
951 *
952 * @param $string the input string to parse for tokens
953 *
954 * @return $tokens array of tokens mentioned in field
955 * @access public
956 * @static
957 */
958 static function getTokens($string) {
959 $matches = array();
960 $tokens = array();
961 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
962 $string,
963 $matches,
964 PREG_PATTERN_ORDER
965 );
966
967 if ($matches[1]) {
968 foreach ($matches[1] as $token) {
969 list($type, $name) = preg_split('/\./', $token, 2);
970 if ($name && $type) {
971 if (!isset($tokens[$type])) {
972 $tokens[$type] = array();
973 }
974 $tokens[$type][] = $name;
975 }
976 }
977 }
978 return $tokens;
979 }
980
981 /**
982 * gives required details of contacts in an indexed array format so we
983 * can iterate in a nice loop and do token evaluation
984 *
985 * @param array $contactIds of contacts
986 * @param array $returnProperties of required properties
987 * @param boolean $skipOnHold don't return on_hold contact info also.
988 * @param boolean $skipDeceased don't return deceased contact info.
989 * @param array $extraParams extra params
990 * @param array $tokens the list of tokens we've extracted from the content
991 * @param int $jobID the mailing list jobID - this is a legacy param
992 *
993 * @return array
994 * @access public
995 * @static
996 */
997 static function getTokenDetails($contactIDs,
998 $returnProperties = NULL,
999 $skipOnHold = TRUE,
1000 $skipDeceased = TRUE,
1001 $extraParams = NULL,
1002 $tokens = array(),
1003 $className = NULL,
1004 $jobID = NULL
1005 ) {
1006 if (empty($contactIDs)) {
1007 // putting a fatal here so we can track if/when this happens
1008 CRM_Core_Error::fatal();
1009 }
1010
1011 $params = array();
1012 foreach ($contactIDs as $key => $contactID) {
1013 $params[] = array(
1014 CRM_Core_Form::CB_PREFIX . $contactID,
1015 '=', 1, 0, 0,
1016 );
1017 }
1018
1019 // fix for CRM-2613
1020 if ($skipDeceased) {
1021 $params[] = array('is_deceased', '=', 0, 0, 0);
1022 }
1023
1024 //fix for CRM-3798
1025 if ($skipOnHold) {
1026 $params[] = array('on_hold', '=', 0, 0, 0);
1027 }
1028
1029 if ($extraParams) {
1030 $params = array_merge($params, $extraParams);
1031 }
1032
1033 // if return properties are not passed then get all return properties
1034 if (empty($returnProperties)) {
1035 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact::exportableFields()),
1036 array('display_name', 'checksum', 'contact_id')
1037 );
1038 foreach ($fields as $key => $val) {
1039 $returnProperties[$val] = 1;
1040 }
1041 }
1042
1043 $custom = array();
1044 foreach ($returnProperties as $name => $dontCare) {
1045 $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
1046 if ($cfID) {
1047 $custom[] = $cfID;
1048 }
1049 }
1050
1051 //get the total number of contacts to fetch from database.
1052 $numberofContacts = count($contactIDs);
1053 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1054
1055 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1056
1057 $contactDetails = &$details[0];
1058
1059 foreach ($contactIDs as $key => $contactID) {
1060 if (array_key_exists($contactID, $contactDetails)) {
1061 if (CRM_Utils_Array::value('preferred_communication_method', $returnProperties) == 1
1062 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1063 ) {
e7e657f0 1064 $pcm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
6a488035
TO
1065
1066 // communication Prefferance
1067 $contactPcm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1068 $contactDetails[$contactID]['preferred_communication_method']
1069 );
1070 $result = array();
1071 foreach ($contactPcm as $key => $val) {
1072 if ($val) {
1073 $result[$val] = $pcm[$val];
1074 }
1075 }
1076 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1077 }
1078
1079 foreach ($custom as $cfID) {
1080 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1081 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1082 $cfID, $details[1]
1083 );
1084 }
1085 }
1086
1087 //special case for greeting replacement
1088 foreach (array(
1089 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1090 if (CRM_Utils_Array::value($val, $contactDetails[$contactID])) {
1091 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1092 }
1093 }
1094 }
1095 }
1096
1097 // also call a hook and get token details
1098 CRM_Utils_Hook::tokenValues($details[0],
1099 $contactIDs,
1100 $jobID,
1101 $tokens,
1102 $className
1103 );
1104 return $details;
1105 }
1106
1107 /**
1108 * gives required details of contribuion in an indexed array format so we
1109 * can iterate in a nice loop and do token evaluation
1110 *
1111 * @param array $contributionId one contribution id
1112 * @param array $returnProperties of required properties
1113 * @param boolean $skipOnHold don't return on_hold contact info.
1114 * @param boolean $skipDeceased don't return deceased contact info.
1115 * @param array $extraParams extra params
1116 * @param array $tokens the list of tokens we've extracted from the content
1117 *
1118 * @return array
1119 * @access public
1120 * @static
1121 */
1122 static function getContributionTokenDetails($contributionIDs,
1123 $returnProperties = NULL,
1124 $extraParams = NULL,
1125 $tokens = array(),
1126 $className = NULL
1127 ) {
1128 if (empty($contributionIDs)) {
1129 // putting a fatal here so we can track if/when this happens
1130 CRM_Core_Error::fatal();
1131 }
1132
1133 $details = array();
1134
1135 // no apiQuery helper yet, so do a loop and find contribution by id
1136 foreach ($contributionIDs as $contributionID) {
1137
1138 $dao = new CRM_Contribute_DAO_Contribution();
1139 $dao->id = $contributionID;
1140
1141 if ($dao->find(TRUE)) {
1142
1143 $details[$dao->id] = array();
1144 CRM_Core_DAO::storeValues($dao, $details[$dao->id]);
1145
1146 // do the necessary transformation
1147 if (CRM_Utils_Array::value('payment_instrument_id', $details[$dao->id])) {
1148 $piId = $details[$dao->id]['payment_instrument_id'];
1149 $pis = CRM_Contribute_PseudoConstant::paymentInstrument();
1150 $details[$dao->id]['payment_instrument'] = $pis[$piId];
1151 }
1152 if (CRM_Utils_Array::value('campaign_id', $details[$dao->id])) {
1153 $campaignId = $details[$dao->id]['campaign_id'];
1154 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1155 $details[$dao->id]['campaign'] = $campaigns[$campaignId];
1156 }
1157
1158 // TODO: call a hook to get token contribution details
1159 }
1160 }
1161
1162 return $details;
1163 }
1164
1165 /**
1166 * replace greeting tokens exists in message/subject
1167 *
1168 * @access public
1169 */
1170 static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL) {
1171
1172 if (!$contactDetails && !$contactId) {
1173 return;
1174 }
1175
1176 // check if there are any tokens
1177 $greetingTokens = self::getTokens($tokenString);
1178
1179 if (!empty($greetingTokens)) {
1180 // first use the existing contact object for token replacement
1181 if (!empty($contactDetails)) {
1182 $tokenString = CRM_Utils_Token::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE);
1183 }
1184
1185 // check if there are any unevaluated tokens
1186 $greetingTokens = self::getTokens($tokenString);
1187
1188 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1189 // so retrieve it from database
1190 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1191 $greetingsReturnProperties = array_flip(CRM_Utils_Array::value('contact', $greetingTokens));
1192 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1193 $contactParams = array('contact_id' => $contactId);
1194
1195 $greetingDetails = self::getTokenDetails($contactParams,
1196 $greetingsReturnProperties,
1197 FALSE, FALSE, NULL,
1198 $greetingTokens,
1199 $className
1200 );
1201
1202 // again replace tokens
1203 $tokenString = CRM_Utils_Token::replaceContactTokens($tokenString,
1204 $greetingDetails,
1205 TRUE,
1206 $greetingTokens
1207 );
1208 }
1209 }
1210 }
1211
1212 static function flattenTokens(&$tokens) {
1213 $flattenTokens = array();
1214
1215 foreach (array(
1216 'html', 'text', 'subject') as $prop) {
1217 if (!isset($tokens[$prop])) {
1218 continue;
1219 }
1220 foreach ($tokens[$prop] as $type => $names) {
1221 if (!isset($flattenTokens[$type])) {
1222 $flattenTokens[$type] = array();
1223 }
1224 foreach ($names as $name) {
1225 $flattenTokens[$type][$name] = 1;
1226 }
1227 }
1228 }
1229
1230 return $flattenTokens;
1231 }
1232
1233 /**
1234 * Replace all user tokens in $str
1235 *
1236 * @param string $str The string with tokens to be replaced
1237 *
1238 * @return string The processed string
1239 * @access public
1240 * @static
1241 */
1242 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1243 $key = 'user';
1244 if (!$knownTokens ||
1245 !isset($knownTokens[$key])
1246 ) {
1247 return $str;
1248 }
1249
8bab0eb0
DL
1250 $str = preg_replace_callback(
1251 self::tokenRegex($key),
1252 function ($matches) use($escapeSmarty) {
1253 return CRM_Utils_Token::getUserTokenReplacement($matches[1], $escapeSmarty);
1254 },
1255 $str
6a488035
TO
1256 );
1257 return $str;
1258 }
1259
1260 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1261 $value = '';
1262
1263 list($objectName, $objectValue) = explode('-', $token, 2);
1264
1265 switch ($objectName) {
1266 case 'permission':
1267 $value = CRM_Core_Permission::permissionEmails($objectValue);
1268 break;
1269
1270 case 'role':
1271 $value = CRM_Core_Permission::roleEmails($objectValue);
1272 break;
1273 }
1274
1275 if ($escapeSmarty) {
1276 $value = self::tokenEscapeSmarty($value);
1277 }
1278
1279 return $value;
1280 }
1281
1282
1283 protected static function _buildContributionTokens() {
1284 $key = 'contribution';
1285 if (self::$_tokens[$key] == NULL) {
1286 self::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution::exportableFields('All'),
1287 array('campaign', 'financial_type')
1288 ));
1289 }
1290 }
1291
1292 public static function &replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1293 self::_buildContributionTokens();
1294
1295 // here we intersect with the list of pre-configured valid tokens
1296 // so that we remove anything we do not recognize
1297 // I hope to move this step out of here soon and
1298 // then we will just iterate on a list of tokens that are passed to us
1299 $key = 'contribution';
1300 if (!$knownTokens || !CRM_Utils_Array::value($key, $knownTokens)) {
1301 return $str;
1302 }
1303
8bab0eb0
DL
1304 $str = preg_replace_callback(
1305 self::tokenRegex($key),
1306 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1307 return CRM_Utils_Token::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1308 },
6a488035
TO
1309 $str
1310 );
1311
1312 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1313 return $str;
1314 }
1315
1316 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1317 self::_buildContributionTokens();
1318
1319 switch ($token) {
1320 case 'total_amount':
1321 case 'net_amount':
1322 case 'fee_amount':
1323 case 'non_deductible_amount':
1324 $value = CRM_Utils_Money::format(CRM_Utils_Array::retrieveValueRecursive($contribution, $token));
1325 break;
1326
1327 case 'receive_date':
1328 $value = CRM_Utils_Array::retrieveValueRecursive($contribution, $token);
1329 $value = CRM_Utils_Date::customFormat($value, NULL, array('j', 'm', 'Y'));
1330 break;
1331
1332 default:
1333 if (!in_array($token, self::$_tokens['contribution'])) {
1334 $value = "{contribution.$token}";
1335 }
1336 else {
1337 $value = CRM_Utils_Array::retrieveValueRecursive($contribution, $token);
1338 }
1339 break;
1340 }
1341
1342
1343 if ($escapeSmarty) {
1344 $value = self::tokenEscapeSmarty($value);
1345 }
1346 return $value;
1347 }
1348
1349 function getPermissionEmails($permissionName) {}
1350
1351 function getRoleEmails($roleName) {}
1352}