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