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