3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 |
9 +--------------------------------------------------------------------+
12 use Civi\Token\TokenProcessor
;
17 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 * This class provides the functionality to create PDF letter for a group of contacts or a single contact.
23 class CRM_Contribute_Form_Task_PDFLetter
extends CRM_Contribute_Form_Task
{
25 use CRM_Contact_Form_Task_PDFTrait
;
28 * All the existing templates in the system.
32 public $_templates = NULL;
34 public $_single = NULL;
39 * Build all the data structures needed to build the form.
41 public function preProcess() {
42 $this->skipOnHold
= $this->skipDeceased
= FALSE;
43 $this->preProcessPDF();
45 $this->assign('single', $this->isSingle());
49 * This virtual function is used to set the default values of
50 * various form elements
55 * reference to the array of default values
61 public function setDefaultValues() {
62 $defaults = $this->getPDFDefaultValues();
63 if (isset($this->_activityId
)) {
64 $params = ['id' => $this->_activityId
];
65 CRM_Activity_BAO_Activity
::retrieve($params, $defaults);
66 $defaults['html_message'] = $defaults['details'] ??
NULL;
69 $defaults['thankyou_update'] = 1;
75 * Build the form object.
77 * @throws \CRM_Core_Exception
79 public function buildQuickForm() {
81 $this->assign('suppressForm', FALSE);
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);
85 $this->addPDFElementsToForm();
87 // specific need for contributions
88 $this->add('static', 'more_options_header', NULL, ts('Thank-you Letter Options'));
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);
92 // Group options for tokens are not yet implemented. dgg
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'),
99 'payment_instrument_id' => ts('Contact and Payment Method'),
101 $this->addElement('select', 'group_by', ts('Group contributions by'), $options, [], "<br/>", FALSE);
102 // this was going to be free-text but I opted for radio options in case there was a script injection risk
103 $separatorOptions = ['comma' => 'Comma', 'td' => 'Horizontal Table Cell', 'tr' => 'Vertical Table Cell', 'br' => 'Line Break'];
105 $this->addElement('select', 'group_by_separator', ts('Separator (grouped contributions)'), $separatorOptions);
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.'),
111 if (CRM_Core_Config
::singleton()->doNotAttachPDFReceipt
) {
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.');
115 $this->addElement('select', 'email_options', ts('Print and email options'), $emailOptions, [], "<br/>", FALSE);
117 $this->addButtons($this->getButtons());
122 * Get the name for the main submit button.
126 protected function getMainSubmitButtonName(): string {
127 return ts('Make Thank-you Letters');
131 * Process the form after the input has been submitted and validated.
133 * @throws \CRM_Core_Exception
134 * @throws \CiviCRM_API3_Exception
136 public function postProcess() {
137 $formValues = $this->controller
->exportValues($this->getName());
138 [$formValues, $html_message] = $this->processMessageTemplate($formValues);
140 $messageToken = CRM_Utils_Token
::getTokens($html_message);
142 $returnProperties = [];
143 if (isset($messageToken['contact'])) {
144 foreach ($messageToken['contact'] as $key => $value) {
145 $returnProperties[$value] = 1;
151 if (!empty($formValues['email_options'])) {
152 $returnProperties['email'] = $returnProperties['on_hold'] = $returnProperties['is_deceased'] = $returnProperties['do_not_email'] = 1;
154 'subject' => $formValues['subject'] ??
NULL,
155 'from' => $formValues['from_email_address'] ??
NULL,
158 $emailParams['from'] = CRM_Utils_Mail
::formatFromAddress($emailParams['from']);
160 // We need display_name for emailLetter() so add to returnProperties here
161 $returnProperties['display_name'] = 1;
162 if (stristr($formValues['email_options'], 'pdfemail')) {
167 $receipt_update = $formValues['receipt_update'] ??
FALSE;
168 $thankyou_update = $formValues['thankyou_update'] ??
FALSE;
169 $nowDate = date('YmdHis');
170 $receipts = $thanks = $emailed = 0;
172 $task = 'CRM_Contribution_Form_Task_PDFLetterCommon';
173 $realSeparator = ', ';
176 'tr' => '</td></tr><tr><td>',
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']];
184 elseif ($formValues['group_by_separator'] == 'br') {
185 $realSeparator = "<br />";
188 // a placeholder in case the separator is common in the string - e.g ', '
189 $separator = '****~~~~';
190 $groupBy = $this->getSubmittedValue('group_by');
192 // skip some contacts ?
193 $skipOnHold = $this->skipOnHold ??
FALSE;
194 $skipDeceased = $this->skipDeceased ??
TRUE;
195 $contributionIDs = $this->getIDs();
196 if ($this->isQueryIncludesSoftCredits()) {
197 $contributionIDs = [];
198 $result = $this->getSearchQueryResults();
199 while ($result->fetch()) {
200 $this->_contactIds
[$result->contact_id
] = $result->contact_id
;
201 $contributionIDs["{$result->contact_id}-{$result->contribution_id}"] = $result->contribution_id
;
204 [$contributions, $contacts] = $this->buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $this->isQueryIncludesSoftCredits());
206 $contactHtml = $emailedHtml = [];
207 foreach ($contributions as $contributionId => $contribution) {
208 $contact = &$contacts[$contribution['contact_id']];
212 $groupByID = empty($contribution[$groupBy]) ?
0 : $contribution[$groupBy];
213 $contribution = $contact['combined'][$groupBy][$groupByID];
217 if (empty($groupBy) ||
empty($contact['is_sent'][$groupBy][$groupByID])) {
218 $html[$contributionId] = $this->generateHtml($contact, $contribution, $groupBy, $contributions, $realSeparator, $tableSeparators, $messageToken, $html_message, $separator, $grouped, $groupByID);
219 $contactHtml[$contact['contact_id']][] = $html[$contributionId];
220 if ($this->isSendEmails()) {
221 if ($this->emailLetter($contact, $html[$contributionId], $isPDF, $formValues, $emailParams)) {
223 if (!stristr($formValues['email_options'], 'both')) {
224 $emailedHtml[$contributionId] = TRUE;
228 $contact['is_sent'][$groupBy][$groupByID] = TRUE;
230 if ($this->isLiveMode()) {
231 // Update receipt/thankyou dates
232 $contributionParams = ['id' => $contributionId];
233 if ($receipt_update) {
234 $contributionParams['receipt_date'] = $nowDate;
236 if ($thankyou_update) {
237 $contributionParams['thankyou_date'] = $nowDate;
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);
247 $contactIds = array_keys($contacts);
248 // CRM-16725 Skip creation of activities if user is previewing their PDF letter(s)
249 if ($this->isLiveMode()) {
250 $this->createActivities($html_message, $contactIds, CRM_Utils_Array
::value('subject', $formValues, ts('Thank you letter')), CRM_Utils_Array
::value('campaign_id', $formValues), $contactHtml);
252 $html = array_diff_key($html, $emailedHtml);
256 $fileName = $this->getFileName();
257 if ($this->getSubmittedValue('document_type') === 'pdf') {
258 CRM_Utils_PDF_Utils
::html2pdf($html, $fileName . '.pdf', FALSE, $formValues);
261 CRM_Utils_PDF_Document
::html2doc($html, $fileName . '.' . $this->getSubmittedValue('document_type'), $formValues);
265 $this->postProcessHook();
268 $updateStatus = ts('Receipts have been emailed to %1 contributions.', [1 => $emailed]);
271 $updateStatus = ts('Receipt date has been updated for %1 contributions.', [1 => $receipts]);
274 $updateStatus .= ' ' . ts('Thank-you date has been updated for %1 contributions.', [1 => $thanks]);
278 CRM_Core_Session
::setStatus($updateStatus);
281 // ie. we have only sent emails - lets no show a white screen
282 CRM_Utils_System
::civiExit();
287 * Are emails to be sent out?
291 protected function isSendEmails(): bool {
292 return $this->isLiveMode() && $this->getSubmittedValue('email_options');
296 * Get the token processor schema required to list any tokens for this task.
300 public function getTokenSchema(): array {
301 return ['contributionId', 'contactId'];
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
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
319 * @throws \CiviCRM_API3_Exception
321 public function buildContributionArray($groupBy, $contributionIDs, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator, $isIncludeSoftCredits) {
322 $contributions = $contacts = [];
323 foreach ($contributionIDs as $item => $contributionId) {
324 $contribution = CRM_Contribute_BAO_Contribution
::getContributionTokenValues($contributionId, $messageToken)['values'][$contributionId];
325 $contribution['campaign'] = $contribution['contribution_campaign_title'] ??
NULL;
326 $contributions[$contributionId] = $contribution;
328 if ($isIncludeSoftCredits) {
329 //@todo find out why this happens & add comments
330 [$contactID] = explode('-', $item);
331 $contactID = (int) $contactID;
334 $contactID = $contribution['contact_id'];
336 if (!isset($contacts[$contactID])) {
337 $contacts[$contactID] = [];
338 $contacts[$contactID]['contact_aggregate'] = 0;
339 $contacts[$contactID]['combined'] = $contacts[$contactID]['contribution_ids'] = [];
342 $contacts[$contactID]['contact_aggregate'] +
= $contribution['total_amount'];
343 $groupByID = empty($contribution[$groupBy]) ?
0 : $contribution[$groupBy];
345 $contacts[$contactID]['contribution_ids'][$groupBy][$groupByID][$contributionId] = TRUE;
346 if (!isset($contacts[$contactID]['combined'][$groupBy]) ||
!isset($contacts[$contactID]['combined'][$groupBy][$groupByID])) {
347 $contacts[$contactID]['combined'][$groupBy][$groupByID] = $contribution;
348 $contacts[$contactID]['aggregates'][$groupBy][$groupByID] = $contribution['total_amount'];
351 $contacts[$contactID]['combined'][$groupBy][$groupByID] = self
::combineContributions($contacts[$contactID]['combined'][$groupBy][$groupByID], $contribution, $separator);
352 $contacts[$contactID]['aggregates'][$groupBy][$groupByID] +
= $contribution['total_amount'];
355 // Assign the available contributions before calling tokens so hooks parsing smarty can access it.
356 // Note that in core code you can only use smarty here if enable if for the whole site, incl
357 // CiviMail, with a big performance impact.
358 // Hooks allow more nuanced smarty usage here.
359 CRM_Core_Smarty
::singleton()->assign('contributions', $contributions);
360 $resolvedContacts = civicrm_api3('Contact', 'get', [
361 'return' => array_keys($returnProperties),
362 'id' => ['IN' => array_keys($contacts)],
363 'options' => ['limit' => 0],
365 foreach ($contacts as $contactID => $contact) {
366 $contacts[$contactID] = array_merge($resolvedContacts[$contactID], $contact);
368 return [$contributions, $contacts];
372 * We combine the contributions by adding the contribution to each field with the separator in
373 * between the existing value and the new one. We put the separator there even if empty so it is clear what the
374 * value for previous contributions was
376 * @param array $existing
377 * @param array $contribution
378 * @param string $separator
382 public static function combineContributions($existing, $contribution, $separator) {
383 foreach ($contribution as $field => $value) {
384 $existing[$field] = isset($existing[$field]) ?
$existing[$field] . $separator : '';
385 $existing[$field] .= $value;
391 * We are going to retrieve the combined contribution and if smarty mail is enabled we
392 * will also assign an array of contributions for this contact to the smarty template
394 * @param array $contact
395 * @param array $contributions
397 * @param int $groupByID
399 public static function assignCombinedContributionValues($contact, $contributions, $groupBy, $groupByID) {
400 CRM_Core_Smarty
::singleton()->assign('contact_aggregate', $contact['contact_aggregate']);
401 CRM_Core_Smarty
::singleton()
402 ->assign('contributions', $contributions);
403 CRM_Core_Smarty
::singleton()->assign('contribution_aggregate', $contact['aggregates'][$groupBy][$groupByID]);
409 * @param $contribution
411 * @param $contributions
412 * @param $realSeparator
413 * @param $tableSeparators
414 * @param $messageToken
415 * @param $html_message
418 * @param bool $grouped
419 * @param int $groupByID
422 * @throws \CRM_Core_Exception
424 public function generateHtml($contact, $contribution, $groupBy, $contributions, $realSeparator, $tableSeparators, $messageToken, $html_message, $separator, $grouped, $groupByID) {
425 static $validated = FALSE;
428 $groupedContributions = array_intersect_key($contributions, $contact['contribution_ids'][$groupBy][$groupByID]);
429 CRM_Contribute_Form_Task_PDFLetter
::assignCombinedContributionValues($contact, $groupedContributions, $groupBy, $groupByID);
431 if (empty($groupBy) ||
empty($contact['is_sent'][$groupBy][$groupByID])) {
432 if (!$validated && in_array($realSeparator, $tableSeparators) && !CRM_Contribute_Form_Task_PDFLetter
::isValidHTMLWithTableSeparator($messageToken, $html_message)) {
433 $realSeparator = ', ';
434 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 $html = str_replace($separator, $realSeparator, $this->resolveTokens($html_message, $contact['contact_id'], $contribution['id'], $grouped, $separator, $groupedContributions));
446 * @param array $contact
447 * @param string $html
450 * @param array $format
451 * @param array $params
455 public function emailLetter($contact, $html, $is_pdf, $format = [], $params = []) {
457 if (empty($contact['email'])) {
460 $mustBeEmpty = ['do_not_email', 'is_deceased', 'on_hold'];
461 foreach ($mustBeEmpty as $emptyField) {
462 if (!empty($contact[$emptyField])) {
468 'contactId' => $contact['id'],
469 'toName' => $contact['display_name'],
470 'toEmail' => $contact['email'],
474 if (empty($params['from'])) {
475 $emails = CRM_Core_BAO_Email
::getFromEmail();
476 $emails = array_keys($emails);
477 $defaults['from'] = array_pop($emails);
480 $defaults['from'] = $params['from'];
482 if (!empty($params['subject'])) {
483 $defaults['subject'] = $params['subject'];
486 $defaults['subject'] = ts('Thank you for your contribution/s');
489 $defaults['html'] = ts('Please see attached');
490 $defaults['attachments'] = [CRM_Utils_Mail
::appendPDF('ThankYou.pdf', $html, $format)];
492 return CRM_Utils_Mail
::send($defaults);
494 catch (CRM_Core_Exception
$e) {
500 * Check that the token only appears in a table cell. The '</td><td>' separator cannot otherwise work
501 * Calculate the number of times it appears IN the cell & the number of times it appears - should be the same!
503 * @param string $token
504 * @param string $entity
505 * @param string $textToSearch
509 public static function isHtmlTokenInTableCell($token, $entity, $textToSearch) {
510 $tokenToMatch = $entity . '\.' . $token;
511 $pattern = '|<td(?![\w-])((?!</td>).)*\{' . $tokenToMatch . '\}.*?</td>|si';
512 $within = preg_match_all($pattern, $textToSearch);
513 $total = preg_match_all("|{" . $tokenToMatch . "}|", $textToSearch);
514 return ($within == $total);
518 * Check whether any of the tokens exist in the html outside a table cell.
519 * If they do the table cell separator is not supported (return false)
520 * At this stage we are only anticipating contributions passed in this way but
521 * it would be easy to add others
527 public static function isValidHTMLWithTableSeparator($tokens, $html) {
528 $relevantEntities = ['contribution'];
529 foreach ($relevantEntities as $entity) {
530 if (isset($tokens[$entity]) && is_array($tokens[$entity])) {
531 foreach ($tokens[$entity] as $token) {
532 if (!CRM_Contribute_Form_Task_PDFLetter
::isHtmlTokenInTableCell($token, $entity, $html)) {
543 * @param string $html_message
544 * @param int $contactID
545 * @param int $contributionID
546 * @param bool $grouped
547 * Does this letter represent more than one contribution.
548 * @param string $separator
549 * What is the preferred letter separator.
550 * @param array $contributions
554 protected function resolveTokens(string $html_message, int $contactID, $contributionID, $grouped, $separator, $contributions): string {
556 'smarty' => (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
),
557 'contactId' => $contactID,
558 'schema' => ['contributionId'],
561 // First replace the contribution tokens. These are pretty ... special.
562 // if the text looks like `<td>{contribution.currency} {contribution.total_amount}</td>'
563 // and there are 2 rows with a currency separator of
564 // you wind up with a string like
565 // '<td>USD</td><td>USD></td> <td>$50</td><td>$89</td>
566 // see https://docs.civicrm.org/user/en/latest/contributions/manual-receipts-and-thank-yous/#grouped-contribution-thank-you-letters
567 $tokenProcessor = new TokenProcessor(\Civi
::dispatcher(), $tokenContext);
568 $contributionTokens = CRM_Utils_Token
::getTokens($html_message)['contribution'] ??
[];
569 foreach ($contributionTokens as $token) {
570 $tokenProcessor->addMessage($token, '{contribution.' . $token . '}', 'text/html');
573 foreach ($contributions as $contribution) {
574 $tokenProcessor->addRow([
575 'contributionId' => $contribution['id'],
576 'contribution' => $contribution,
579 $tokenProcessor->evaluate();
580 $resolvedTokens = [];
581 foreach ($contributionTokens as $token) {
582 foreach ($tokenProcessor->getRows() as $row) {
583 $resolvedTokens[$token][$row->context
['contributionId']] = $row->render($token);
585 $html_message = str_replace('{contribution.' . $token . '}', implode($separator, $resolvedTokens[$token]), $html_message);
588 $tokenContext['contributionId'] = $contributionID;
589 return CRM_Core_TokenSmarty
::render(['html' => $html_message], $tokenContext)['html'];