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