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