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