Merge pull request #13700 from colemanw/CRM-21008
[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 boolean
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 = array($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 = array(
89 array(
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 array(
108 'onClick' => "document.getElementById('selectPdfFormat').style.display = 'none';
109 document.getElementById('selectEmailFrom').style.display = 'block';")
110 );
111 $this->addElement('radio', 'output', NULL, ts('PDF Receipts'), 'pdf_receipt',
112 array(
113 'onClick' => "document.getElementById('selectPdfFormat').style.display = 'block';
114 document.getElementById('selectEmailFrom').style.display = 'none';")
115 );
116 $this->addRule('output', ts('Selection required'), 'required');
117
118 $this->add('select', 'pdf_format_id', ts('Page Format'),
119 array(0 => ts('- default -')) + CRM_Core_BAO_PdfFormat::getList(TRUE)
120 );
121 $this->add('checkbox', 'receipt_update', ts('Update receipt dates for these contributions'), FALSE);
122 $this->add('checkbox', 'override_privacy', ts('Override privacy setting? (Do not email / Do not mail)'), FALSE);
123
124 $this->add('select', 'from_email_address', ts('From Email'), $this->_fromEmails, FALSE);
125
126 $this->addButtons(array(
127 array(
128 'type' => 'next',
129 'name' => ts('Process Receipt(s)'),
130 'isDefault' => TRUE,
131 ),
132 array(
133 'type' => 'back',
134 'name' => ts('Cancel'),
135 ),
136 )
137 );
138 }
139
140 /**
141 * Set default values.
142 */
143 public function setDefaultValues() {
144 $defaultFormat = CRM_Core_BAO_PdfFormat::getDefaultValues();
145 return array('pdf_format_id' => $defaultFormat['id'], 'receipt_update' => 1, 'override_privacy' => 0);
146 }
147
148 /**
149 * Process the form after the input has been submitted and validated.
150 */
151 public function postProcess() {
152 // get all the details needed to generate a receipt
153 $message = array();
154 $template = CRM_Core_Smarty::singleton();
155
156 $params = $this->controller->exportValues($this->_name);
157 $elements = self::getElements($this->_contributionIds, $params, $this->_contactIds);
158
159 foreach ($elements['details'] as $contribID => $detail) {
160 $input = $ids = $objects = array();
161
162 if (in_array($detail['contact'], $elements['excludeContactIds'])) {
163 continue;
164 }
165
166 $input['component'] = $detail['component'];
167
168 $ids['contact'] = $detail['contact'];
169 $ids['contribution'] = $contribID;
170 $ids['contributionRecur'] = NULL;
171 $ids['contributionPage'] = NULL;
172 $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
173 $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
174 $ids['event'] = CRM_Utils_Array::value('event', $detail);
175
176 if (!$elements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
177 CRM_Core_Error::fatal();
178 }
179
180 $contribution = &$objects['contribution'];
181
182 // set some fake input values so we can reuse IPN code
183 $input['amount'] = $contribution->total_amount;
184 $input['is_test'] = $contribution->is_test;
185 $input['fee_amount'] = $contribution->fee_amount;
186 $input['net_amount'] = $contribution->net_amount;
187 $input['trxn_id'] = $contribution->trxn_id;
188 $input['trxn_date'] = isset($contribution->trxn_date) ? $contribution->trxn_date : NULL;
189 $input['receipt_update'] = $params['receipt_update'];
190 $input['contribution_status_id'] = $contribution->contribution_status_id;
191 $input['paymentProcessor'] = empty($contribution->trxn_id) ? NULL :
192 CRM_Core_DAO::singleValueQuery("SELECT payment_processor_id
193 FROM civicrm_financial_trxn
194 WHERE trxn_id = %1
195 LIMIT 1", array(
196 1 => array($contribution->trxn_id, 'String')));
197
198 // CRM_Contribute_BAO_Contribution::composeMessageArray expects mysql formatted date
199 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
200
201 $values = array();
202 if (isset($params['from_email_address']) && !$elements['createPdf']) {
203 // If a logged in user from email is used rather than a domain wide from email address
204 // the from_email_address params key will be numerical and we need to convert it to be
205 // in normal from email format
206 $from = CRM_Utils_Mail::formatFromAddress($params['from_email_address']);
207 // CRM-19129 Allow useres the choice of From Email to send the receipt from.
208 $fromDetails = explode(' <', $from);
209 $input['receipt_from_email'] = substr(trim($fromDetails[1]), 0, -1);
210 $input['receipt_from_name'] = str_replace('"', '', $fromDetails[0]);
211 }
212
213 $mail = CRM_Contribute_BAO_Contribution::sendMail($input, $ids, $objects['contribution']->id, $values,
214 $elements['createPdf']);
215
216 if ($mail['html']) {
217 $message[] = $mail['html'];
218 }
219 else {
220 $message[] = nl2br($mail['body']);
221 }
222
223 // reset template values before processing next transactions
224 $template->clearTemplateVars();
225 }
226
227 if ($elements['createPdf']) {
228 CRM_Utils_PDF_Utils::html2pdf($message,
229 'civicrmContributionReceipt.pdf',
230 FALSE,
231 $elements['params']['pdf_format_id']
232 );
233 CRM_Utils_System::civiExit();
234 }
235 else {
236 if ($elements['suppressedEmails']) {
237 $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).', array(1 => $elements['suppressedEmails']));
238 $msgTitle = ts('Email Error');
239 $msgType = 'error';
240 }
241 else {
242 $status = ts('Your mail has been sent.');
243 $msgTitle = ts('Sent');
244 $msgType = 'success';
245 }
246 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
247 }
248 }
249
250 /**
251 * Declaration of common variables for Invoice and PDF.
252 *
253 *
254 * @param array $contribIds
255 * Contribution Id.
256 * @param array $params
257 * Parameter for pdf or email invoices.
258 * @param array $contactIds
259 * Contact Id.
260 *
261 * @return array
262 * array of common elements
263 *
264 */
265 static public function getElements($contribIds, $params, $contactIds) {
266 $pdfElements = array();
267
268 $pdfElements['contribIDs'] = implode(',', $contribIds);
269
270 $pdfElements['details'] = CRM_Contribute_Form_Task_Status::getDetails($pdfElements['contribIDs']);
271
272 $pdfElements['baseIPN'] = new CRM_Core_Payment_BaseIPN();
273
274 $pdfElements['params'] = $params;
275
276 $pdfElements['createPdf'] = FALSE;
277 if (!empty($pdfElements['params']['output']) &&
278 ($pdfElements['params']['output'] == "pdf_invoice" || $pdfElements['params']['output'] == "pdf_receipt")
279 ) {
280 $pdfElements['createPdf'] = TRUE;
281 }
282
283 $excludeContactIds = array();
284 if (!$pdfElements['createPdf']) {
285 $returnProperties = array(
286 'email' => 1,
287 'do_not_email' => 1,
288 'is_deceased' => 1,
289 'on_hold' => 1,
290 );
291
292 list($contactDetails) = CRM_Utils_Token::getTokenDetails($contactIds, $returnProperties, FALSE, FALSE);
293 $pdfElements['suppressedEmails'] = 0;
294 $suppressedEmails = 0;
295 foreach ($contactDetails as $id => $values) {
296 if (empty($values['email']) ||
297 (empty($params['override_privacy']) && !empty($values['do_not_email']))
298 || CRM_Utils_Array::value('is_deceased', $values)
299 || !empty($values['on_hold'])
300 ) {
301 $suppressedEmails++;
302 $pdfElements['suppressedEmails'] = $suppressedEmails;
303 $excludeContactIds[] = $values['contact_id'];
304 }
305 }
306 }
307 $pdfElements['excludeContactIds'] = $excludeContactIds;
308
309 return $pdfElements;
310 }
311
312 }