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