INFRA-132 - Put space after flow-control (if/switch/for/foreach/while)
[civicrm-core.git] / CRM / Utils / Token.php
... / ...
CommitLineData
1<?php
2/*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
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',
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
97 * The message.
98 *
99 * @return true|array true if all required tokens are found,
100 * else an array of the missing tokens
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' => array(
108 'action.optOut' => ts("'Opt out via email' - displays an email address for recipients to opt out of receiving emails from your organization."),
109 '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."),
110 'action.unsubscribe' => ts("'Unsubscribe via email' - displays an email address for recipients to unsubscribe from the specific mailing list used to send this message."),
111 '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."),
112 ),
113 );
114 }
115
116 $missing = array();
117 foreach (self::$_requiredTokens as $token => $value) {
118 if (!is_array($value)) {
119 if (!preg_match('/(^|[^\{])' . preg_quote('{' . $token . '}') . '/', $str)) {
120 $missing[$token] = $value;
121 }
122 }
123 else {
124 $present = FALSE;
125 $desc = NULL;
126 foreach ($value as $t => $d) {
127 $desc = $d;
128 if (preg_match('/(^|[^\{])' . preg_quote('{' . $t . '}') . '/', $str)) {
129 $present = TRUE;
130 }
131 }
132 if (!$present) {
133 $missing[$token] = $desc;
134 }
135 }
136 }
137
138 if (empty($missing)) {
139 return TRUE;
140 }
141 return $missing;
142 }
143
144 /**
145 * Wrapper for token matching
146 *
147 * @param string $type
148 * The token type (domain,mailing,contact,action).
149 * @param string $var
150 * The token variable.
151 * @param string $str
152 * The string to search.
153 *
154 * @return boolean Was there a match
155 * @static
156 */
157 public static function token_match($type, $var, &$str) {
158 $token = preg_quote('{' . "$type.$var") . '(\|.+?)?' . preg_quote('}');
159 return preg_match("/(^|[^\{])$token/", $str);
160 }
161
162 /**
163 * Wrapper for token replacing
164 *
165 * @param string $type
166 * The token type.
167 * @param string $var
168 * The token variable.
169 * @param string $value
170 * The value to substitute for the token.
171 * @param string (reference) $str The string to replace in
172 *
173 * @param bool $escapeSmarty
174 *
175 * @return string The processed string
176 * @static
177 */
178 public static function &token_replace($type, $var, $value, &$str, $escapeSmarty = FALSE) {
179 $token = preg_quote('{' . "$type.$var") . '(\|([^\}]+?))?' . preg_quote('}');
180 if (!$value) {
181 $value = '$3';
182 }
183 if ($escapeSmarty) {
184 $value = self::tokenEscapeSmarty($value);
185 }
186 $str = preg_replace("/([^\{])?$token/", "\${1}$value", $str);
187 return $str;
188 }
189
190 /**
191 * Get< the regex for token replacement
192 *
193 * @param string $token_type
194 * A string indicating the the type of token to be used in the expression.
195 *
196 * @return string regular expression sutiable for using in preg_replace
197 * @static
198 */
199 private static function tokenRegex($token_type) {
200 return '/(?<!\{|\\\\)\{' . $token_type . '\.([\w]+(\-[\w\s]+)?)\}(?!\})/';
201 }
202
203 /**
204 * Escape the string so a malicious user cannot inject smarty code into the template
205 *
206 * @param string $string
207 * A string that needs to be escaped from smarty parsing.
208 *
209 * @return string the escaped string
210 * @static
211 */
212 private static function tokenEscapeSmarty($string) {
213 // need to use negative look-behind, as both str_replace() and preg_replace() are sequential
214 return preg_replace(array('/{/', '/(?<!{ldelim)}/'), array('{ldelim}', '{rdelim}'), $string);
215 }
216
217 /**
218 * Replace all the domain-level tokens in $str
219 *
220 * @param string $str
221 * The string with tokens to be replaced.
222 * @param object $domain
223 * The domain BAO.
224 * @param bool $html
225 * Replace tokens with HTML or plain text.
226 *
227 * @param null $knownTokens
228 * @param bool $escapeSmarty
229 *
230 * @return string The processed string
231 * @static
232 */
233 public static function &replaceDomainTokens(
234 $str,
235 &$domain,
236 $html = FALSE,
237 $knownTokens = NULL,
238 $escapeSmarty = FALSE
239 ) {
240 $key = 'domain';
241 if (
242 !$knownTokens || empty($knownTokens[$key])) {
243 return $str;
244 }
245
246 $str = preg_replace_callback(
247 self::tokenRegex($key),
248 function ($matches) use(&$domain, $html, $escapeSmarty) {
249 return CRM_Utils_Token::getDomainTokenReplacement($matches[1], $domain, $html, $escapeSmarty);
250 },
251 $str
252 );
253 return $str;
254 }
255
256 /**
257 * @param $token
258 * @param $domain
259 * @param bool $html
260 * @param bool $escapeSmarty
261 *
262 * @return mixed|null|string
263 */
264 public static function getDomainTokenReplacement($token, &$domain, $html = FALSE, $escapeSmarty = FALSE) {
265 // check if the token we were passed is valid
266 // we have to do this because this function is
267 // called only when we find a token in the string
268
269 $loc = &$domain->getLocationValues();
270
271 if (!in_array($token, self::$_tokens['domain'])) {
272 $value = "{domain.$token}";
273 }
274 elseif ($token == 'address') {
275 static $addressCache = array();
276
277 $cache_key = $html ? 'address-html' : 'address-text';
278 if (array_key_exists($cache_key, $addressCache)) {
279 return $addressCache[$cache_key];
280 }
281
282 $value = NULL;
283 /* Construct the address token */
284
285 if (!empty($loc[$token])) {
286 if ($html) {
287 $value = $loc[$token][1]['display'];
288 $value = str_replace("\n", '<br />', $value);
289 }
290 else {
291 $value = $loc[$token][1]['display_text'];
292 }
293 $addressCache[$cache_key] = $value;
294 }
295 }
296 elseif ($token == 'name' || $token == 'id' || $token == 'description') {
297 $value = $domain->$token;
298 }
299 elseif ($token == 'phone' || $token == 'email') {
300 /* Construct the phone and email tokens */
301
302 $value = NULL;
303 if (!empty($loc[$token])) {
304 foreach ($loc[$token] as $index => $entity) {
305 $value = $entity[$token];
306 break;
307 }
308 }
309 }
310
311 if ($escapeSmarty) {
312 $value = self::tokenEscapeSmarty($value);
313 }
314
315 return $value;
316 }
317
318 /**
319 * Replace all the org-level tokens in $str
320 *
321 * @param string $str
322 * The string with tokens to be replaced.
323 * @param object $org
324 * Associative array of org properties.
325 * @param bool $html
326 * Replace tokens with HTML or plain text.
327 *
328 * @param bool $escapeSmarty
329 *
330 * @return string The processed string
331 * @static
332 */
333 public static function &replaceOrgTokens($str, &$org, $html = FALSE, $escapeSmarty = FALSE) {
334 self::$_tokens['org'] =
335 array_merge(
336 array_keys(CRM_Contact_BAO_Contact::importableFields('Organization')),
337 array('address', 'display_name', 'checksum', 'contact_id')
338 );
339
340 $cv = NULL;
341 foreach (self::$_tokens['org'] as $token) {
342 // print "Getting token value for $token<br/><br/>";
343 if ($token == '') {
344 continue;
345 }
346
347 /* If the string doesn't contain this token, skip it. */
348
349 if (!self::token_match('org', $token, $str)) {
350 continue;
351 }
352
353 /* Construct value from $token and $contact */
354
355 $value = NULL;
356
357 if ($cfID = CRM_Core_BAO_CustomField::getKeyID($token)) {
358 // only generate cv if we need it
359 if ($cv === NULL) {
360 $cv = CRM_Core_BAO_CustomValue::getContactValues($org['contact_id']);
361 }
362 foreach ($cv as $cvFieldID => $value) {
363 if ($cvFieldID == $cfID) {
364 $value = CRM_Core_BAO_CustomOption::getOptionLabel($cfID, $value);
365 break;
366 }
367 }
368 }
369 elseif ($token == 'checksum') {
370 $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($org['contact_id']);
371 $value = "cs={$cs}";
372 }
373 elseif ($token == 'address') {
374 /* Build the location values array */
375
376 $loc = array();
377 $loc['display_name'] = CRM_Utils_Array::retrieveValueRecursive($org, 'display_name');
378 $loc['street_address'] = CRM_Utils_Array::retrieveValueRecursive($org, 'street_address');
379 $loc['city'] = CRM_Utils_Array::retrieveValueRecursive($org, 'city');
380 $loc['state_province'] = CRM_Utils_Array::retrieveValueRecursive($org, 'state_province');
381 $loc['postal_code'] = CRM_Utils_Array::retrieveValueRecursive($org, 'postal_code');
382
383 /* Construct the address token */
384
385 $value = CRM_Utils_Address::format($loc);
386 if ($html) {
387 $value = str_replace("\n", '<br />', $value);
388 }
389 }
390 else {
391 $value = CRM_Utils_Array::retrieveValueRecursive($org, $token);
392 }
393
394 self::token_replace('org', $token, $value, $str, $escapeSmarty);
395 }
396
397 return $str;
398 }
399
400 /**
401 * Replace all mailing tokens in $str
402 *
403 * @param string $str
404 * The string with tokens to be replaced.
405 * @param object $mailing
406 * The mailing BAO, or null for validation.
407 * @param bool $html
408 * Replace tokens with HTML or plain text.
409 *
410 * @param null $knownTokens
411 * @param bool $escapeSmarty
412 *
413 * @return string The processed sstring
414 * @static
415 */
416 public static function &replaceMailingTokens(
417 $str,
418 &$mailing,
419 $html = FALSE,
420 $knownTokens = NULL,
421 $escapeSmarty = FALSE
422 ) {
423 $key = 'mailing';
424 if (!$knownTokens || !isset($knownTokens[$key])) {
425 return $str;
426 }
427
428 $str = preg_replace_callback(
429 self::tokenRegex($key),
430 function ($matches) use(&$mailing, $escapeSmarty) {
431 return CRM_Utils_Token::getMailingTokenReplacement($matches[1], $mailing, $escapeSmarty);
432 },
433 $str
434 );
435 return $str;
436 }
437
438 /**
439 * @param $token
440 * @param $mailing
441 * @param bool $escapeSmarty
442 *
443 * @return string
444 */
445 public static function getMailingTokenReplacement($token, &$mailing, $escapeSmarty = FALSE) {
446 $value = '';
447 switch ($token) {
448 // CRM-7663
449
450 case 'id':
451 $value = $mailing ? $mailing->id : 'undefined';
452 break;
453
454 case 'name':
455 $value = $mailing ? $mailing->name : 'Mailing Name';
456 break;
457
458 case 'group':
459 $groups = $mailing ? $mailing->getGroupNames() : array('Mailing Groups');
460 $value = implode(', ', $groups);
461 break;
462
463 case 'subject':
464 $value = $mailing->subject;
465 break;
466
467 case 'viewUrl':
468 $mailingKey = $mailing->id;
469 if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
470 $mailingKey = $hash;
471 }
472 $value = CRM_Utils_System::url('civicrm/mailing/view',
473 "reset=1&id={$mailingKey}",
474 TRUE, NULL, FALSE, TRUE
475 );
476 break;
477
478 case 'editUrl':
479 $value = CRM_Utils_System::url('civicrm/mailing/send',
480 "reset=1&mid={$mailing->id}&continue=true",
481 TRUE, NULL, FALSE, TRUE
482 );
483 break;
484
485 case 'scheduleUrl':
486 $value = CRM_Utils_System::url('civicrm/mailing/schedule',
487 "reset=1&mid={$mailing->id}",
488 TRUE, NULL, FALSE, TRUE
489 );
490 break;
491
492 case 'html':
493 $page = new CRM_Mailing_Page_View();
494 $value = $page->run($mailing->id, NULL, FALSE, TRUE);
495 break;
496
497 case 'approvalStatus':
498 $value = CRM_Core_PseudoConstant::getLabel('CRM_Mailing_DAO_Mailing', 'approval_status_id', $mailing->approval_status_id);
499 break;
500
501 case 'approvalNote':
502 $value = $mailing->approval_note;
503 break;
504
505 case 'approveUrl':
506 $value = CRM_Utils_System::url('civicrm/mailing/approve',
507 "reset=1&mid={$mailing->id}",
508 TRUE, NULL, FALSE, TRUE
509 );
510 break;
511
512 case 'creator':
513 $value = CRM_Contact_BAO_Contact::displayName($mailing->created_id);
514 break;
515
516 case 'creatorEmail':
517 $value = CRM_Contact_BAO_Contact::getPrimaryEmail($mailing->created_id);
518 break;
519
520 default:
521 $value = "{mailing.$token}";
522 break;
523 }
524
525 if ($escapeSmarty) {
526 $value = self::tokenEscapeSmarty($value);
527 }
528 return $value;
529 }
530
531 /**
532 * Replace all action tokens in $str
533 *
534 * @param string $str
535 * The string with tokens to be replaced.
536 * @param array $addresses
537 * Assoc. array of VERP event addresses.
538 * @param array $urls
539 * Assoc. array of action URLs.
540 * @param bool $html
541 * Replace tokens with HTML or plain text.
542 * @param array $knownTokens
543 * A list of tokens that are known to exist in the email body.
544 *
545 * @param bool $escapeSmarty
546 *
547 * @return string The processed string
548 * @static
549 */
550 public static function &replaceActionTokens(
551 $str,
552 &$addresses,
553 &$urls,
554 $html = FALSE,
555 $knownTokens = NULL,
556 $escapeSmarty = FALSE
557 ) {
558 $key = 'action';
559 // here we intersect with the list of pre-configured valid tokens
560 // so that we remove anything we do not recognize
561 // I hope to move this step out of here soon and
562 // then we will just iterate on a list of tokens that are passed to us
563 if (!$knownTokens || empty($knownTokens[$key])) {
564 return $str;
565 }
566
567 $str = preg_replace_callback(
568 self::tokenRegex($key),
569 function ($matches) use(&$addresses, &$urls, $html, $escapeSmarty) {
570 return CRM_Utils_Token::getActionTokenReplacement($matches[1], $addresses, $urls, $html, $escapeSmarty);
571 },
572 $str
573 );
574 return $str;
575 }
576
577 /**
578 * @param $token
579 * @param $addresses
580 * @param $urls
581 * @param bool $html
582 * @param bool $escapeSmarty
583 *
584 * @return mixed|string
585 */
586 public static function getActionTokenReplacement(
587 $token,
588 &$addresses,
589 &$urls,
590 $html = FALSE,
591 $escapeSmarty = FALSE
592 ) {
593 /* If the token is an email action, use it. Otherwise, find the
594 * appropriate URL */
595
596 if (!in_array($token, self::$_tokens['action'])) {
597 $value = "{action.$token}";
598 }
599 else {
600 $value = CRM_Utils_Array::value($token, $addresses);
601
602 if ($value == NULL) {
603 $value = CRM_Utils_Array::value($token, $urls);
604 }
605
606 if ($value && $html) {
607 //fix for CRM-2318
608 if ((substr($token, -3) != 'Url') && ($token != 'forward')) {
609 $value = "mailto:$value";
610 }
611 }
612 elseif ($value && !$html) {
613 $value = str_replace('&amp;', '&', $value);
614 }
615 }
616
617 if ($escapeSmarty) {
618 $value = self::tokenEscapeSmarty($value);
619 }
620 return $value;
621 }
622
623 /**
624 * Replace all the contact-level tokens in $str with information from
625 * $contact.
626 *
627 * @param string $str
628 * The string with tokens to be replaced.
629 * @param array $contact
630 * Associative array of contact properties.
631 * @param bool $html
632 * Replace tokens with HTML or plain text.
633 * @param array $knownTokens
634 * A list of tokens that are known to exist in the email body.
635 * @param bool $returnBlankToken
636 * Return unevaluated token if value is null.
637 *
638 * @param bool $escapeSmarty
639 *
640 * @return string The processed string
641 * @static
642 */
643 public static function &replaceContactTokens(
644 $str,
645 &$contact,
646 $html = FALSE,
647 $knownTokens = NULL,
648 $returnBlankToken = FALSE,
649 $escapeSmarty = FALSE
650 ) {
651 $key = 'contact';
652 if (self::$_tokens[$key] == NULL) {
653 /* This should come from UF */
654
655 self::$_tokens[$key] =
656 array_merge(
657 array_keys(CRM_Contact_BAO_Contact::exportableFields('All')),
658 array('checksum', 'contact_id')
659 );
660 }
661
662 // here we intersect with the list of pre-configured valid tokens
663 // so that we remove anything we do not recognize
664 // I hope to move this step out of here soon and
665 // then we will just iterate on a list of tokens that are passed to us
666 if (!$knownTokens || empty($knownTokens[$key])) {
667 return $str;
668 }
669
670 $str = preg_replace_callback(
671 self::tokenRegex($key),
672 function ($matches) use(&$contact, $html, $returnBlankToken, $escapeSmarty) {
673 return CRM_Utils_Token::getContactTokenReplacement($matches[1], $contact, $html, $returnBlankToken, $escapeSmarty);
674 },
675 $str
676 );
677
678 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
679 return $str;
680 }
681
682 /**
683 * @param $token
684 * @param $contact
685 * @param bool $html
686 * @param bool $returnBlankToken
687 * @param bool $escapeSmarty
688 *
689 * @return bool|mixed|null|string
690 */
691 public static function getContactTokenReplacement(
692 $token,
693 &$contact,
694 $html = FALSE,
695 $returnBlankToken = FALSE,
696 $escapeSmarty = FALSE
697 ) {
698 if (self::$_tokens['contact'] == NULL) {
699 /* This should come from UF */
700
701 self::$_tokens['contact'] =
702 array_merge(
703 array_keys(CRM_Contact_BAO_Contact::exportableFields('All')),
704 array('checksum', 'contact_id')
705 );
706 }
707
708 /* Construct value from $token and $contact */
709
710 $value = NULL;
711 $noReplace = FALSE;
712
713 // Support legacy tokens
714 $token = CRM_Utils_Array::value($token, self::legacyContactTokens(), $token);
715
716 // check if the token we were passed is valid
717 // we have to do this because this function is
718 // called only when we find a token in the string
719
720 if (!in_array($token, self::$_tokens['contact'])) {
721 $noReplace = TRUE;
722 }
723 elseif ($token == 'checksum') {
724 $hash = CRM_Utils_Array::value('hash', $contact);
725 $contactID = CRM_Utils_Array::retrieveValueRecursive($contact, 'contact_id');
726 $cs = CRM_Contact_BAO_Contact_Utils::generateChecksum($contactID,
727 NULL,
728 NULL,
729 $hash
730 );
731 $value = "cs={$cs}";
732 }
733 else {
734 $value = CRM_Utils_Array::retrieveValueRecursive($contact, $token);
735
736 // FIXME: for some pseudoconstants we get array ( 0 => id, 1 => label )
737 if (is_array($value)) {
738 $value = $value[1];
739 }
740 // Convert pseudoconstants using metadata
741 elseif ($value && is_numeric($value)) {
742 $allFields = CRM_Contact_BAO_Contact::exportableFields('All');
743 if (!empty($allFields[$token]['pseudoconstant'])) {
744 $value = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $token, $value);
745 }
746 }
747 }
748
749 if (!$html) {
750 $value = str_replace('&amp;', '&', $value);
751 }
752
753 // if null then return actual token
754 if ($returnBlankToken && !$value) {
755 $noReplace = TRUE;
756 }
757
758 if ($noReplace) {
759 $value = "{contact.$token}";
760 }
761
762 if ($escapeSmarty
763 && !($returnBlankToken && $noReplace)) { // $returnBlankToken means the caller wants to do further attempts at processing unreplaced tokens -- so don't escape them yet in this case.
764 $value = self::tokenEscapeSmarty($value);
765 }
766
767 return $value;
768 }
769
770 /**
771 * Replace all the hook tokens in $str with information from
772 * $contact.
773 *
774 * @param string $str
775 * The string with tokens to be replaced.
776 * @param array $contact
777 * Associative array of contact properties (including hook token values).
778 * @param $categories
779 * @param bool $html
780 * Replace tokens with HTML or plain text.
781 *
782 * @param bool $escapeSmarty
783 *
784 * @return string The processed string
785 * @static
786 */
787 public static function &replaceHookTokens(
788 $str,
789 &$contact,
790 &$categories,
791 $html = FALSE,
792 $escapeSmarty = FALSE
793 ) {
794 foreach ($categories as $key) {
795 $str = preg_replace_callback(
796 self::tokenRegex($key),
797 function ($matches) use(&$contact, $key, $html, $escapeSmarty) {
798 return CRM_Utils_Token::getHookTokenReplacement($matches[1], $contact, $key, $html, $escapeSmarty);
799 },
800 $str
801 );
802 }
803 return $str;
804 }
805
806 /**
807 * Parse html through Smarty resolving any smarty functions
808 * @param string $tokenHtml
809 * @param array $entity
810 * @param string $entityType
811 * @return string html parsed through smarty
812 */
813 public static function parseThroughSmarty($tokenHtml, $entity, $entityType = 'contact') {
814 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
815 $smarty = CRM_Core_Smarty::singleton();
816 // also add the tokens to the template
817 $smarty->assign_by_ref($entityType, $entity);
818 $tokenHtml = $smarty->fetch("string:$tokenHtml");
819 }
820 return $tokenHtml;
821 }
822
823 /**
824 * @param $token
825 * @param $contact
826 * @param $category
827 * @param bool $html
828 * @param bool $escapeSmarty
829 *
830 * @return mixed|string
831 */
832 public static function getHookTokenReplacement(
833 $token,
834 &$contact,
835 $category,
836 $html = FALSE,
837 $escapeSmarty = FALSE
838 ) {
839 $value = CRM_Utils_Array::value("{$category}.{$token}", $contact);
840
841 if ($value && !$html) {
842 $value = str_replace('&amp;', '&', $value);
843 }
844
845 if ($escapeSmarty) {
846 $value = self::tokenEscapeSmarty($value);
847 }
848
849 return $value;
850 }
851
852 /**
853 * unescapeTokens removes any characters that caused the replacement routines to skip token replacement
854 * for example {{token}} or \{token} will result in {token} in the final email
855 *
856 * this routine will remove the extra backslashes and braces
857 *
858 * @param $str ref to the string that will be scanned and modified
859 * @return void this function works directly on the string that is passed
860 * @access public
861 * @static
862 */
863 public static function unescapeTokens(&$str) {
864 $str = preg_replace('/\\\\|\{(\{\w+\.\w+\})\}/', '\\1', $str);
865 }
866
867 /**
868 * Replace unsubscribe tokens
869 *
870 * @param string $str
871 * The string with tokens to be replaced.
872 * @param object $domain
873 * The domain BAO.
874 * @param array $groups
875 * The groups (if any) being unsubscribed.
876 * @param bool $html
877 * Replace tokens with html or plain text.
878 * @param int $contact_id
879 * The contact ID.
880 * @param string hash The security hash of the unsub event
881 *
882 * @return string The processed string
883 * @static
884 */
885 public static function &replaceUnsubscribeTokens(
886 $str,
887 &$domain,
888 &$groups,
889 $html,
890 $contact_id,
891 $hash
892 ) {
893 if (self::token_match('unsubscribe', 'group', $str)) {
894 if (!empty($groups)) {
895 $config = CRM_Core_Config::singleton();
896 $base = CRM_Utils_System::baseURL();
897
898 // FIXME: an ugly hack for CRM-2035, to be dropped once CRM-1799 is implemented
899 $dao = new CRM_Contact_DAO_Group();
900 $dao->find();
901 while ($dao->fetch()) {
902 if (substr($dao->visibility, 0, 6) == 'Public') {
903 $visibleGroups[] = $dao->id;
904 }
905 }
906 $value = implode(', ', $groups);
907 self::token_replace('unsubscribe', 'group', $value, $str);
908 }
909 }
910 return $str;
911 }
912
913 /**
914 * Replace resubscribe tokens
915 *
916 * @param string $str
917 * The string with tokens to be replaced.
918 * @param object $domain
919 * The domain BAO.
920 * @param array $groups
921 * The groups (if any) being resubscribed.
922 * @param bool $html
923 * Replace tokens with html or plain text.
924 * @param int $contact_id
925 * The contact ID.
926 * @param string hash The security hash of the resub event
927 *
928 * @return string The processed string
929 * @static
930 */
931 public static function &replaceResubscribeTokens(
932 $str, &$domain, &$groups, $html,
933 $contact_id, $hash
934 ) {
935 if (self::token_match('resubscribe', 'group', $str)) {
936 if (!empty($groups)) {
937 $value = implode(', ', $groups);
938 self::token_replace('resubscribe', 'group', $value, $str);
939 }
940 }
941 return $str;
942 }
943
944 /**
945 * Replace subscription-confirmation-request tokens
946 *
947 * @param string $str
948 * The string with tokens to be replaced.
949 * @param string $group
950 * The name of the group being subscribed.
951 * @param $url
952 * @param bool $html
953 * Replace tokens with html or plain text.
954 *
955 * @return string The processed string
956 * @static
957 */
958 public static function &replaceSubscribeTokens($str, $group, $url, $html) {
959 if (self::token_match('subscribe', 'group', $str)) {
960 self::token_replace('subscribe', 'group', $group, $str);
961 }
962 if (self::token_match('subscribe', 'url', $str)) {
963 self::token_replace('subscribe', 'url', $url, $str);
964 }
965 return $str;
966 }
967
968 /**
969 * Replace subscription-invitation tokens
970 *
971 * @param string $str
972 * The string with tokens to be replaced.
973 *
974 * @return string The processed string
975 * @static
976 */
977 public static function &replaceSubscribeInviteTokens($str) {
978 if (preg_match('/\{action\.subscribeUrl\}/', $str)) {
979 $url = CRM_Utils_System::url('civicrm/mailing/subscribe',
980 'reset=1',
981 TRUE, NULL, TRUE, TRUE
982 );
983 $str = preg_replace('/\{action\.subscribeUrl\}/', $url, $str);
984 }
985
986 if (preg_match('/\{action\.subscribeUrl.\d+\}/', $str, $matches)) {
987 foreach ($matches as $key => $value) {
988 $gid = substr($value, 21, -1);
989 $url = CRM_Utils_System::url('civicrm/mailing/subscribe',
990 "reset=1&gid={$gid}",
991 TRUE, NULL, TRUE, TRUE
992 );
993 $url = str_replace('&amp;', '&', $url);
994 $str = preg_replace('/' . preg_quote($value) . '/', $url, $str);
995 }
996 }
997
998 if (preg_match('/\{action\.subscribe.\d+\}/', $str, $matches)) {
999 foreach ($matches as $key => $value) {
1000 $gid = substr($value, 18, -1);
1001 $config = CRM_Core_Config::singleton();
1002 $domain = CRM_Core_BAO_MailSettings::defaultDomain();
1003 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
1004 // we add the 0.0000000000000000 part to make this match the other email patterns (with action, two ids and a hash)
1005 $str = preg_replace('/' . preg_quote($value) . '/', "mailto:{$localpart}s.{$gid}.0.0000000000000000@$domain", $str);
1006 }
1007 }
1008 return $str;
1009 }
1010
1011 /**
1012 * Replace welcome/confirmation tokens
1013 *
1014 * @param string $str
1015 * The string with tokens to be replaced.
1016 * @param string $group
1017 * The name of the group being subscribed.
1018 * @param bool $html
1019 * Replace tokens with html or plain text.
1020 *
1021 * @return string The processed string
1022 * @static
1023 */
1024 public static function &replaceWelcomeTokens($str, $group, $html) {
1025 if (self::token_match('welcome', 'group', $str)) {
1026 self::token_replace('welcome', 'group', $group, $str);
1027 }
1028 return $str;
1029 }
1030
1031 /**
1032 * Find unprocessed tokens (call this last)
1033 *
1034 * @param string $str
1035 * The string to search.
1036 *
1037 * @return array Array of tokens that weren't replaced
1038 * @static
1039 */
1040 public static function &unmatchedTokens(&$str) {
1041 //preg_match_all('/[^\{\\\\]\{(\w+\.\w+)\}[^\}]/', $str, $match);
1042 preg_match_all('/\{(\w+\.\w+)\}/', $str, $match);
1043 return $match[1];
1044 }
1045
1046 /**
1047 * Find and replace tokens for each component
1048 *
1049 * @param string $str
1050 * The string to search.
1051 * @param array $contact
1052 * Associative array of contact properties.
1053 * @param array $components
1054 * A list of tokens that are known to exist in the email body.
1055 *
1056 * @param bool $escapeSmarty
1057 * @param bool $returnEmptyToken
1058 *
1059 * @return string The processed string
1060 * @static
1061 */
1062 public static function &replaceComponentTokens(&$str, $contact, $components, $escapeSmarty = FALSE, $returnEmptyToken = TRUE) {
1063 if (!is_array($components) || empty($contact)) {
1064 return $str;
1065 }
1066
1067 foreach ($components as $name => $tokens) {
1068 if (!is_array($tokens) || empty($tokens)) {
1069 continue;
1070 }
1071
1072 foreach ($tokens as $token) {
1073 if (self::token_match($name, $token, $str) && isset($contact[$name . '.' . $token])) {
1074 self::token_replace($name, $token, $contact[$name . '.' . $token], $str, $escapeSmarty);
1075 }
1076 elseif (!$returnEmptyToken) {
1077 //replacing empty token
1078 self::token_replace($name, $token, "", $str, $escapeSmarty);
1079 }
1080 }
1081 }
1082 return $str;
1083 }
1084
1085 /**
1086 * Get array of string tokens
1087 *
1088 * @param $string
1089 * The input string to parse for tokens.
1090 *
1091 * @return array $tokens array of tokens mentioned in field@access public
1092 * @static
1093 */
1094 public static function getTokens($string) {
1095 $matches = array();
1096 $tokens = array();
1097 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1098 $string,
1099 $matches,
1100 PREG_PATTERN_ORDER
1101 );
1102
1103 if ($matches[1]) {
1104 foreach ($matches[1] as $token) {
1105 list($type, $name) = preg_split('/\./', $token, 2);
1106 if ($name && $type) {
1107 if (!isset($tokens[$type])) {
1108 $tokens[$type] = array();
1109 }
1110 $tokens[$type][] = $name;
1111 }
1112 }
1113 }
1114 return $tokens;
1115 }
1116
1117 /**
1118 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1119 * and getTokens appears to be historical rather than intentional and should be reviewed
1120 * @param $string
1121 * @return array fields to pass in as return properties when populating token
1122 *
1123 */
1124 public static function getReturnProperties(&$string) {
1125 $returnProperties = array();
1126 $matches = array();
1127 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1128 $string,
1129 $matches,
1130 PREG_PATTERN_ORDER
1131 );
1132 if ($matches[1]) {
1133 foreach ($matches[1] as $token) {
1134 list($type, $name) = preg_split('/\./', $token, 2);
1135 if ($name) {
1136 $returnProperties["{$name}"] = 1;
1137 }
1138 }
1139 }
1140
1141 return $returnProperties;
1142 }
1143
1144 /**
1145 * Gives required details of contacts in an indexed array format so we
1146 * can iterate in a nice loop and do token evaluation
1147 *
1148 * @param $contactIDs
1149 * @param array $returnProperties
1150 * Of required properties.
1151 * @param bool $skipOnHoldDon't return on_hold contact info also.
1152 * Don't return on_hold contact info also.
1153 * @param bool $skipDeceasedDon't return deceased contact info.
1154 * Don't return deceased contact info.
1155 * @param array $extraParams
1156 * Extra params.
1157 * @param array $tokens
1158 * The list of tokens we've extracted from the content.
1159 * @param null $className
1160 * @param int $jobID
1161 * The mailing list jobID - this is a legacy param.
1162 *
1163 * @return array
1164 * @static
1165 */
1166 static function getTokenDetails(
1167 $contactIDs,
1168 $returnProperties = NULL,
1169 $skipOnHold = TRUE,
1170 $skipDeceased = TRUE,
1171 $extraParams = NULL,
1172 $tokens = array(),
1173 $className = NULL,
1174 $jobID = NULL
1175 ) {
1176 if (empty($contactIDs)) {
1177 // putting a fatal here so we can track if/when this happens
1178 CRM_Core_Error::fatal();
1179 }
1180
1181 $params = array();
1182 foreach ($contactIDs as $key => $contactID) {
1183 $params[] = array(
1184 CRM_Core_Form::CB_PREFIX . $contactID,
1185 '=', 1, 0, 0,
1186 );
1187 }
1188
1189 // fix for CRM-2613
1190 if ($skipDeceased) {
1191 $params[] = array('is_deceased', '=', 0, 0, 0);
1192 }
1193
1194 //fix for CRM-3798
1195 if ($skipOnHold) {
1196 $params[] = array('on_hold', '=', 0, 0, 0);
1197 }
1198
1199 if ($extraParams) {
1200 $params = array_merge($params, $extraParams);
1201 }
1202
1203 // if return properties are not passed then get all return properties
1204 if (empty($returnProperties)) {
1205 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact::exportableFields()),
1206 array('display_name', 'checksum', 'contact_id')
1207 );
1208 foreach ($fields as $key => $val) {
1209 $returnProperties[$val] = 1;
1210 }
1211 }
1212
1213 $custom = array();
1214 foreach ($returnProperties as $name => $dontCare) {
1215 $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
1216 if ($cfID) {
1217 $custom[] = $cfID;
1218 }
1219 }
1220
1221 //get the total number of contacts to fetch from database.
1222 $numberofContacts = count($contactIDs);
1223 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1224
1225 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1226
1227 $contactDetails = &$details[0];
1228
1229 foreach ($contactIDs as $key => $contactID) {
1230 if (array_key_exists($contactID, $contactDetails)) {
1231 if (CRM_Utils_Array::value('preferred_communication_method', $returnProperties) == 1
1232 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1233 ) {
1234 $pcm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1235
1236 // communication Prefferance
1237 $contactPcm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1238 $contactDetails[$contactID]['preferred_communication_method']
1239 );
1240 $result = array();
1241 foreach ($contactPcm as $key => $val) {
1242 if ($val) {
1243 $result[$val] = $pcm[$val];
1244 }
1245 }
1246 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1247 }
1248
1249 foreach ($custom as $cfID) {
1250 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1251 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1252 $cfID, $details[1]
1253 );
1254 }
1255 }
1256
1257 //special case for greeting replacement
1258 foreach (array(
1259 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1260 if (!empty($contactDetails[$contactID][$val])) {
1261 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1262 }
1263 }
1264 }
1265 }
1266
1267 // also call a hook and get token details
1268 CRM_Utils_Hook::tokenValues($details[0],
1269 $contactIDs,
1270 $jobID,
1271 $tokens,
1272 $className
1273 );
1274 return $details;
1275 }
1276
1277 /**
1278 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1279 * specific tokens to be rendered
1280 *
1281 * @param array $contactIDs
1282 * This should always be array(0) or its not anonymous - left to keep signature same.
1283 * as main fn
1284 * @param string $returnProperties
1285 * @param bool $skipOnHold
1286 * @param bool $skipDeceased
1287 * @param string $extraParams
1288 * @param array $tokens
1289 * @param string $className
1290 * Sent as context to the hook.
1291 * @param string $jobID
1292 * @return array contactDetails with hooks swapped out
1293 */
1294 public function getAnonymousTokenDetails($contactIDs = array(
1295 0),
1296 $returnProperties = NULL,
1297 $skipOnHold = TRUE,
1298 $skipDeceased = TRUE,
1299 $extraParams = NULL,
1300 $tokens = array(),
1301 $className = NULL,
1302 $jobID = NULL) {
1303 $details = array(0 => array());
1304 // also call a hook and get token details
1305 CRM_Utils_Hook::tokenValues($details[0],
1306 $contactIDs,
1307 $jobID,
1308 $tokens,
1309 $className
1310 );
1311 return $details;
1312 }
1313
1314 /**
1315 * Gives required details of contribuion in an indexed array format so we
1316 * can iterate in a nice loop and do token evaluation
1317 *
1318 * @param array $contributionIDs
1319 * @param array $returnProperties
1320 * Of required properties.
1321 * @param array $extraParams
1322 * Extra params.
1323 * @param array $tokens
1324 * The list of tokens we've extracted from the content.
1325 * @param string $className
1326 *
1327 * @return array
1328 * @static
1329 */
1330 static function getContributionTokenDetails(
1331 $contributionIDs,
1332 $returnProperties = NULL,
1333 $extraParams = NULL,
1334 $tokens = array(),
1335 $className = NULL
1336 ) {
1337 //@todo - this function basically replications calling civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1338 if (empty($contributionIDs)) {
1339 // putting a fatal here so we can track if/when this happens
1340 CRM_Core_Error::fatal();
1341 }
1342
1343 $details = array();
1344
1345 // no apiQuery helper yet, so do a loop and find contribution by id
1346 foreach ($contributionIDs as $contributionID) {
1347
1348 $dao = new CRM_Contribute_DAO_Contribution();
1349 $dao->id = $contributionID;
1350
1351 if ($dao->find(TRUE)) {
1352
1353 $details[$dao->id] = array();
1354 CRM_Core_DAO::storeValues($dao, $details[$dao->id]);
1355
1356 // do the necessary transformation
1357 if (!empty($details[$dao->id]['payment_instrument_id'])) {
1358 $piId = $details[$dao->id]['payment_instrument_id'];
1359 $pis = CRM_Contribute_PseudoConstant::paymentInstrument();
1360 $details[$dao->id]['payment_instrument'] = $pis[$piId];
1361 }
1362 if (!empty($details[$dao->id]['campaign_id'])) {
1363 $campaignId = $details[$dao->id]['campaign_id'];
1364 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1365 $details[$dao->id]['campaign'] = $campaigns[$campaignId];
1366 }
1367
1368 if (!empty($details[$dao->id]['financial_type_id'])) {
1369 $financialtypeId = $details[$dao->id]['financial_type_id'];
1370 $ftis = CRM_Contribute_PseudoConstant::financialType();
1371 $details[$dao->id]['financial_type'] = $ftis[$financialtypeId];
1372 }
1373
1374 // TODO: call a hook to get token contribution details
1375 }
1376 }
1377
1378 return $details;
1379 }
1380
1381 /**
1382 * Get Membership Token Details
1383 * @param array $membershipIDs
1384 * Array of membership IDS.
1385 */
1386 public static function getMembershipTokenDetails($membershipIDs) {
1387 $memberships = civicrm_api3('membership', 'get', array('options' => array('limit' => 200000), 'membership_id' => array('IN' => (array) $membershipIDs)));
1388 return $memberships['values'];
1389 }
1390 /**
1391 * Replace greeting tokens exists in message/subject
1392 *
1393 */
1394 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1395
1396 if (!$contactDetails && !$contactId) {
1397 return;
1398 }
1399
1400 // check if there are any tokens
1401 $greetingTokens = self::getTokens($tokenString);
1402
1403 if (!empty($greetingTokens)) {
1404 // first use the existing contact object for token replacement
1405 if (!empty($contactDetails)) {
1406 $tokenString = CRM_Utils_Token::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1407 }
1408
1409 // check if there are any unevaluated tokens
1410 $greetingTokens = self::getTokens($tokenString);
1411
1412 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1413 // so retrieve it from database
1414 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1415 $greetingsReturnProperties = array_flip(CRM_Utils_Array::value('contact', $greetingTokens));
1416 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1417 $contactParams = array('contact_id' => $contactId);
1418
1419 $greetingDetails = self::getTokenDetails($contactParams,
1420 $greetingsReturnProperties,
1421 FALSE, FALSE, NULL,
1422 $greetingTokens,
1423 $className
1424 );
1425
1426 // again replace tokens
1427 $tokenString = CRM_Utils_Token::replaceContactTokens($tokenString,
1428 $greetingDetails,
1429 TRUE,
1430 $greetingTokens,
1431 FALSE,
1432 $escapeSmarty
1433 );
1434 }
1435
1436 // check if there are still any unevaluated tokens
1437 $remainingTokens = self::getTokens($tokenString);
1438
1439 // contact related $greetingTokens not empty, there are customized or hook tokens to replace
1440 if (!empty($remainingTokens['contact']) ) {
1441 // Fill the return properties array
1442 $greetingTokens = $remainingTokens['contact'];
1443 reset($greetingTokens);
1444 $greetingsReturnProperties = array();
1445 while (list($key) = each($greetingTokens)) {
1446 $props = array_flip(CRM_Utils_Array::value($key, $greetingTokens));
1447 $props = array_fill_keys(array_keys($props), 1);
1448 $greetingsReturnProperties = $greetingsReturnProperties + $props;
1449 }
1450 $contactParams = array('contact_id' => $contactId);
1451 $greetingDetails = self::getTokenDetails($contactParams,
1452 $greetingsReturnProperties,
1453 FALSE, FALSE, NULL,
1454 $greetingTokens,
1455 $className
1456 );
1457 // Prepare variables for calling replaceHookTokens
1458 $categories = array_keys($greetingTokens);
1459 list($contact) = $greetingDetails;
1460 // Replace tokens defined in Hooks.
1461 $tokenString = CRM_Utils_Token::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1462 }
1463 }
1464 }
1465
1466 /**
1467 * @param $tokens
1468 *
1469 * @return array
1470 */
1471 public static function flattenTokens(&$tokens) {
1472 $flattenTokens = array();
1473
1474 foreach (array(
1475 'html', 'text', 'subject') as $prop) {
1476 if (!isset($tokens[$prop])) {
1477 continue;
1478 }
1479 foreach ($tokens[$prop] as $type => $names) {
1480 if (!isset($flattenTokens[$type])) {
1481 $flattenTokens[$type] = array();
1482 }
1483 foreach ($names as $name) {
1484 $flattenTokens[$type][$name] = 1;
1485 }
1486 }
1487 }
1488
1489 return $flattenTokens;
1490 }
1491
1492 /**
1493 * Replace all user tokens in $str
1494 *
1495 * @param string $str
1496 * The string with tokens to be replaced.
1497 *
1498 * @param null $knownTokens
1499 * @param bool $escapeSmarty
1500 *
1501 * @return string The processed string
1502 * @static
1503 */
1504 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1505 $key = 'user';
1506 if (!$knownTokens ||
1507 !isset($knownTokens[$key])
1508 ) {
1509 return $str;
1510 }
1511
1512 $str = preg_replace_callback(
1513 self::tokenRegex($key),
1514 function ($matches) use($escapeSmarty) {
1515 return CRM_Utils_Token::getUserTokenReplacement($matches[1], $escapeSmarty);
1516 },
1517 $str
1518 );
1519 return $str;
1520 }
1521
1522 /**
1523 * @param $token
1524 * @param bool $escapeSmarty
1525 *
1526 * @return string
1527 */
1528 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1529 $value = '';
1530
1531 list($objectName, $objectValue) = explode('-', $token, 2);
1532
1533 switch ($objectName) {
1534 case 'permission':
1535 $value = CRM_Core_Permission::permissionEmails($objectValue);
1536 break;
1537
1538 case 'role':
1539 $value = CRM_Core_Permission::roleEmails($objectValue);
1540 break;
1541 }
1542
1543 if ($escapeSmarty) {
1544 $value = self::tokenEscapeSmarty($value);
1545 }
1546
1547 return $value;
1548 }
1549
1550 /**
1551 *
1552 */
1553 protected static function _buildContributionTokens() {
1554 $key = 'contribution';
1555 if (self::$_tokens[$key] == NULL) {
1556 self::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution::exportableFields('All'),
1557 array('campaign', 'financial_type')
1558 ));
1559 }
1560 }
1561
1562 /**
1563 * Store membership tokens on the static _tokens array
1564 */
1565 protected static function _buildMembershipTokens() {
1566 $key = 'membership';
1567 if (!isset(self::$_tokens[$key]) || self::$_tokens[$key] == NULL) {
1568 $membershipTokens = array();
1569 $tokens = CRM_Core_SelectValues::membershipTokens();
1570 foreach ($tokens as $token => $dontCare) {
1571 $membershipTokens[] = substr($token, (strpos($token, '.') + 1), -1);
1572 }
1573 self::$_tokens[$key] = $membershipTokens;
1574 }
1575 }
1576
1577 /**
1578 * Replace tokens for an entity
1579 * @param string $entity
1580 * @param array $entityArray
1581 * (e.g. in format from api).
1582 * @param string $str
1583 * String to replace in.
1584 * @param array $knownTokens
1585 * Array of tokens present.
1586 * @param bool $escapeSmarty
1587 * @return string string with replacements made
1588 */
1589 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1590 if (!$knownTokens || empty($knownTokens[$entity])) {
1591 return $str;
1592 }
1593
1594 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1595 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1596 foreach ($knownTokens[$entity] as $token) {
1597 $replaceMent = CRM_Utils_Token::$fn($token, $entityArray, $escapeSmarty);
1598 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1599 }
1600 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1601 return $str;
1602 }
1603
1604 /**
1605 * Replace Contribution tokens in html
1606 *
1607 * @param string $str
1608 * @param array $contribution
1609 * @param bool|string $html
1610 * @param string $knownTokens
1611 * @param bool|string $escapeSmarty
1612 *
1613 * @return unknown|Ambigous <string, mixed>|mixed
1614 */
1615 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1616 $key = 'contribution';
1617 if (!$knownTokens || !CRM_Utils_Array::value($key, $knownTokens)) {
1618 return $str; //early return
1619 }
1620 self::_buildContributionTokens();
1621
1622 // here we intersect with the list of pre-configured valid tokens
1623 // so that we remove anything we do not recognize
1624 // I hope to move this step out of here soon and
1625 // then we will just iterate on a list of tokens that are passed to us
1626
1627 $str = preg_replace_callback(
1628 self::tokenRegex($key),
1629 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1630 return CRM_Utils_Token::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1631 },
1632 $str
1633 );
1634
1635 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1636 return $str;
1637 }
1638
1639 /**
1640 * We have a situation where we are rendering more than one token in each field because we are combining
1641 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1642 *
1643 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1644 * it applies (other tokens are OK including date fields)
1645 *
1646 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1647 * does - but the fields is already being formatted through a date function
1648 *
1649 * @param string $separator
1650 * @param string $str
1651 * @param array $contribution
1652 * @param bool|string $html
1653 * @param string $knownTokens
1654 * @param bool|string $escapeSmarty
1655 *
1656 * @return \Ambigous|mixed|string|\unknown
1657 */
1658 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1659 if (empty($knownTokens['contribution'])) {
1660 return $str;
1661 }
1662
1663 if (in_array('receive_date', $knownTokens['contribution'])) {
1664 $formattedDates = array();
1665 $dates = explode($separator, $contribution['receive_date']);
1666 foreach ($dates as $date) {
1667 $formattedDates[] = CRM_Utils_Date::customFormat($date, NULL, array('j', 'm', 'Y'));
1668 }
1669 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1670 unset($knownTokens['contribution']['receive_date']);
1671 }
1672 return self::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1673 }
1674
1675 /**
1676 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1677 * - this is used by the pdfLetter task from membership search
1678 * @param string $token
1679 * @param array $membership
1680 * An api result array for a single membership.
1681 * @param bool $escapeSmarty
1682 * @return string token replacement
1683 */
1684 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1685 $entity = 'membership';
1686 self::_buildMembershipTokens();
1687 switch ($token) {
1688 case 'type':
1689 $value = $membership['membership_name'];
1690 break;
1691
1692 case 'status':
1693 $statuses = CRM_Member_BAO_Membership::buildOptions('status_id');
1694 $value = $statuses[$membership['status_id']];
1695 break;
1696
1697 case 'fee':
1698 try{
1699 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1700 }
1701 catch (CiviCRM_API3_Exception $e) {
1702 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1703 // api handles NULL (4.4)
1704 $value = 0;
1705 }
1706 break;
1707
1708 default:
1709 if (in_array($token, self::$_tokens[$entity])) {
1710 $value = $membership[$token];
1711 }
1712 else {
1713 //ie unchanged
1714 $value = "{$entity}.{$token}";
1715 }
1716 break;
1717 }
1718
1719 if ($escapeSmarty) {
1720 $value = self::tokenEscapeSmarty($value);
1721 }
1722 return $value;
1723 }
1724
1725 /**
1726 * @param $token
1727 * @param $contribution
1728 * @param bool $html
1729 * @param bool $escapeSmarty
1730 *
1731 * @return mixed|string
1732 */
1733 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1734 self::_buildContributionTokens();
1735
1736 switch ($token) {
1737 case 'total_amount':
1738 case 'net_amount':
1739 case 'fee_amount':
1740 case 'non_deductible_amount':
1741 $value = CRM_Utils_Money::format(CRM_Utils_Array::retrieveValueRecursive($contribution, $token));
1742 break;
1743
1744 case 'receive_date':
1745 $value = CRM_Utils_Array::retrieveValueRecursive($contribution, $token);
1746 $value = CRM_Utils_Date::customFormat($value, NULL, array('j', 'm', 'Y'));
1747 break;
1748
1749 default:
1750 if (!in_array($token, self::$_tokens['contribution'])) {
1751 $value = "{contribution.$token}";
1752 }
1753 else {
1754 $value = CRM_Utils_Array::retrieveValueRecursive($contribution, $token);
1755 }
1756 break;
1757 }
1758
1759 if ($escapeSmarty) {
1760 $value = self::tokenEscapeSmarty($value);
1761 }
1762 return $value;
1763 }
1764
1765 /**
1766 * @return array: legacy_token => new_token
1767 */
1768 public static function legacyContactTokens() {
1769 return array(
1770 'individual_prefix' => 'prefix_id',
1771 'individual_suffix' => 'suffix_id',
1772 'gender' => 'gender_id',
1773 'communication_style' => 'communication_style_id',
1774 );
1775 }
1776
1777 /**
1778 * Formats a token list for the select2 widget
1779 * @param $tokens
1780 * @return array
1781 */
1782 public static function formatTokensForDisplay($tokens) {
1783 $sorted = $output = array();
1784
1785 // Sort in ascending order by ignoring word case
1786 natcasesort($tokens);
1787
1788 // Attempt to place tokens into optgroups
1789 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1790 foreach ($tokens as $k => $v) {
1791 // Check to see if this token is already in a group e.g. for custom fields
1792 $split = explode(' :: ', $v);
1793 if (!empty($split[1])) {
1794 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1795 }
1796 // Group by entity
1797 else {
1798 $split = explode('.', trim($k, '{}'));
1799 if (isset($split[1])) {
1800 $entity = array_key_exists($split[1], CRM_Core_DAO_Address::export()) ? 'Address' : ucfirst($split[0]);
1801 }
1802 else {
1803 $entity = 'Contact';
1804 }
1805 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1806 }
1807 }
1808
1809 ksort($sorted);
1810 foreach ($sorted as $k => $v) {
1811 $output[] = array('text' => $k, 'children' => $v);
1812 }
1813
1814 return $output;
1815 }
1816}