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