INFRA-132 - Fix missing newlines in comments
[civicrm-core.git] / CRM / Utils / Token.php
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 */
39 class CRM_Utils_Token {
40 static $_requiredTokens = NULL;
41
42 static $_tokens = array(
43 'action' => array(
44 'forward',
45 'optOut',
46 'optOutUrl',
47 'reply',
48 'unsubscribe',
49 'unsubscribeUrl',
50 'resubscribe',
51 'resubscribeUrl',
52 'subscribeUrl',
53 ),
54 'mailing' => array(
55 'id',
56 'name',
57 'group',
58 'subject',
59 'viewUrl',
60 'editUrl',
61 'scheduleUrl',
62 'approvalStatus',
63 'approvalNote',
64 'approveUrl',
65 'creator',
66 'creatorEmail',
67 ),
68 'user' => array(
69 // we extract the stuff after the role / permission and return the
70 // civicrm email addresses of all users with that role / permission
71 // useful with rules integration
72 'permission:',
73 'role:',
74 ),
75 // populate this dynamically
76 'contact' => NULL,
77 // populate this dynamically
78 'contribution' => NULL,
79 'domain' => array(
80 'name',
81 'phone',
82 'address',
83 'email',
84 'id',
85 'description',
86 ),
87 'subscribe' => array('group'),
88 'unsubscribe' => array('group'),
89 'resubscribe' => array('group'),
90 'welcome' => array('group'),
91 );
92
93 /**
94 * Check a string (mailing body) for required tokens.
95 *
96 * @param string $str
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 $string
1089 * The input string to parse for tokens.
1090 *
1091 * @return array $tokens array of tokens mentioned in field
1092 * @access public
1093 * @static
1094 */
1095 public static function getTokens($string) {
1096 $matches = array();
1097 $tokens = array();
1098 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1099 $string,
1100 $matches,
1101 PREG_PATTERN_ORDER
1102 );
1103
1104 if ($matches[1]) {
1105 foreach ($matches[1] as $token) {
1106 list($type, $name) = preg_split('/\./', $token, 2);
1107 if ($name && $type) {
1108 if (!isset($tokens[$type])) {
1109 $tokens[$type] = array();
1110 }
1111 $tokens[$type][] = $name;
1112 }
1113 }
1114 }
1115 return $tokens;
1116 }
1117
1118 /**
1119 * Function to determine which values to retrieve to insert into tokens. The heavy resemblance between this function
1120 * and getTokens appears to be historical rather than intentional and should be reviewed
1121 * @param $string
1122 * @return array fields to pass in as return properties when populating token
1123 *
1124 */
1125 public static function getReturnProperties(&$string) {
1126 $returnProperties = array();
1127 $matches = array();
1128 preg_match_all('/(?<!\{|\\\\)\{(\w+\.\w+)\}(?!\})/',
1129 $string,
1130 $matches,
1131 PREG_PATTERN_ORDER
1132 );
1133 if ($matches[1]) {
1134 foreach ($matches[1] as $token) {
1135 list($type, $name) = preg_split('/\./', $token, 2);
1136 if ($name) {
1137 $returnProperties["{$name}"] = 1;
1138 }
1139 }
1140 }
1141
1142 return $returnProperties;
1143 }
1144
1145 /**
1146 * Gives required details of contacts in an indexed array format so we
1147 * can iterate in a nice loop and do token evaluation
1148 *
1149 * @param $contactIDs
1150 * @param array $returnProperties
1151 * Of required properties.
1152 * @param bool $skipOnHoldDon't return on_hold contact info also.
1153 * Don't return on_hold contact info also.
1154 * @param bool $skipDeceasedDon't return deceased contact info.
1155 * Don't return deceased contact info.
1156 * @param array $extraParams
1157 * Extra params.
1158 * @param array $tokens
1159 * The list of tokens we've extracted from the content.
1160 * @param null $className
1161 * @param int $jobID
1162 * The mailing list jobID - this is a legacy param.
1163 *
1164 * @return array
1165 * @static
1166 */
1167 static function getTokenDetails(
1168 $contactIDs,
1169 $returnProperties = NULL,
1170 $skipOnHold = TRUE,
1171 $skipDeceased = TRUE,
1172 $extraParams = NULL,
1173 $tokens = array(),
1174 $className = NULL,
1175 $jobID = NULL
1176 ) {
1177 if (empty($contactIDs)) {
1178 // putting a fatal here so we can track if/when this happens
1179 CRM_Core_Error::fatal();
1180 }
1181
1182 $params = array();
1183 foreach ($contactIDs as $key => $contactID) {
1184 $params[] = array(
1185 CRM_Core_Form::CB_PREFIX . $contactID,
1186 '=', 1, 0, 0,
1187 );
1188 }
1189
1190 // fix for CRM-2613
1191 if ($skipDeceased) {
1192 $params[] = array('is_deceased', '=', 0, 0, 0);
1193 }
1194
1195 //fix for CRM-3798
1196 if ($skipOnHold) {
1197 $params[] = array('on_hold', '=', 0, 0, 0);
1198 }
1199
1200 if ($extraParams) {
1201 $params = array_merge($params, $extraParams);
1202 }
1203
1204 // if return properties are not passed then get all return properties
1205 if (empty($returnProperties)) {
1206 $fields = array_merge(array_keys(CRM_Contact_BAO_Contact::exportableFields()),
1207 array('display_name', 'checksum', 'contact_id')
1208 );
1209 foreach ($fields as $key => $val) {
1210 $returnProperties[$val] = 1;
1211 }
1212 }
1213
1214 $custom = array();
1215 foreach ($returnProperties as $name => $dontCare) {
1216 $cfID = CRM_Core_BAO_CustomField::getKeyID($name);
1217 if ($cfID) {
1218 $custom[] = $cfID;
1219 }
1220 }
1221
1222 //get the total number of contacts to fetch from database.
1223 $numberofContacts = count($contactIDs);
1224 $query = new CRM_Contact_BAO_Query($params, $returnProperties);
1225
1226 $details = $query->apiQuery($params, $returnProperties, NULL, NULL, 0, $numberofContacts);
1227
1228 $contactDetails = &$details[0];
1229
1230 foreach ($contactIDs as $key => $contactID) {
1231 if (array_key_exists($contactID, $contactDetails)) {
1232 if (CRM_Utils_Array::value('preferred_communication_method', $returnProperties) == 1
1233 && array_key_exists('preferred_communication_method', $contactDetails[$contactID])
1234 ) {
1235 $pcm = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
1236
1237 // communication Prefferance
1238 $contactPcm = explode(CRM_Core_DAO::VALUE_SEPARATOR,
1239 $contactDetails[$contactID]['preferred_communication_method']
1240 );
1241 $result = array();
1242 foreach ($contactPcm as $key => $val) {
1243 if ($val) {
1244 $result[$val] = $pcm[$val];
1245 }
1246 }
1247 $contactDetails[$contactID]['preferred_communication_method'] = implode(', ', $result);
1248 }
1249
1250 foreach ($custom as $cfID) {
1251 if (isset($contactDetails[$contactID]["custom_{$cfID}"])) {
1252 $contactDetails[$contactID]["custom_{$cfID}"] = CRM_Core_BAO_CustomField::getDisplayValue($contactDetails[$contactID]["custom_{$cfID}"],
1253 $cfID, $details[1]
1254 );
1255 }
1256 }
1257
1258 //special case for greeting replacement
1259 foreach (array(
1260 'email_greeting', 'postal_greeting', 'addressee') as $val) {
1261 if (!empty($contactDetails[$contactID][$val])) {
1262 $contactDetails[$contactID][$val] = $contactDetails[$contactID]["{$val}_display"];
1263 }
1264 }
1265 }
1266 }
1267
1268 // also call a hook and get token details
1269 CRM_Utils_Hook::tokenValues($details[0],
1270 $contactIDs,
1271 $jobID,
1272 $tokens,
1273 $className
1274 );
1275 return $details;
1276 }
1277
1278 /**
1279 * Call hooks on tokens for anonymous users - contact id is set to 0 - this allows non-contact
1280 * specific tokens to be rendered
1281 *
1282 * @param array $contactIDs
1283 * This should always be array(0) or its not anonymous - left to keep signature same.
1284 * as main fn
1285 * @param string $returnProperties
1286 * @param bool $skipOnHold
1287 * @param bool $skipDeceased
1288 * @param string $extraParams
1289 * @param array $tokens
1290 * @param string $className
1291 * Sent as context to the hook.
1292 * @param string $jobID
1293 * @return array contactDetails with hooks swapped out
1294 */
1295 public function getAnonymousTokenDetails($contactIDs = array(
1296 0),
1297 $returnProperties = NULL,
1298 $skipOnHold = TRUE,
1299 $skipDeceased = TRUE,
1300 $extraParams = NULL,
1301 $tokens = array(),
1302 $className = NULL,
1303 $jobID = NULL) {
1304 $details = array(0 => array());
1305 // also call a hook and get token details
1306 CRM_Utils_Hook::tokenValues($details[0],
1307 $contactIDs,
1308 $jobID,
1309 $tokens,
1310 $className
1311 );
1312 return $details;
1313 }
1314
1315 /**
1316 * Gives required details of contribuion in an indexed array format so we
1317 * can iterate in a nice loop and do token evaluation
1318 *
1319 * @param array $contributionIDs
1320 * @param array $returnProperties
1321 * Of required properties.
1322 * @param array $extraParams
1323 * Extra params.
1324 * @param array $tokens
1325 * The list of tokens we've extracted from the content.
1326 * @param string $className
1327 *
1328 * @return array
1329 * @static
1330 */
1331 static function getContributionTokenDetails(
1332 $contributionIDs,
1333 $returnProperties = NULL,
1334 $extraParams = NULL,
1335 $tokens = array(),
1336 $className = NULL
1337 ) {
1338 //@todo - this function basically replications calling civicrm_api3('contribution', 'get', array('id' => array('IN' => array())
1339 if (empty($contributionIDs)) {
1340 // putting a fatal here so we can track if/when this happens
1341 CRM_Core_Error::fatal();
1342 }
1343
1344 $details = array();
1345
1346 // no apiQuery helper yet, so do a loop and find contribution by id
1347 foreach ($contributionIDs as $contributionID) {
1348
1349 $dao = new CRM_Contribute_DAO_Contribution();
1350 $dao->id = $contributionID;
1351
1352 if ($dao->find(TRUE)) {
1353
1354 $details[$dao->id] = array();
1355 CRM_Core_DAO::storeValues($dao, $details[$dao->id]);
1356
1357 // do the necessary transformation
1358 if (!empty($details[$dao->id]['payment_instrument_id'])) {
1359 $piId = $details[$dao->id]['payment_instrument_id'];
1360 $pis = CRM_Contribute_PseudoConstant::paymentInstrument();
1361 $details[$dao->id]['payment_instrument'] = $pis[$piId];
1362 }
1363 if (!empty($details[$dao->id]['campaign_id'])) {
1364 $campaignId = $details[$dao->id]['campaign_id'];
1365 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1366 $details[$dao->id]['campaign'] = $campaigns[$campaignId];
1367 }
1368
1369 if (!empty($details[$dao->id]['financial_type_id'])) {
1370 $financialtypeId = $details[$dao->id]['financial_type_id'];
1371 $ftis = CRM_Contribute_PseudoConstant::financialType();
1372 $details[$dao->id]['financial_type'] = $ftis[$financialtypeId];
1373 }
1374
1375 // TODO: call a hook to get token contribution details
1376 }
1377 }
1378
1379 return $details;
1380 }
1381
1382 /**
1383 * Get Membership Token Details
1384 * @param array $membershipIDs
1385 * Array of membership IDS.
1386 */
1387 public static function getMembershipTokenDetails($membershipIDs) {
1388 $memberships = civicrm_api3('membership', 'get', array('options' => array('limit' => 200000), 'membership_id' => array('IN' => (array) $membershipIDs)));
1389 return $memberships['values'];
1390 }
1391 /**
1392 * Replace greeting tokens exists in message/subject
1393 *
1394 */
1395 public static function replaceGreetingTokens(&$tokenString, $contactDetails = NULL, $contactId = NULL, $className = NULL, $escapeSmarty = FALSE) {
1396
1397 if (!$contactDetails && !$contactId) {
1398 return;
1399 }
1400
1401 // check if there are any tokens
1402 $greetingTokens = self::getTokens($tokenString);
1403
1404 if (!empty($greetingTokens)) {
1405 // first use the existing contact object for token replacement
1406 if (!empty($contactDetails)) {
1407 $tokenString = CRM_Utils_Token::replaceContactTokens($tokenString, $contactDetails, TRUE, $greetingTokens, TRUE, $escapeSmarty);
1408 }
1409
1410 // check if there are any unevaluated tokens
1411 $greetingTokens = self::getTokens($tokenString);
1412
1413 // $greetingTokens not empty, means there are few tokens which are not evaluated, like custom data etc
1414 // so retrieve it from database
1415 if (!empty($greetingTokens) && array_key_exists('contact', $greetingTokens)) {
1416 $greetingsReturnProperties = array_flip(CRM_Utils_Array::value('contact', $greetingTokens));
1417 $greetingsReturnProperties = array_fill_keys(array_keys($greetingsReturnProperties), 1);
1418 $contactParams = array('contact_id' => $contactId);
1419
1420 $greetingDetails = self::getTokenDetails($contactParams,
1421 $greetingsReturnProperties,
1422 FALSE, FALSE, NULL,
1423 $greetingTokens,
1424 $className
1425 );
1426
1427 // again replace tokens
1428 $tokenString = CRM_Utils_Token::replaceContactTokens($tokenString,
1429 $greetingDetails,
1430 TRUE,
1431 $greetingTokens,
1432 FALSE,
1433 $escapeSmarty
1434 );
1435 }
1436
1437 // check if there are still any unevaluated tokens
1438 $remainingTokens = self::getTokens($tokenString);
1439
1440 // contact related $greetingTokens not empty, there are customized or hook tokens to replace
1441 if (!empty($remainingTokens['contact'])) {
1442 // Fill the return properties array
1443 $greetingTokens = $remainingTokens['contact'];
1444 reset($greetingTokens);
1445 $greetingsReturnProperties = array();
1446 while (list($key) = each($greetingTokens)) {
1447 $props = array_flip(CRM_Utils_Array::value($key, $greetingTokens));
1448 $props = array_fill_keys(array_keys($props), 1);
1449 $greetingsReturnProperties = $greetingsReturnProperties + $props;
1450 }
1451 $contactParams = array('contact_id' => $contactId);
1452 $greetingDetails = self::getTokenDetails($contactParams,
1453 $greetingsReturnProperties,
1454 FALSE, FALSE, NULL,
1455 $greetingTokens,
1456 $className
1457 );
1458 // Prepare variables for calling replaceHookTokens
1459 $categories = array_keys($greetingTokens);
1460 list($contact) = $greetingDetails;
1461 // Replace tokens defined in Hooks.
1462 $tokenString = CRM_Utils_Token::replaceHookTokens($tokenString, $contact[$contactId], $categories);
1463 }
1464 }
1465 }
1466
1467 /**
1468 * @param $tokens
1469 *
1470 * @return array
1471 */
1472 public static function flattenTokens(&$tokens) {
1473 $flattenTokens = array();
1474
1475 foreach (array(
1476 'html', 'text', 'subject') as $prop) {
1477 if (!isset($tokens[$prop])) {
1478 continue;
1479 }
1480 foreach ($tokens[$prop] as $type => $names) {
1481 if (!isset($flattenTokens[$type])) {
1482 $flattenTokens[$type] = array();
1483 }
1484 foreach ($names as $name) {
1485 $flattenTokens[$type][$name] = 1;
1486 }
1487 }
1488 }
1489
1490 return $flattenTokens;
1491 }
1492
1493 /**
1494 * Replace all user tokens in $str
1495 *
1496 * @param string $str
1497 * The string with tokens to be replaced.
1498 *
1499 * @param null $knownTokens
1500 * @param bool $escapeSmarty
1501 *
1502 * @return string The processed string
1503 * @static
1504 */
1505 public static function &replaceUserTokens($str, $knownTokens = NULL, $escapeSmarty = FALSE) {
1506 $key = 'user';
1507 if (!$knownTokens ||
1508 !isset($knownTokens[$key])
1509 ) {
1510 return $str;
1511 }
1512
1513 $str = preg_replace_callback(
1514 self::tokenRegex($key),
1515 function ($matches) use($escapeSmarty) {
1516 return CRM_Utils_Token::getUserTokenReplacement($matches[1], $escapeSmarty);
1517 },
1518 $str
1519 );
1520 return $str;
1521 }
1522
1523 /**
1524 * @param $token
1525 * @param bool $escapeSmarty
1526 *
1527 * @return string
1528 */
1529 public static function getUserTokenReplacement($token, $escapeSmarty = FALSE) {
1530 $value = '';
1531
1532 list($objectName, $objectValue) = explode('-', $token, 2);
1533
1534 switch ($objectName) {
1535 case 'permission':
1536 $value = CRM_Core_Permission::permissionEmails($objectValue);
1537 break;
1538
1539 case 'role':
1540 $value = CRM_Core_Permission::roleEmails($objectValue);
1541 break;
1542 }
1543
1544 if ($escapeSmarty) {
1545 $value = self::tokenEscapeSmarty($value);
1546 }
1547
1548 return $value;
1549 }
1550
1551 /**
1552 *
1553 */
1554 protected static function _buildContributionTokens() {
1555 $key = 'contribution';
1556 if (self::$_tokens[$key] == NULL) {
1557 self::$_tokens[$key] = array_keys(array_merge(CRM_Contribute_BAO_Contribution::exportableFields('All'),
1558 array('campaign', 'financial_type')
1559 ));
1560 }
1561 }
1562
1563 /**
1564 * Store membership tokens on the static _tokens array
1565 */
1566 protected static function _buildMembershipTokens() {
1567 $key = 'membership';
1568 if (!isset(self::$_tokens[$key]) || self::$_tokens[$key] == NULL) {
1569 $membershipTokens = array();
1570 $tokens = CRM_Core_SelectValues::membershipTokens();
1571 foreach ($tokens as $token => $dontCare) {
1572 $membershipTokens[] = substr($token, (strpos($token, '.') + 1), -1);
1573 }
1574 self::$_tokens[$key] = $membershipTokens;
1575 }
1576 }
1577
1578 /**
1579 * Replace tokens for an entity
1580 * @param string $entity
1581 * @param array $entityArray
1582 * (e.g. in format from api).
1583 * @param string $str
1584 * String to replace in.
1585 * @param array $knownTokens
1586 * Array of tokens present.
1587 * @param bool $escapeSmarty
1588 * @return string string with replacements made
1589 */
1590 public static function replaceEntityTokens($entity, $entityArray, $str, $knownTokens = array(), $escapeSmarty = FALSE) {
1591 if (!$knownTokens || empty($knownTokens[$entity])) {
1592 return $str;
1593 }
1594
1595 $fn = 'get' . ucfirst($entity) . 'tokenReplacement';
1596 //since we already know the tokens lets just use them & do str_replace which is faster & simpler than preg_replace
1597 foreach ($knownTokens[$entity] as $token) {
1598 $replaceMent = CRM_Utils_Token::$fn($token, $entityArray, $escapeSmarty);
1599 $str = str_replace('{' . $entity . '.' . $token . '}', $replaceMent, $str);
1600 }
1601 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1602 return $str;
1603 }
1604
1605 /**
1606 * Replace Contribution tokens in html
1607 *
1608 * @param string $str
1609 * @param array $contribution
1610 * @param bool|string $html
1611 * @param string $knownTokens
1612 * @param bool|string $escapeSmarty
1613 *
1614 * @return unknown|Ambigous <string, mixed>|mixed
1615 */
1616 public static function replaceContributionTokens($str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1617 $key = 'contribution';
1618 if (!$knownTokens || !CRM_Utils_Array::value($key, $knownTokens)) {
1619 return $str; //early return
1620 }
1621 self::_buildContributionTokens();
1622
1623 // here we intersect with the list of pre-configured valid tokens
1624 // so that we remove anything we do not recognize
1625 // I hope to move this step out of here soon and
1626 // then we will just iterate on a list of tokens that are passed to us
1627
1628 $str = preg_replace_callback(
1629 self::tokenRegex($key),
1630 function ($matches) use(&$contribution, $html, $escapeSmarty) {
1631 return CRM_Utils_Token::getContributionTokenReplacement($matches[1], $contribution, $html, $escapeSmarty);
1632 },
1633 $str
1634 );
1635
1636 $str = preg_replace('/\\\\|\{(\s*)?\}/', ' ', $str);
1637 return $str;
1638 }
1639
1640 /**
1641 * We have a situation where we are rendering more than one token in each field because we are combining
1642 * tokens from more than one contribution when pdf thank you letters are grouped (CRM-14367)
1643 *
1644 * The replaceContributionToken doesn't handle receive_date correctly in this scenario because of the formatting
1645 * it applies (other tokens are OK including date fields)
1646 *
1647 * So we sort this out & then call the main function. Note that we are not escaping smarty on this fields like the main function
1648 * does - but the fields is already being formatted through a date function
1649 *
1650 * @param string $separator
1651 * @param string $str
1652 * @param array $contribution
1653 * @param bool|string $html
1654 * @param string $knownTokens
1655 * @param bool|string $escapeSmarty
1656 *
1657 * @return \Ambigous|mixed|string|\unknown
1658 */
1659 public static function replaceMultipleContributionTokens($separator, $str, &$contribution, $html = FALSE, $knownTokens = NULL, $escapeSmarty = FALSE) {
1660 if (empty($knownTokens['contribution'])) {
1661 return $str;
1662 }
1663
1664 if (in_array('receive_date', $knownTokens['contribution'])) {
1665 $formattedDates = array();
1666 $dates = explode($separator, $contribution['receive_date']);
1667 foreach ($dates as $date) {
1668 $formattedDates[] = CRM_Utils_Date::customFormat($date, NULL, array('j', 'm', 'Y'));
1669 }
1670 $str = str_replace("{contribution.receive_date}", implode($separator, $formattedDates), $str);
1671 unset($knownTokens['contribution']['receive_date']);
1672 }
1673 return self::replaceContributionTokens($str, $contribution, $html, $knownTokens, $escapeSmarty);
1674 }
1675
1676 /**
1677 * Get replacement strings for any membership tokens (only a small number of tokens are implemnted in the first instance
1678 * - this is used by the pdfLetter task from membership search
1679 * @param string $token
1680 * @param array $membership
1681 * An api result array for a single membership.
1682 * @param bool $escapeSmarty
1683 * @return string token replacement
1684 */
1685 public static function getMembershipTokenReplacement($token, $membership, $escapeSmarty = FALSE) {
1686 $entity = 'membership';
1687 self::_buildMembershipTokens();
1688 switch ($token) {
1689 case 'type':
1690 $value = $membership['membership_name'];
1691 break;
1692
1693 case 'status':
1694 $statuses = CRM_Member_BAO_Membership::buildOptions('status_id');
1695 $value = $statuses[$membership['status_id']];
1696 break;
1697
1698 case 'fee':
1699 try {
1700 $value = civicrm_api3('membership_type', 'getvalue', array('id' => $membership['membership_type_id'], 'return' => 'minimum_fee'));
1701 }
1702 catch (CiviCRM_API3_Exception $e) {
1703 // we can anticipate we will get an error if the minimum fee is set to 'NULL' because of the way the
1704 // api handles NULL (4.4)
1705 $value = 0;
1706 }
1707 break;
1708
1709 default:
1710 if (in_array($token, self::$_tokens[$entity])) {
1711 $value = $membership[$token];
1712 }
1713 else {
1714 //ie unchanged
1715 $value = "{$entity}.{$token}";
1716 }
1717 break;
1718 }
1719
1720 if ($escapeSmarty) {
1721 $value = self::tokenEscapeSmarty($value);
1722 }
1723 return $value;
1724 }
1725
1726 /**
1727 * @param $token
1728 * @param $contribution
1729 * @param bool $html
1730 * @param bool $escapeSmarty
1731 *
1732 * @return mixed|string
1733 */
1734 public static function getContributionTokenReplacement($token, &$contribution, $html = FALSE, $escapeSmarty = FALSE) {
1735 self::_buildContributionTokens();
1736
1737 switch ($token) {
1738 case 'total_amount':
1739 case 'net_amount':
1740 case 'fee_amount':
1741 case 'non_deductible_amount':
1742 $value = CRM_Utils_Money::format(CRM_Utils_Array::retrieveValueRecursive($contribution, $token));
1743 break;
1744
1745 case 'receive_date':
1746 $value = CRM_Utils_Array::retrieveValueRecursive($contribution, $token);
1747 $value = CRM_Utils_Date::customFormat($value, NULL, array('j', 'm', 'Y'));
1748 break;
1749
1750 default:
1751 if (!in_array($token, self::$_tokens['contribution'])) {
1752 $value = "{contribution.$token}";
1753 }
1754 else {
1755 $value = CRM_Utils_Array::retrieveValueRecursive($contribution, $token);
1756 }
1757 break;
1758 }
1759
1760 if ($escapeSmarty) {
1761 $value = self::tokenEscapeSmarty($value);
1762 }
1763 return $value;
1764 }
1765
1766 /**
1767 * @return array: legacy_token => new_token
1768 */
1769 public static function legacyContactTokens() {
1770 return array(
1771 'individual_prefix' => 'prefix_id',
1772 'individual_suffix' => 'suffix_id',
1773 'gender' => 'gender_id',
1774 'communication_style' => 'communication_style_id',
1775 );
1776 }
1777
1778 /**
1779 * Formats a token list for the select2 widget
1780 * @param $tokens
1781 * @return array
1782 */
1783 public static function formatTokensForDisplay($tokens) {
1784 $sorted = $output = array();
1785
1786 // Sort in ascending order by ignoring word case
1787 natcasesort($tokens);
1788
1789 // Attempt to place tokens into optgroups
1790 // TODO: These groupings could be better and less hackish. Getting them pre-grouped from upstream would be nice.
1791 foreach ($tokens as $k => $v) {
1792 // Check to see if this token is already in a group e.g. for custom fields
1793 $split = explode(' :: ', $v);
1794 if (!empty($split[1])) {
1795 $sorted[$split[1]][] = array('id' => $k, 'text' => $split[0]);
1796 }
1797 // Group by entity
1798 else {
1799 $split = explode('.', trim($k, '{}'));
1800 if (isset($split[1])) {
1801 $entity = array_key_exists($split[1], CRM_Core_DAO_Address::export()) ? 'Address' : ucfirst($split[0]);
1802 }
1803 else {
1804 $entity = 'Contact';
1805 }
1806 $sorted[ts($entity)][] = array('id' => $k, 'text' => $v);
1807 }
1808 }
1809
1810 ksort($sorted);
1811 foreach ($sorted as $k => $v) {
1812 $output[] = array('text' => $k, 'children' => $v);
1813 }
1814
1815 return $output;
1816 }
1817 }