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