Merge pull request #21799 from eileenmcnaughton/refs
[civicrm-core.git] / CRM / Contribute / Form / Task / PDFLetter.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035 11
31f2ebac
EM
12use Civi\Token\TokenProcessor;
13
6a488035
TO
14/**
15 *
16 * @package CRM
ca5cec67 17 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
18 */
19
20/**
07f8d162 21 * This class provides the functionality to create PDF letter for a group of contacts or a single contact.
6a488035
TO
22 */
23class CRM_Contribute_Form_Task_PDFLetter extends CRM_Contribute_Form_Task {
24
fc34a273
EM
25 use CRM_Contact_Form_Task_PDFTrait;
26
6a488035 27 /**
fe482240 28 * All the existing templates in the system.
6a488035
TO
29 *
30 * @var array
31 */
32 public $_templates = NULL;
33
34 public $_single = NULL;
35
36 public $_cid = NULL;
37
38 /**
fe482240 39 * Build all the data structures needed to build the form.
ed106721 40 */
00be9182 41 public function preProcess() {
6a488035 42 $this->skipOnHold = $this->skipDeceased = FALSE;
c97bfeff 43 $this->preProcessPDF();
1a90603e 44 parent::preProcess();
45 $this->assign('single', $this->isSingle());
6a488035
TO
46 }
47
186c9c17
EM
48 /**
49 * This virtual function is used to set the default values of
50 * various form elements
51 *
52 * access public
53 *
a6c01b45
CW
54 * @return array
55 * reference to the array of default values
186c9c17 56 */
1330f57a 57
186c9c17
EM
58 /**
59 * @return array
60 */
00be9182 61 public function setDefaultValues() {
fc34a273 62 $defaults = $this->getPDFDefaultValues();
6a488035 63 if (isset($this->_activityId)) {
be2fb01f 64 $params = ['id' => $this->_activityId];
6a488035 65 CRM_Activity_BAO_Activity::retrieve($params, $defaults);
9c1bc317 66 $defaults['html_message'] = $defaults['details'] ?? NULL;
6a488035 67 }
b5fd2bef
CW
68 else {
69 $defaults['thankyou_update'] = 1;
70 }
6a488035
TO
71 return $defaults;
72 }
73
74 /**
fe482240 75 * Build the form object.
053c1a4b
EM
76 *
77 * @throws \CRM_Core_Exception
6a488035
TO
78 */
79 public function buildQuickForm() {
80 //enable form element
81 $this->assign('suppressForm', FALSE);
82
b701d2e5 83 // Contribute PDF tasks allow you to email as well, so we need to add email address to those forms
84 $this->add('select', 'from_email_address', ts('From Email Address'), $this->_fromEmails, TRUE);
053c1a4b 85 $this->addPDFElementsToForm();
6a488035
TO
86
87 // specific need for contributions
383c047b 88 $this->add('static', 'more_options_header', NULL, ts('Thank-you Letter Options'));
6a488035
TO
89 $this->add('checkbox', 'receipt_update', ts('Update receipt dates for these contributions'), FALSE);
90 $this->add('checkbox', 'thankyou_update', ts('Update thank-you dates for these contributions'), FALSE);
6a488035
TO
91
92 // Group options for tokens are not yet implemented. dgg
be2fb01f 93 $options = [
383c047b
DG
94 '' => ts('- no grouping -'),
95 'contact_id' => ts('Contact'),
96 'contribution_recur_id' => ts('Contact and Recurring'),
97 'financial_type_id' => ts('Contact and Financial Type'),
98 'campaign_id' => ts('Contact and Campaign'),
536f0e02 99 'payment_instrument_id' => ts('Contact and Payment Method'),
be2fb01f
CW
100 ];
101 $this->addElement('select', 'group_by', ts('Group contributions by'), $options, [], "<br/>", FALSE);
383c047b 102 // this was going to be free-text but I opted for radio options in case there was a script injection risk
be2fb01f 103 $separatorOptions = ['comma' => 'Comma', 'td' => 'Horizontal Table Cell', 'tr' => 'Vertical Table Cell', 'br' => 'Line Break'];
698253db 104
383c047b 105 $this->addElement('select', 'group_by_separator', ts('Separator (grouped contributions)'), $separatorOptions);
be2fb01f 106 $emailOptions = [
383c047b
DG
107 '' => ts('Generate PDFs for printing (only)'),
108 'email' => ts('Send emails where possible. Generate printable PDFs for contacts who cannot receive email.'),
109 'both' => ts('Send emails where possible. Generate printable PDFs for all contacts.'),
be2fb01f 110 ];
353ffa53 111 if (CRM_Core_Config::singleton()->doNotAttachPDFReceipt) {
97eaa51b
EM
112 $emailOptions['pdfemail'] = ts('Send emails with an attached PDF where possible. Generate printable PDFs for contacts who cannot receive email.');
113 $emailOptions['pdfemail_both'] = ts('Send emails with an attached PDF where possible. Generate printable PDFs for all contacts.');
114 }
be2fb01f 115 $this->addElement('select', 'email_options', ts('Print and email options'), $emailOptions, [], "<br/>", FALSE);
ed106721 116
f336046d 117 $this->addButtons($this->getButtons());
6a488035
TO
118
119 }
120
f336046d
EM
121 /**
122 * Get the name for the main submit button.
123 *
124 * @return string
125 */
126 protected function getMainSubmitButtonName(): string {
127 return ts('Make Thank-you Letters');
128 }
129
6a488035 130 /**
fe482240 131 * Process the form after the input has been submitted and validated.
9da59513 132 *
133 * @throws \CRM_Core_Exception
cf56c730 134 * @throws \CiviCRM_API3_Exception
6a488035
TO
135 */
136 public function postProcess() {
9be8686d 137 $formValues = $this->controller->exportValues($this->getName());
31f2ebac
EM
138 [$formValues, $html_message] = $this->processMessageTemplate($formValues);
139
140 $messageToken = CRM_Utils_Token::getTokens($html_message);
141
142 $returnProperties = [];
143 if (isset($messageToken['contact'])) {
144 foreach ($messageToken['contact'] as $key => $value) {
145 $returnProperties[$value] = 1;
146 }
147 }
148
b701d2e5 149 $isPDF = FALSE;
150 $emailParams = [];
151 if (!empty($formValues['email_options'])) {
152 $returnProperties['email'] = $returnProperties['on_hold'] = $returnProperties['is_deceased'] = $returnProperties['do_not_email'] = 1;
153 $emailParams = [
154 'subject' => $formValues['subject'] ?? NULL,
155 'from' => $formValues['from_email_address'] ?? NULL,
156 ];
157
158 $emailParams['from'] = CRM_Utils_Mail::formatFromAddress($emailParams['from']);
159
160 // We need display_name for emailLetter() so add to returnProperties here
161 $returnProperties['display_name'] = 1;
162 if (stristr($formValues['email_options'], 'pdfemail')) {
163 $isPDF = TRUE;
164 }
165 }
166 // update dates ?
167 $receipt_update = $formValues['receipt_update'] ?? FALSE;
168 $thankyou_update = $formValues['thankyou_update'] ?? FALSE;
169 $nowDate = date('YmdHis');
170 $receipts = $thanks = $emailed = 0;
171 $updateStatus = '';
172 $task = 'CRM_Contribution_Form_Task_PDFLetterCommon';
173 $realSeparator = ', ';
174 $tableSeparators = [
175 'td' => '</td><td>',
176 'tr' => '</td></tr><tr><td>',
177 ];
178 //the original thinking was mutliple options - but we are going with only 2 (comma & td) for now in case
179 // there are security (& UI) issues we need to think through
180 if (isset($formValues['group_by_separator'])) {
181 if (in_array($formValues['group_by_separator'], ['td', 'tr'])) {
182 $realSeparator = $tableSeparators[$formValues['group_by_separator']];
183 }
184 elseif ($formValues['group_by_separator'] == 'br') {
185 $realSeparator = "<br />";
186 }
187 }
188 // a placeholder in case the separator is common in the string - e.g ', '
189 $separator = '****~~~~';
9da59513 190 $groupBy = $this->getSubmittedValue('group_by');
b701d2e5 191
192 // skip some contacts ?
3467497b 193 $skipOnHold = $this->skipOnHold ?? FALSE;
194 $skipDeceased = $this->skipDeceased ?? TRUE;
9da59513 195 $contributionIDs = $this->getIDs();
3467497b 196 if ($this->isQueryIncludesSoftCredits()) {
b701d2e5 197 $contributionIDs = [];
3467497b 198 $result = $this->getSearchQueryResults();
b701d2e5 199 while ($result->fetch()) {
3467497b 200 $this->_contactIds[$result->contact_id] = $result->contact_id;
b701d2e5 201 $contributionIDs["{$result->contact_id}-{$result->contribution_id}"] = $result->contribution_id;
202 }
203 }
3467497b 204 [$contributions, $contacts] = $this->buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $this->isQueryIncludesSoftCredits());
b701d2e5 205 $html = [];
206 $contactHtml = $emailedHtml = [];
207 foreach ($contributions as $contributionId => $contribution) {
208 $contact = &$contacts[$contribution['contact_id']];
209 $grouped = FALSE;
210 $groupByID = 0;
211 if ($groupBy) {
212 $groupByID = empty($contribution[$groupBy]) ? 0 : $contribution[$groupBy];
213 $contribution = $contact['combined'][$groupBy][$groupByID];
214 $grouped = TRUE;
215 }
216
217 if (empty($groupBy) || empty($contact['is_sent'][$groupBy][$groupByID])) {
3467497b 218 $html[$contributionId] = $this->generateHtml($contact, $contribution, $groupBy, $contributions, $realSeparator, $tableSeparators, $messageToken, $html_message, $separator, $grouped, $groupByID);
b701d2e5 219 $contactHtml[$contact['contact_id']][] = $html[$contributionId];
f336046d 220 if ($this->isSendEmails()) {
3467497b 221 if ($this->emailLetter($contact, $html[$contributionId], $isPDF, $formValues, $emailParams)) {
b701d2e5 222 $emailed++;
223 if (!stristr($formValues['email_options'], 'both')) {
224 $emailedHtml[$contributionId] = TRUE;
225 }
226 }
227 }
228 $contact['is_sent'][$groupBy][$groupByID] = TRUE;
229 }
f336046d
EM
230 if ($this->isLiveMode()) {
231 // Update receipt/thankyou dates
232 $contributionParams = ['id' => $contributionId];
233 if ($receipt_update) {
234 $contributionParams['receipt_date'] = $nowDate;
235 }
236 if ($thankyou_update) {
237 $contributionParams['thankyou_date'] = $nowDate;
238 }
239 if ($receipt_update || $thankyou_update) {
240 civicrm_api3('Contribution', 'create', $contributionParams);
241 $receipts = ($receipt_update ? $receipts + 1 : $receipts);
242 $thanks = ($thankyou_update ? $thanks + 1 : $thanks);
243 }
b701d2e5 244 }
245 }
246
247 $contactIds = array_keys($contacts);
f336046d
EM
248 // CRM-16725 Skip creation of activities if user is previewing their PDF letter(s)
249 if ($this->isLiveMode()) {
2537798f 250 $this->createActivities($html_message, $contactIds, CRM_Utils_Array::value('subject', $formValues, ts('Thank you letter')), CRM_Utils_Array::value('campaign_id', $formValues), $contactHtml);
f336046d 251 }
b701d2e5 252 $html = array_diff_key($html, $emailedHtml);
253
b701d2e5 254 //CRM-19761
255 if (!empty($html)) {
7c0d6f7a 256 $fileName = $this->getFileName();
ba7ea395
JF
257 if ($this->getSubmittedValue('document_type') === 'pdf') {
258 CRM_Utils_PDF_Utils::html2pdf($html, $fileName . '.pdf', FALSE, $formValues);
b701d2e5 259 }
260 else {
ba7ea395 261 CRM_Utils_PDF_Document::html2doc($html, $fileName . '.' . $this->getSubmittedValue('document_type'), $formValues);
b701d2e5 262 }
263 }
264
3467497b 265 $this->postProcessHook();
b701d2e5 266
267 if ($emailed) {
268 $updateStatus = ts('Receipts have been emailed to %1 contributions.', [1 => $emailed]);
269 }
270 if ($receipts) {
271 $updateStatus = ts('Receipt date has been updated for %1 contributions.', [1 => $receipts]);
272 }
273 if ($thanks) {
274 $updateStatus .= ' ' . ts('Thank-you date has been updated for %1 contributions.', [1 => $thanks]);
275 }
276
277 if ($updateStatus) {
278 CRM_Core_Session::setStatus($updateStatus);
279 }
280 if (!empty($html)) {
281 // ie. we have only sent emails - lets no show a white screen
282 CRM_Utils_System::civiExit();
283 }
6a488035 284 }
96025800 285
f336046d
EM
286 /**
287 * Are emails to be sent out?
288 *
289 * @return bool
290 */
291 protected function isSendEmails(): bool {
292 return $this->isLiveMode() && $this->getSubmittedValue('email_options');
293 }
294
5ec6b0ad 295 /**
601c941f 296 * Get the token processor schema required to list any tokens for this task.
5ec6b0ad
TM
297 *
298 * @return array
299 */
601c941f
EM
300 public function getTokenSchema(): array {
301 return ['contributionId', 'contactId'];
5ec6b0ad
TM
302 }
303
01a5461d 304 /**
305 * Generate the contribution array from the form, we fill in the contact details and determine any aggregation
306 * around contact_id of contribution_recur_id
307 *
308 * @param string $groupBy
309 * @param array $contributionIDs
310 * @param array $returnProperties
311 * @param bool $skipOnHold
312 * @param bool $skipDeceased
313 * @param array $messageToken
314 * @param string $task
315 * @param string $separator
316 * @param bool $isIncludeSoftCredits
317 *
318 * @return array
319 */
3467497b 320 public function buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $isIncludeSoftCredits) {
01a5461d 321 $contributions = $contacts = [];
322 foreach ($contributionIDs as $item => $contributionId) {
323 $contribution = CRM_Contribute_BAO_Contribution::getContributionTokenValues($contributionId, $messageToken)['values'][$contributionId];
324 $contribution['campaign'] = $contribution['contribution_campaign_title'] ?? NULL;
325 $contributions[$contributionId] = $contribution;
326
327 if ($isIncludeSoftCredits) {
328 //@todo find out why this happens & add comments
329 [$contactID] = explode('-', $item);
330 $contactID = (int) $contactID;
331 }
332 else {
333 $contactID = $contribution['contact_id'];
334 }
335 if (!isset($contacts[$contactID])) {
336 $contacts[$contactID] = [];
337 $contacts[$contactID]['contact_aggregate'] = 0;
338 $contacts[$contactID]['combined'] = $contacts[$contactID]['contribution_ids'] = [];
339 }
340
341 $contacts[$contactID]['contact_aggregate'] += $contribution['total_amount'];
342 $groupByID = empty($contribution[$groupBy]) ? 0 : $contribution[$groupBy];
343
344 $contacts[$contactID]['contribution_ids'][$groupBy][$groupByID][$contributionId] = TRUE;
345 if (!isset($contacts[$contactID]['combined'][$groupBy]) || !isset($contacts[$contactID]['combined'][$groupBy][$groupByID])) {
346 $contacts[$contactID]['combined'][$groupBy][$groupByID] = $contribution;
347 $contacts[$contactID]['aggregates'][$groupBy][$groupByID] = $contribution['total_amount'];
348 }
349 else {
350 $contacts[$contactID]['combined'][$groupBy][$groupByID] = self::combineContributions($contacts[$contactID]['combined'][$groupBy][$groupByID], $contribution, $separator);
351 $contacts[$contactID]['aggregates'][$groupBy][$groupByID] += $contribution['total_amount'];
352 }
353 }
354 // Assign the available contributions before calling tokens so hooks parsing smarty can access it.
355 // Note that in core code you can only use smarty here if enable if for the whole site, incl
356 // CiviMail, with a big performance impact.
357 // Hooks allow more nuanced smarty usage here.
358 CRM_Core_Smarty::singleton()->assign('contributions', $contributions);
359 foreach ($contacts as $contactID => $contact) {
360 [$tokenResolvedContacts] = CRM_Utils_Token::getTokenDetails(['contact_id' => $contactID],
361 $returnProperties,
362 $skipOnHold,
363 $skipDeceased,
364 NULL,
365 $messageToken,
366 $task
367 );
368 $contacts[$contactID] = array_merge($tokenResolvedContacts[$contactID], $contact);
369 }
370 return [$contributions, $contacts];
371 }
372
373 /**
374 * We combine the contributions by adding the contribution to each field with the separator in
375 * between the existing value and the new one. We put the separator there even if empty so it is clear what the
376 * value for previous contributions was
377 *
378 * @param array $existing
379 * @param array $contribution
380 * @param string $separator
381 *
382 * @return array
383 */
384 public static function combineContributions($existing, $contribution, $separator) {
385 foreach ($contribution as $field => $value) {
386 $existing[$field] = isset($existing[$field]) ? $existing[$field] . $separator : '';
387 $existing[$field] .= $value;
388 }
389 return $existing;
390 }
391
392 /**
393 * We are going to retrieve the combined contribution and if smarty mail is enabled we
394 * will also assign an array of contributions for this contact to the smarty template
395 *
396 * @param array $contact
397 * @param array $contributions
398 * @param $groupBy
399 * @param int $groupByID
400 */
401 public static function assignCombinedContributionValues($contact, $contributions, $groupBy, $groupByID) {
402 CRM_Core_Smarty::singleton()->assign('contact_aggregate', $contact['contact_aggregate']);
403 CRM_Core_Smarty::singleton()
404 ->assign('contributions', $contributions);
405 CRM_Core_Smarty::singleton()->assign('contribution_aggregate', $contact['aggregates'][$groupBy][$groupByID]);
406 }
407
408 /**
409 * @param $contact
410 * @param $formValues
411 * @param $contribution
412 * @param $groupBy
413 * @param $contributions
414 * @param $realSeparator
415 * @param $tableSeparators
416 * @param $messageToken
417 * @param $html_message
418 * @param $separator
419 * @param $categories
420 * @param bool $grouped
421 * @param int $groupByID
422 *
423 * @return string
424 * @throws \CRM_Core_Exception
425 */
3467497b 426 public function generateHtml(&$contact, $contribution, $groupBy, $contributions, $realSeparator, $tableSeparators, $messageToken, $html_message, $separator, $grouped, $groupByID) {
01a5461d 427 static $validated = FALSE;
428 $html = NULL;
429
430 $groupedContributions = array_intersect_key($contributions, $contact['contribution_ids'][$groupBy][$groupByID]);
431 CRM_Contribute_Form_Task_PDFLetter::assignCombinedContributionValues($contact, $groupedContributions, $groupBy, $groupByID);
432
433 if (empty($groupBy) || empty($contact['is_sent'][$groupBy][$groupByID])) {
b701d2e5 434 if (!$validated && in_array($realSeparator, $tableSeparators) && !CRM_Contribute_Form_Task_PDFLetter::isValidHTMLWithTableSeparator($messageToken, $html_message)) {
01a5461d 435 $realSeparator = ', ';
436 CRM_Core_Session::setStatus(ts('You have selected the table cell separator, but one or more token fields are not placed inside a table cell. This would result in invalid HTML, so comma separators have been used instead.'));
437 }
438 $validated = TRUE;
31f2ebac 439 $html = str_replace($separator, $realSeparator, $this->resolveTokens($html_message, $contact, $contribution['id'], $grouped, $separator, $groupedContributions));
01a5461d 440 }
441
442 return $html;
443 }
444
9be8686d 445 /**
446 * Send pdf by email.
447 *
448 * @param array $contact
449 * @param string $html
450 *
451 * @param $is_pdf
452 * @param array $format
453 * @param array $params
454 *
455 * @return bool
456 */
3467497b 457 public function emailLetter($contact, $html, $is_pdf, $format = [], $params = []) {
9be8686d 458 try {
459 if (empty($contact['email'])) {
460 return FALSE;
461 }
462 $mustBeEmpty = ['do_not_email', 'is_deceased', 'on_hold'];
463 foreach ($mustBeEmpty as $emptyField) {
464 if (!empty($contact[$emptyField])) {
465 return FALSE;
466 }
467 }
468
469 $defaults = [
470 'toName' => $contact['display_name'],
471 'toEmail' => $contact['email'],
472 'text' => '',
473 'html' => $html,
474 ];
475 if (empty($params['from'])) {
476 $emails = CRM_Core_BAO_Email::getFromEmail();
477 $emails = array_keys($emails);
478 $defaults['from'] = array_pop($emails);
479 }
480 else {
481 $defaults['from'] = $params['from'];
482 }
483 if (!empty($params['subject'])) {
484 $defaults['subject'] = $params['subject'];
485 }
486 else {
487 $defaults['subject'] = ts('Thank you for your contribution/s');
488 }
489 if ($is_pdf) {
490 $defaults['html'] = ts('Please see attached');
491 $defaults['attachments'] = [CRM_Utils_Mail::appendPDF('ThankYou.pdf', $html, $format)];
492 }
493 $params = array_merge($defaults);
494 return CRM_Utils_Mail::send($params);
495 }
496 catch (CRM_Core_Exception $e) {
497 return FALSE;
498 }
499 }
500
501 /**
502 * Check that the token only appears in a table cell. The '</td><td>' separator cannot otherwise work
503 * Calculate the number of times it appears IN the cell & the number of times it appears - should be the same!
504 *
505 * @param string $token
506 * @param string $entity
507 * @param string $textToSearch
508 *
509 * @return bool
510 */
511 public static function isHtmlTokenInTableCell($token, $entity, $textToSearch) {
512 $tokenToMatch = $entity . '\.' . $token;
513 $pattern = '|<td(?![\w-])((?!</td>).)*\{' . $tokenToMatch . '\}.*?</td>|si';
514 $within = preg_match_all($pattern, $textToSearch);
515 $total = preg_match_all("|{" . $tokenToMatch . "}|", $textToSearch);
516 return ($within == $total);
517 }
518
b701d2e5 519 /**
520 * Check whether any of the tokens exist in the html outside a table cell.
521 * If they do the table cell separator is not supported (return false)
522 * At this stage we are only anticipating contributions passed in this way but
523 * it would be easy to add others
524 * @param $tokens
525 * @param $html
526 *
527 * @return bool
528 */
529 public static function isValidHTMLWithTableSeparator($tokens, $html) {
530 $relevantEntities = ['contribution'];
531 foreach ($relevantEntities as $entity) {
532 if (isset($tokens[$entity]) && is_array($tokens[$entity])) {
533 foreach ($tokens[$entity] as $token) {
534 if (!CRM_Contribute_Form_Task_PDFLetter::isHtmlTokenInTableCell($token, $entity, $html)) {
535 return FALSE;
536 }
537 }
538 }
539 }
540 return TRUE;
541 }
542
12d88807 543 /**
544 *
545 * @param string $html_message
546 * @param array $contact
31f2ebac 547 * @param int $contributionID
12d88807 548 * @param bool $grouped
549 * Does this letter represent more than one contribution.
550 * @param string $separator
551 * What is the preferred letter separator.
552 * @param array $contributions
553 *
554 * @return string
555 */
31f2ebac 556 protected function resolveTokens(string $html_message, $contact, $contributionID, $grouped, $separator, $contributions): string {
82430f99
TO
557 $tokenContext = [
558 'smarty' => (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY),
559 'contactId' => $contact['contact_id'],
31f2ebac 560 'schema' => ['contributionId'],
82430f99 561 ];
9a88bc66 562 if ($grouped) {
31f2ebac
EM
563 // First replace the contribution tokens. These are pretty ... special.
564 // if the text looks like `<td>{contribution.currency} {contribution.total_amount}</td>'
565 // and there are 2 rows with a currency separator of
566 // you wind up with a string like
567 // '<td>USD</td><td>USD></td> <td>$50</td><td>$89</td>
568 // see https://docs.civicrm.org/user/en/latest/contributions/manual-receipts-and-thank-yous/#grouped-contribution-thank-you-letters
569 $tokenProcessor = new TokenProcessor(\Civi::dispatcher(), $tokenContext);
570 $contributionTokens = CRM_Utils_Token::getTokens($html_message)['contribution'] ?? [];
571 foreach ($contributionTokens as $token) {
572 $tokenProcessor->addMessage($token, '{contribution.' . $token . '}', 'text/html');
573 }
574
575 foreach ($contributions as $contribution) {
576 $tokenProcessor->addRow([
577 'contributionId' => $contribution['id'],
578 'contribution' => $contribution,
579 ]);
580 }
581 $tokenProcessor->evaluate();
582 $resolvedTokens = [];
583 foreach ($contributionTokens as $token) {
584 foreach ($tokenProcessor->getRows() as $row) {
585 $resolvedTokens[$token][$row->context['contributionId']] = $row->render($token);
586 }
587 // We've resolved the value for each row - resorting to swapping them out
588 // with the old function.
589 $html_message = CRM_Utils_Token::token_replace('contribution', $token, implode($separator, $resolvedTokens[$token]), $html_message);
590 }
9a88bc66 591 }
31f2ebac
EM
592 $tokenContext['contributionId'] = $contributionID;
593 return CRM_Core_TokenSmarty::render(['html' => $html_message], $tokenContext)['html'];
12d88807 594 }
595
6a488035 596}