Merge pull request #17147 from kartik1000/Fix#1650
[civicrm-core.git] / CRM / Contribute / Form / Task / PDF.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
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18/**
19 * This class provides the functionality to email a group of
20 * contacts.
21 */
22class CRM_Contribute_Form_Task_PDF extends CRM_Contribute_Form_Task {
23
24 /**
25 * Are we operating in "single mode", i.e. updating the task of only
26 * one specific contribution?
27 *
b67daa72 28 * @var bool
6a488035
TO
29 */
30 public $_single = FALSE;
31
32 protected $_rows;
33
34 /**
fe482240 35 * Build all the data structures needed to build the form.
95ea96be 36 */
389bcebf 37 public function preProcess() {
6a488035
TO
38 $id = CRM_Utils_Request::retrieve('id', 'Positive',
39 $this, FALSE
40 );
41
42 if ($id) {
be2fb01f 43 $this->_contributionIds = [$id];
6a488035
TO
44 $this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
45 $this->_single = TRUE;
46 $this->assign('totalSelectedContributions', 1);
47 }
48 else {
49 parent::preProcess();
50 }
51
52 // check that all the contribution ids have pending status
53 $query = "
54SELECT count(*)
55FROM civicrm_contribution
56WHERE contribution_status_id != 1
57AND {$this->_componentClause}";
58 $count = CRM_Core_DAO::singleValueQuery($query);
59 if ($count != 0) {
60 CRM_Core_Error::statusBounce("Please select only online contributions with Completed status.");
61 }
62
6a488035
TO
63 $this->assign('single', $this->_single);
64
65 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
66 $urlParams = 'force=1';
67 if (CRM_Utils_Rule::qfKey($qfKey)) {
68 $urlParams .= "&qfKey=$qfKey";
69 }
70
71 $url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
be2fb01f
CW
72 $breadCrumb = [
73 [
353ffa53 74 'url' => $url,
6a488035 75 'title' => ts('Search Results'),
be2fb01f
CW
76 ],
77 ];
f68954cb 78 CRM_Contact_Form_Task_EmailCommon ::preProcessFromAddress($this, FALSE);
7d86c73a 79 // we have all the contribution ids, so now we get the contact ids
3c4ce98e 80 parent::setContactIDs();
6a488035
TO
81 CRM_Utils_System::appendBreadCrumb($breadCrumb);
82 CRM_Utils_System::setTitle(ts('Print Contribution Receipts'));
83 }
84
85 /**
fe482240 86 * Build the form object.
6a488035
TO
87 */
88 public function buildQuickForm() {
89
90 $this->addElement('radio', 'output', NULL, ts('Email Receipts'), 'email_receipt',
be2fb01f 91 [
6d98bfad 92 'onClick' => "document.getElementById('selectPdfFormat').style.display = 'none';
1330f57a
SL
93 document.getElementById('selectEmailFrom').style.display = 'block';",
94 ]
6a488035
TO
95 );
96 $this->addElement('radio', 'output', NULL, ts('PDF Receipts'), 'pdf_receipt',
be2fb01f 97 [
99ad38df 98 'onClick' => "document.getElementById('selectPdfFormat').style.display = 'block';
1330f57a
SL
99 document.getElementById('selectEmailFrom').style.display = 'none';",
100 ]
6a488035
TO
101 );
102 $this->addRule('output', ts('Selection required'), 'required');
103
104 $this->add('select', 'pdf_format_id', ts('Page Format'),
be2fb01f 105 [0 => ts('- default -')] + CRM_Core_BAO_PdfFormat::getList(TRUE)
6a488035 106 );
10708045 107 $this->add('checkbox', 'receipt_update', ts('Update receipt dates for these contributions'), FALSE);
be4478f0 108 $this->add('checkbox', 'override_privacy', ts('Override privacy setting? (Do not email / Do not mail)'), FALSE);
6a488035 109
beac1417 110 $this->add('select', 'from_email_address', ts('From Email'), $this->_fromEmails, FALSE);
6d98bfad 111
be2fb01f 112 $this->addButtons([
1330f57a
SL
113 [
114 'type' => 'next',
115 'name' => ts('Process Receipt(s)'),
116 'isDefault' => TRUE,
117 ],
118 [
119 'type' => 'back',
120 'name' => ts('Cancel'),
121 ],
122 ]);
6a488035
TO
123 }
124
125 /**
fe482240 126 * Set default values.
6a488035 127 */
00be9182 128 public function setDefaultValues() {
6a488035 129 $defaultFormat = CRM_Core_BAO_PdfFormat::getDefaultValues();
be2fb01f 130 return ['pdf_format_id' => $defaultFormat['id'], 'receipt_update' => 1, 'override_privacy' => 0];
6a488035
TO
131 }
132
133 /**
fe482240 134 * Process the form after the input has been submitted and validated.
6a488035
TO
135 */
136 public function postProcess() {
137 // get all the details needed to generate a receipt
be2fb01f 138 $message = [];
2826a42e 139 $template = CRM_Core_Smarty::singleton();
6a488035 140
6efffa5d
PB
141 $params = $this->controller->exportValues($this->_name);
142 $elements = self::getElements($this->_contributionIds, $params, $this->_contactIds);
6a488035 143
2826a42e 144 foreach ($elements['details'] as $contribID => $detail) {
be2fb01f 145 $input = $ids = $objects = [];
6a488035 146
3a1261ac 147 if (in_array($detail['contact'], $elements['excludeContactIds'])) {
6a488035
TO
148 continue;
149 }
150
151 $input['component'] = $detail['component'];
152
153 $ids['contact'] = $detail['contact'];
2826a42e 154 $ids['contribution'] = $contribID;
6a488035
TO
155 $ids['contributionRecur'] = NULL;
156 $ids['contributionPage'] = NULL;
9c1bc317
CW
157 $ids['membership'] = $detail['membership'] ?? NULL;
158 $ids['participant'] = $detail['participant'] ?? NULL;
159 $ids['event'] = $detail['event'] ?? NULL;
6a488035 160
3a1261ac 161 if (!$elements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
a39a65ee 162 throw new CRM_Core_Exception('invalid data');
6a488035
TO
163 }
164
165 $contribution = &$objects['contribution'];
6a488035
TO
166
167 // set some fake input values so we can reuse IPN code
353ffa53
TO
168 $input['amount'] = $contribution->total_amount;
169 $input['is_test'] = $contribution->is_test;
6a488035
TO
170 $input['fee_amount'] = $contribution->fee_amount;
171 $input['net_amount'] = $contribution->net_amount;
353ffa53 172 $input['trxn_id'] = $contribution->trxn_id;
77c21b32 173 $input['trxn_date'] = $contribution->trxn_date ?? NULL;
cc7b912f 174 $input['receipt_update'] = $params['receipt_update'];
d5580ed4 175 $input['contribution_status_id'] = $contribution->contribution_status_id;
35724050
BS
176 $input['paymentProcessor'] = empty($contribution->trxn_id) ? NULL :
177 CRM_Core_DAO::singleValueQuery("SELECT payment_processor_id
178 FROM civicrm_financial_trxn
179 WHERE trxn_id = %1
be2fb01f 180 LIMIT 1", [
1330f57a
SL
181 1 => [$contribution->trxn_id, 'String'],
182 ]);
6a488035 183
665e5ec7 184 // CRM_Contribute_BAO_Contribution::composeMessageArray expects mysql formatted date
6a488035
TO
185 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
186
be2fb01f 187 $values = [];
beac1417 188 if (isset($params['from_email_address']) && !$elements['createPdf']) {
5b8e26b5
SL
189 // If a logged in user from email is used rather than a domain wide from email address
190 // the from_email_address params key will be numerical and we need to convert it to be
191 // in normal from email format
192 $from = CRM_Utils_Mail::formatFromAddress($params['from_email_address']);
df72e709 193 // CRM-19129 Allow useres the choice of From Email to send the receipt from.
5b8e26b5 194 $fromDetails = explode(' <', $from);
6d98bfad
SL
195 $input['receipt_from_email'] = substr(trim($fromDetails[1]), 0, -1);
196 $input['receipt_from_name'] = str_replace('"', '', $fromDetails[0]);
197 }
198
6626a693 199 $mail = CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution']->id, $values,
a35dd516 200 $elements['createPdf']);
6a488035
TO
201
202 if ($mail['html']) {
203 $message[] = $mail['html'];
204 }
205 else {
206 $message[] = nl2br($mail['body']);
207 }
208
209 // reset template values before processing next transactions
210 $template->clearTemplateVars();
211 }
3a1261ac
RK
212
213 if ($elements['createPdf']) {
6a488035
TO
214 CRM_Utils_PDF_Utils::html2pdf($message,
215 'civicrmContributionReceipt.pdf',
216 FALSE,
3a1261ac 217 $elements['params']['pdf_format_id']
6a488035
TO
218 );
219 CRM_Utils_System::civiExit();
220 }
221 else {
3a1261ac 222 if ($elements['suppressedEmails']) {
be2fb01f 223 $status = ts('Email was NOT sent to %1 contacts (no email address on file, or communication preferences specify DO NOT EMAIL, or contact is deceased).', [1 => $elements['suppressedEmails']]);
6a488035
TO
224 $msgTitle = ts('Email Error');
225 $msgType = 'error';
226 }
227 else {
228 $status = ts('Your mail has been sent.');
229 $msgTitle = ts('Sent');
230 $msgType = 'success';
231 }
232 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
233 }
234 }
3a1261ac
RK
235
236 /**
fe482240 237 * Declaration of common variables for Invoice and PDF.
3a1261ac 238 *
3a1261ac 239 *
014c4014
TO
240 * @param array $contribIds
241 * Contribution Id.
242 * @param array $params
243 * Parameter for pdf or email invoices.
244 * @param array $contactIds
245 * Contact Id.
6efffa5d 246 *
a6c01b45
CW
247 * @return array
248 * array of common elements
2826a42e 249 *
3a1261ac 250 */
1330f57a 251 public static function getElements($contribIds, $params, $contactIds) {
be2fb01f 252 $pdfElements = [];
3a1261ac 253
6efffa5d 254 $pdfElements['contribIDs'] = implode(',', $contribIds);
3a1261ac
RK
255
256 $pdfElements['details'] = CRM_Contribute_Form_Task_Status::getDetails($pdfElements['contribIDs']);
257
258 $pdfElements['baseIPN'] = new CRM_Core_Payment_BaseIPN();
259
6efffa5d 260 $pdfElements['params'] = $params;
3a1261ac
RK
261
262 $pdfElements['createPdf'] = FALSE;
830b3e83 263 if (!empty($pdfElements['params']['output']) &&
353ffa53
TO
264 ($pdfElements['params']['output'] == "pdf_invoice" || $pdfElements['params']['output'] == "pdf_receipt")
265 ) {
3a1261ac
RK
266 $pdfElements['createPdf'] = TRUE;
267 }
268
be2fb01f 269 $excludeContactIds = [];
3a1261ac 270 if (!$pdfElements['createPdf']) {
be2fb01f 271 $returnProperties = [
353ffa53
TO
272 'email' => 1,
273 'do_not_email' => 1,
274 'is_deceased' => 1,
275 'on_hold' => 1,
be2fb01f 276 ];
3a1261ac 277
6efffa5d 278 list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, $returnProperties, FALSE, FALSE);
3a1261ac 279 $pdfElements['suppressedEmails'] = 0;
830b3e83 280 $suppressedEmails = 0;
3a1261ac 281 foreach ($contactDetails as $id => $values) {
10708045
EM
282 if (empty($values['email']) ||
283 (empty($params['override_privacy']) && !empty($values['do_not_email']))
b99f3e96 284 || !empty($values['is_deceased'])
353ffa53
TO
285 || !empty($values['on_hold'])
286 ) {
874c9be7
TO
287 $suppressedEmails++;
288 $pdfElements['suppressedEmails'] = $suppressedEmails;
289 $excludeContactIds[] = $values['contact_id'];
3a1261ac
RK
290 }
291 }
292 }
293 $pdfElements['excludeContactIds'] = $excludeContactIds;
2826a42e 294
3a1261ac
RK
295 return $pdfElements;
296 }
96025800 297
6a488035 298}