Merge pull request #17458 from eileenmcnaughton/export
[civicrm-core.git] / CRM / Contribute / Form / Task / PDF.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
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 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17
18 /**
19 * This class provides the functionality to email a group of
20 * contacts.
21 */
22 class 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 *
28 * @var bool
29 */
30 public $_single = FALSE;
31
32 protected $_rows;
33
34 /**
35 * Build all the data structures needed to build the form.
36 */
37 public function preProcess() {
38 $id = CRM_Utils_Request::retrieve('id', 'Positive',
39 $this, FALSE
40 );
41
42 if ($id) {
43 $this->_contributionIds = [$id];
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 = "
54 SELECT count(*)
55 FROM civicrm_contribution
56 WHERE contribution_status_id != 1
57 AND {$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
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);
72 $breadCrumb = [
73 [
74 'url' => $url,
75 'title' => ts('Search Results'),
76 ],
77 ];
78 CRM_Contact_Form_Task_EmailCommon ::preProcessFromAddress($this, FALSE);
79 // we have all the contribution ids, so now we get the contact ids
80 parent::setContactIDs();
81 CRM_Utils_System::appendBreadCrumb($breadCrumb);
82 CRM_Utils_System::setTitle(ts('Print Contribution Receipts'));
83 }
84
85 /**
86 * Build the form object.
87 */
88 public function buildQuickForm() {
89
90 $this->addElement('radio', 'output', NULL, ts('Email Receipts'), 'email_receipt',
91 [
92 'onClick' => "document.getElementById('selectPdfFormat').style.display = 'none';
93 document.getElementById('selectEmailFrom').style.display = 'block';",
94 ]
95 );
96 $this->addElement('radio', 'output', NULL, ts('PDF Receipts'), 'pdf_receipt',
97 [
98 'onClick' => "document.getElementById('selectPdfFormat').style.display = 'block';
99 document.getElementById('selectEmailFrom').style.display = 'none';",
100 ]
101 );
102 $this->addRule('output', ts('Selection required'), 'required');
103
104 $this->add('select', 'pdf_format_id', ts('Page Format'),
105 [0 => ts('- default -')] + CRM_Core_BAO_PdfFormat::getList(TRUE)
106 );
107 $this->add('checkbox', 'receipt_update', ts('Update receipt dates for these contributions'), FALSE);
108 $this->add('checkbox', 'override_privacy', ts('Override privacy setting? (Do not email / Do not mail)'), FALSE);
109
110 $this->add('select', 'from_email_address', ts('From Email'), $this->_fromEmails, FALSE);
111
112 $this->addButtons([
113 [
114 'type' => 'next',
115 'name' => ts('Process Receipt(s)'),
116 'isDefault' => TRUE,
117 ],
118 [
119 'type' => 'back',
120 'name' => ts('Cancel'),
121 ],
122 ]);
123 }
124
125 /**
126 * Set default values.
127 */
128 public function setDefaultValues() {
129 $defaultFormat = CRM_Core_BAO_PdfFormat::getDefaultValues();
130 return ['pdf_format_id' => $defaultFormat['id'], 'receipt_update' => 1, 'override_privacy' => 0];
131 }
132
133 /**
134 * Process the form after the input has been submitted and validated.
135 */
136 public function postProcess() {
137 // get all the details needed to generate a receipt
138 $message = [];
139 $template = CRM_Core_Smarty::singleton();
140
141 $params = $this->controller->exportValues($this->_name);
142 $elements = self::getElements($this->_contributionIds, $params, $this->_contactIds);
143
144 foreach ($elements['details'] as $contribID => $detail) {
145 $input = $ids = $objects = [];
146
147 if (in_array($detail['contact'], $elements['excludeContactIds'])) {
148 continue;
149 }
150
151 $input['component'] = $detail['component'];
152
153 $ids['contact'] = $detail['contact'];
154 $ids['contribution'] = $contribID;
155 $ids['contributionRecur'] = NULL;
156 $ids['contributionPage'] = NULL;
157 $ids['membership'] = $detail['membership'] ?? NULL;
158 $ids['participant'] = $detail['participant'] ?? NULL;
159 $ids['event'] = $detail['event'] ?? NULL;
160
161 if (!$elements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
162 throw new CRM_Core_Exception('invalid data');
163 }
164
165 $contribution = &$objects['contribution'];
166
167 // set some fake input values so we can reuse IPN code
168 $input['amount'] = $contribution->total_amount;
169 $input['is_test'] = $contribution->is_test;
170 $input['fee_amount'] = $contribution->fee_amount;
171 $input['net_amount'] = $contribution->net_amount;
172 $input['trxn_id'] = $contribution->trxn_id;
173 $input['trxn_date'] = $contribution->trxn_date ?? NULL;
174 $input['receipt_update'] = $params['receipt_update'];
175 $input['contribution_status_id'] = $contribution->contribution_status_id;
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
180 LIMIT 1", [
181 1 => [$contribution->trxn_id, 'String'],
182 ]);
183
184 // CRM_Contribute_BAO_Contribution::composeMessageArray expects mysql formatted date
185 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
186
187 $values = [];
188 if (isset($params['from_email_address']) && !$elements['createPdf']) {
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']);
193 // CRM-19129 Allow useres the choice of From Email to send the receipt from.
194 $fromDetails = explode(' <', $from);
195 $input['receipt_from_email'] = substr(trim($fromDetails[1]), 0, -1);
196 $input['receipt_from_name'] = str_replace('"', '', $fromDetails[0]);
197 }
198
199 $mail = CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution']->id, $values,
200 $elements['createPdf']);
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 }
212
213 if ($elements['createPdf']) {
214 CRM_Utils_PDF_Utils::html2pdf($message,
215 'civicrmContributionReceipt.pdf',
216 FALSE,
217 $elements['params']['pdf_format_id']
218 );
219 CRM_Utils_System::civiExit();
220 }
221 else {
222 if ($elements['suppressedEmails']) {
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']]);
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 }
235
236 /**
237 * Declaration of common variables for Invoice and PDF.
238 *
239 *
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.
246 *
247 * @return array
248 * array of common elements
249 *
250 */
251 public static function getElements($contribIds, $params, $contactIds) {
252 $pdfElements = [];
253
254 $pdfElements['contribIDs'] = implode(',', $contribIds);
255
256 $pdfElements['details'] = CRM_Contribute_Form_Task_Status::getDetails($pdfElements['contribIDs']);
257
258 $pdfElements['baseIPN'] = new CRM_Core_Payment_BaseIPN();
259
260 $pdfElements['params'] = $params;
261
262 $pdfElements['createPdf'] = FALSE;
263 if (!empty($pdfElements['params']['output']) &&
264 ($pdfElements['params']['output'] == "pdf_invoice" || $pdfElements['params']['output'] == "pdf_receipt")
265 ) {
266 $pdfElements['createPdf'] = TRUE;
267 }
268
269 $excludeContactIds = [];
270 if (!$pdfElements['createPdf']) {
271 $returnProperties = [
272 'email' => 1,
273 'do_not_email' => 1,
274 'is_deceased' => 1,
275 'on_hold' => 1,
276 ];
277
278 list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, $returnProperties, FALSE, FALSE);
279 $pdfElements['suppressedEmails'] = 0;
280 $suppressedEmails = 0;
281 foreach ($contactDetails as $id => $values) {
282 if (empty($values['email']) ||
283 (empty($params['override_privacy']) && !empty($values['do_not_email']))
284 || !empty($values['is_deceased'])
285 || !empty($values['on_hold'])
286 ) {
287 $suppressedEmails++;
288 $pdfElements['suppressedEmails'] = $suppressedEmails;
289 $excludeContactIds[] = $values['contact_id'];
290 }
291 }
292 }
293 $pdfElements['excludeContactIds'] = $excludeContactIds;
294
295 return $pdfElements;
296 }
297
298 }