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