INFRA-132 - Trailing commas for multiline arrays
[civicrm-core.git] / CRM / Contribute / Form / Task / PDFLetterCommon.php
CommitLineData
6a488035
TO
1<?php
2
3/**
4 * This class provides the common functionality for creating PDF letter for
5 * one or a group of contact ids.
6 */
7class CRM_Contribute_Form_Task_PDFLetterCommon extends CRM_Contact_Form_Task_PDFLetterCommon {
8
9 /**
100fef9d 10 * Process the form after the input has been submitted and validated
6a488035 11 *
6a488035 12 *
493078cb 13 * @param CRM_Contribute_Form_Task $form
fe7febc7 14 *
355ba699 15 * @return void
6a488035 16 */
00be9182 17 public static function postProcess(&$form) {
6a488035 18 list($formValues, $categories, $html_message, $messageToken, $returnProperties) = self::processMessageTemplate($form);
493078cb
EM
19 $isPDF = FALSE;
20 $emailParams = array();
22e263ad 21 if (!empty($formValues['email_options'])) {
383c047b
DG
22 $returnProperties['email'] = $returnProperties['on_hold'] = $returnProperties['is_deceased'] = $returnProperties['do_not_email'] = 1;
23 $emailParams = array(
21dfd5f5 24 'subject' => $formValues['subject'],
383c047b 25 );
f83f6352
DG
26 // We need display_name for emailLetter() so add to returnProperties here
27 $returnProperties['display_name'] = 1;
22e263ad 28 if (stristr($formValues['email_options'], 'pdfemail')) {
383c047b
DG
29 $isPDF = TRUE;
30 }
31 }
6a488035
TO
32 // update dates ?
33 $receipt_update = isset($formValues['receipt_update']) ? $formValues['receipt_update'] : FALSE;
34 $thankyou_update = isset($formValues['thankyou_update']) ? $formValues['thankyou_update'] : FALSE;
35 $nowDate = date('YmdHis');
383c047b 36 $receipts = $thanks = $emailed = 0;
6a488035 37 $updateStatus = '';
383c047b
DG
38 $task = 'CRM_Contribution_Form_Task_PDFLetterCommon';
39 $realSeparator = ', ';
40 //the original thinking was mutliple options - but we are going with only 2 (comma & td) for now in case
41 // there are security (& UI) issues we need to think through
22e263ad
TO
42 if (isset($formValues['group_by_separator'])) {
43 if ($formValues['group_by_separator'] == 'td') {
383c047b
DG
44 $realSeparator = "</td><td>";
45 }
46 }
47 $separator = '****~~~~';// a placeholder in case the separator is common in the string - e.g ', '
8cb33f3b 48 $validated = FALSE;
383c047b
DG
49
50 $groupBy = $formValues['group_by'];
6a488035
TO
51
52 // skip some contacts ?
53 $skipOnHold = isset($form->skipOnHold) ? $form->skipOnHold : FALSE;
54 $skipDeceased = isset($form->skipDeceased) ? $form->skipDeceased : TRUE;
55
ff926d67 56 list($contributions, $contacts) = self::buildContributionArray($groupBy, $form, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator);
383c047b
DG
57 $html = array();
58 foreach ($contributions as $contributionId => $contribution) {
59 $contact = &$contacts[$contribution['contact_id']];
60 $grouped = $groupByID = 0;
22e263ad 61 if ($groupBy) {
383c047b
DG
62 $groupByID = empty($contribution[$groupBy]) ? 0 : $contribution[$groupBy];
63 $contribution = $contact['combined'][$groupBy][$groupByID];
64 $grouped = TRUE;
6a488035
TO
65 }
66
383c047b 67 self::assignCombinedContributionValues($contact, $contributions, $groupBy, $groupByID);
6a488035 68
22e263ad
TO
69 if (empty($groupBy) || empty($contact['is_sent'][$groupBy][$groupByID])) {
70 if (!$validated && $realSeparator == '</td><td>' && !self::isValidHTMLWithTableSeparator($messageToken, $html_message)) {
8cb33f3b 71 $realSeparator = ', ';
6c690132 72 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.'));
8cb33f3b
EM
73 }
74 $validated = TRUE;
493078cb 75 $html[$contributionId] = str_replace($separator, $realSeparator, self::resolveTokens($html_message, $contact, $contribution, $messageToken, $categories, $grouped, $separator));
383c047b 76 $contact['is_sent'][$groupBy][$groupByID] = TRUE;
22e263ad
TO
77 if (!empty($formValues['email_options'])) {
78 if (self::emailLetter($contact, $html[$contributionId], $isPDF, $formValues, $emailParams)) {
383c047b 79 $emailed ++;
22e263ad 80 if (!stristr($formValues['email_options'], 'both')) {
383c047b
DG
81 unset($html[$contributionId]);
82 }
83 }
84 }
6a488035
TO
85 }
86
6a488035 87 // update dates (do it for each contribution including grouped recurring contribution)
383c047b 88 //@todo - the 2 calls below bypass all hooks. Using the api would possibly be slower than one call but not than 2
6a488035
TO
89 if ($receipt_update) {
90 $result = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'receipt_date', $nowDate);
6a488035
TO
91 if ($result) {
92 $receipts++;
383c047b 93 }
6a488035
TO
94 }
95 if ($thankyou_update) {
96 $result = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contributionId, 'thankyou_date', $nowDate);
6a488035
TO
97 if ($result) {
98 $thanks++;
383c047b 99 }
6a488035
TO
100 }
101 }
383c047b
DG
102 //createActivities requires both $form->_contactIds and $contacts -
103 //@todo - figure out why
104 $form->_contactIds = array_keys($contacts);
6a488035 105 self::createActivities($form, $html_message, $form->_contactIds);
22e263ad 106 if (!empty($html)) {
383c047b
DG
107 CRM_Utils_PDF_Utils::html2pdf($html, "CiviLetter.pdf", FALSE, $formValues);
108 }
6a488035
TO
109
110 $form->postProcessHook();
111
383c047b
DG
112 if ($emailed) {
113 $updateStatus = ts('Receipts have been emailed to %1 contributions.', array(1 => $emailed));
114 }
6a488035
TO
115 if ($receipts) {
116 $updateStatus = ts('Receipt date has been updated for %1 contributions.', array(1 => $receipts));
117 }
118 if ($thanks) {
119 $updateStatus .= ' ' . ts('Thank-you date has been updated for %1 contributions.', array(1 => $thanks));
120 }
121
122 if ($updateStatus) {
123 CRM_Core_Session::setStatus($updateStatus);
124 }
22e263ad 125 if (!empty($html)) {
383c047b
DG
126 // ie. we have only sent emails - lets no show a white screen
127 CRM_Utils_System::civiExit(1);
128 }
129 }
665e5ec7 130
8cb33f3b
EM
131 /**
132 * Check whether any of the tokens exist in the html outside a table cell.
133 * If they do the table cell separator is not supported (return false)
134 * At this stage we are only anticipating contributions passed in this way but
135 * it would be easy to add others
136 * @param $tokens
137 * @param $html
138 *
139 * @return bool
140 */
00be9182 141 public static function isValidHTMLWithTableSeparator($tokens, $html) {
8cb33f3b
EM
142 $relevantEntities = array('contribution');
143 foreach ($relevantEntities as $entity) {
045bdb93 144 if (isset($tokens[$entity]) && is_array($tokens[$entity])) {
8cb33f3b 145 foreach ($tokens[$entity] as $token) {
22e263ad 146 if (!self::isHtmlTokenInTableCell($token, $entity, $html)) {;
8cb33f3b
EM
147 return FALSE;
148 }
149 }
150 }
151 }
152 return TRUE;
153 }
154
155 /**
100fef9d 156 * Check that the token only appears in a table cell. The '</td><td>' separator cannot otherwise work
045bdb93
EM
157 * Calculate the number of times it appears IN the cell & the number of times it appears - should be the same!
158 *
8cb33f3b
EM
159 * @param $token
160 * @param $entity
045bdb93
EM
161 * @param $textToSearch
162 *
045bdb93 163 * @return bool
8cb33f3b 164 */
00be9182 165 public static function isHtmlTokenInTableCell($token, $entity, $textToSearch) {
045bdb93 166 $tokenToMatch = $entity . '.' . $token;
6c690132 167 $dontCare = array();
92fcb95f
TO
168 $within = preg_match_all("|<td.+?{" . $tokenToMatch . "}.+?</td|si", $textToSearch, $dontCare);
169 $total = preg_match_all("|{" . $tokenToMatch . "}|", $textToSearch, $dontCare);
045bdb93 170 return ($within == $total);
8cb33f3b
EM
171 }
172
874c9be7
TO
173 /**
174 *
175 * @param string $html_message
176 * @param array $contact
177 * @param array $contribution
178 * @param array $messageToken
179 * @param array $categories
180 * @param bool $grouped
181 * Does this letter represent more than one contribution.
182 * @param string $separator
183 * What is the preferred letter separator.
184 * @return string
185 */
186 private static function resolveTokens($html_message, $contact, $contribution, $messageToken, $categories, $grouped, $separator) {
187 $tokenHtml = CRM_Utils_Token::replaceContactTokens($html_message, $contact, TRUE, $messageToken);
22e263ad 188 if ($grouped) {
874c9be7
TO
189 $tokenHtml = CRM_Utils_Token::replaceMultipleContributionTokens($separator, $tokenHtml, $contribution, TRUE, $messageToken);
190 }
191 else {
192 // no change to normal behaviour to avoid risk of breakage
193 $tokenHtml = CRM_Utils_Token::replaceContributionTokens($tokenHtml, $contribution, TRUE, $messageToken);
194 }
195 $tokenHtml = CRM_Utils_Token::replaceHookTokens($tokenHtml, $contact, $categories, TRUE);
196 if (defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY) {
383c047b
DG
197 $smarty = CRM_Core_Smarty::singleton();
198 // also add the tokens to the template
199 $smarty->assign_by_ref('contact', $contact);
200 $tokenHtml = $smarty->fetch("string:$tokenHtml");
201 }
202 return $tokenHtml;
203 }
204
205 /**
206 * Generate the contribution array from the form, we fill in the contact details and determine any aggregation
207 * around contact_id of contribution_recur_id
208 *
045bdb93
EM
209 * @param string $groupBy
210 * @param CRM_Contribute_Form_Task $form
354bc6e1 211 * @param array $returnProperties
014c4014
TO
212 * @param bool $skipOnHold
213 * @param bool $skipDeceased
354bc6e1 214 * @param array $messageToken
8cb33f3b 215 * @param string $task
045bdb93 216 * @param string $separator
fe7febc7 217 *
493078cb 218 * @return array:
383c047b 219 */
00be9182 220 public static function buildContributionArray($groupBy, $form, $returnProperties, $skipOnHold, $skipDeceased, $messageToken, $task, $separator) {
383c047b
DG
221 $contributions = $contacts = $notSent = array();
222 $contributionIDs = $form->getVar('_contributionIds');
223 if ($form->_includesSoftCredits) {
224 //@todo - comment on what is stored there
225 $contributionIDs = $form->getVar('_contributionContactIds');
226 }
227 foreach ($contributionIDs as $item => $contributionId) {
ff926d67
EM
228 // get contribution information
229 $contribution = CRM_Utils_Token::getContributionTokenDetails(array('contribution_id' => $contributionId),
230 $returnProperties,
231 NULL,
232 $messageToken,
233 $task
234 );
235 $contribution = $contributions[$contributionId] = $contribution[$contributionId];
236 if ($form->_includesSoftCredits) {
237 //@todo find out why this happens & add comments
238 list($contactID) = explode('-', $item);
239 $contactID = (int) $contactID;
874c9be7 240 }
ff926d67 241 else {
874c9be7 242 $contactID = $contribution['contact_id'];
ff926d67 243 }
22e263ad 244 if (!isset($contacts[$contactID])) {
ff926d67 245 list($contact) = CRM_Utils_Token::getTokenDetails(array('contact_id' => $contactID),
383c047b 246 $returnProperties,
ff926d67
EM
247 $skipOnHold,
248 $skipDeceased,
383c047b
DG
249 NULL,
250 $messageToken,
251 $task
252 );
ff926d67
EM
253 $contacts[$contactID] = $contact[$contactID];
254 $contacts[$contactID]['contact_aggregate'] = 0;
255 $contacts[$contactID]['combined'] = $contacts[$contactID]['contribution_ids'] = array();
256 }
383c047b 257
ff926d67
EM
258 $contacts[$contactID]['contact_aggregate'] += $contribution['total_amount'];
259 $groupByID = empty($contribution[$groupBy]) ? 0 : $contribution[$groupBy];
383c047b 260
ff926d67 261 $contacts[$contactID]['contribution_ids'][$groupBy][$groupByID][$contributionId] = TRUE;
22e263ad 262 if (!isset($contacts[$contactID]['combined'][$groupBy]) || !isset($contacts[$contactID]['combined'][$groupBy][$groupByID])) {
ff926d67
EM
263 $contacts[$contactID]['combined'][$groupBy][$groupByID] = $contribution;
264 $contacts[$contactID]['aggregates'][$groupBy][$groupByID] = $contribution['total_amount'];
383c047b 265 }
ff926d67
EM
266 else {
267 $contacts[$contactID]['combined'][$groupBy][$groupByID] = self::combineContributions($contacts[$contactID]['combined'][$groupBy][$groupByID], $contribution, $separator);
268 $contacts[$contactID]['aggregates'][$groupBy][$groupByID] += $contribution['total_amount'];
383c047b
DG
269 }
270 }
ff926d67 271 return array($contributions, $contacts);
383c047b
DG
272 }
273
274 /**
275 * We combine the contributions by adding the contribution to each field with the separator in
276 * between the existing value and the new one. We put the separator there even if empty so it is clear what the
277 * value for previous contributions was
fe7febc7 278 *
045bdb93
EM
279 * @param array $existing
280 * @param array $contribution
281 * @param string $separator
fe7febc7 282 *
045bdb93 283 * @return array
383c047b 284 */
00be9182 285 public static function combineContributions($existing, $contribution, $separator) {
383c047b 286 foreach ($contribution as $field => $value) {
7eebfcb9
EM
287 $existing[$field] = isset($existing[$field]) ? $existing[$field] . $separator : '';
288 $existing[$field] .= $value;
383c047b
DG
289 }
290 return $existing;
291 }
292
293 /**
294 * We are going to retrieve the combined contribution and if smarty mail is enabled we
295 * will also assign an array of contributions for this contact to the smarty template
fe7febc7 296 *
383c047b
DG
297 * @param array $contact
298 * @param array $contributions
fe7febc7 299 * @param $groupBy
100fef9d 300 * @param int $groupByID
383c047b 301 */
00be9182 302 public static function assignCombinedContributionValues($contact, $contributions, $groupBy, $groupByID) {
383c047b
DG
303 if (!defined('CIVICRM_MAIL_SMARTY') || !CIVICRM_MAIL_SMARTY) {
304 return;
305 }
306 CRM_Core_Smarty::singleton()->assign('contact_aggregate', $contact['contact_aggregate']);
307 CRM_Core_Smarty::singleton()->assign('contributions', array_intersect_key($contributions, $contact['contribution_ids'][$groupBy][$groupByID]));
308 CRM_Core_Smarty::singleton()->assign('contribution_aggregate', $contact['aggregates'][$groupBy][$groupByID]);
309
310 }
311
312 /**
313 * Send pdf by email
fe7febc7 314 *
383c047b
DG
315 * @param array $contact
316 * @param string $html
fe7febc7
EM
317 *
318 * @param $is_pdf
319 * @param array $format
320 * @param array $params
321 *
322 * @return bool
383c047b 323 */
00be9182 324 public static function emailLetter($contact, $html, $is_pdf, $format = array(), $params = array()) {
383c047b 325 try {
22e263ad 326 if (empty($contact['email'])) {
383c047b
DG
327 return FALSE;
328 }
329 $mustBeEmpty = array('do_not_email', 'is_deceased', 'on_hold');
330 foreach ($mustBeEmpty as $emptyField) {
22e263ad 331 if (!empty($contact[$emptyField])) {
383c047b
DG
332 return FALSE;
333 }
334 }
335
336 $defaults = array(
337 'toName' => $contact['display_name'],
338 'toEmail' => $contact['email'],
339 'subject' => ts('Thank you for your contribution/s'),
340 'text' => '',
341 'html' => $html,
342 );
22e263ad 343 if (empty($params['from'])) {
383c047b
DG
344 $emails = CRM_Core_BAO_Email::getFromEmail();
345 $emails = array_keys($emails);
346 $defaults['from'] = array_pop($emails);
347 }
22e263ad 348 if ($is_pdf) {
383c047b
DG
349 $defaults['html'] = ts('Please see attached');
350 $defaults['attachments'] = array(CRM_Utils_Mail::appendPDF('ThankYou.pdf', $html, $format));
351 }
352 $params = array_merge($defaults);
353 return CRM_Utils_Mail::send($params);
354 }
355 catch (CRM_Core_Exception $e) {
356 return FALSE;
357 }
6a488035 358 }
6a488035 359}