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