Merge pull request #6680 from colemanw/cleanup
[civicrm-core.git] / CRM / Contribute / Form / Task / Invoice.php
CommitLineData
b8df2a80
RK
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
b8df2a80 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
b8df2a80
RK
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
b8df2a80
RK
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
b8df2a80
RK
32 */
33
34/**
35 * This class provides the functionality to email a group of
36 * contacts.
37 */
38class CRM_Contribute_Form_Task_Invoice extends CRM_Contribute_Form_Task {
dce4c3ea 39 /**
b8df2a80
RK
40 * Are we operating in "single mode", i.e. updating the task of only
41 * one specific contribution?
42 *
43 * @var boolean
44 */
45 public $_single = FALSE;
46
3a1261ac 47 /**
fe482240 48 * Gives all the statues for conribution.
3a1261ac
RK
49 */
50 public $_contributionStatusId;
51
52 /**
fe482240 53 * Gives the HTML template of PDF Invoice.
3a1261ac
RK
54 */
55 public $_messageInvoice;
56
57 /**
fe482240 58 * This variable is used to assign parameters for HTML template of PDF Invoice.
3a1261ac
RK
59 */
60 public $_invoiceTemplate;
dce4c3ea 61
830b3e83 62 /**
fe482240 63 * Selected output.
830b3e83 64 */
65 public $_selectedOutput;
66
b8df2a80 67 /**
fe482240 68 * Build all the data structures needed to build the form.
dce4c3ea 69 */
00be9182 70 public function preProcess() {
b8df2a80
RK
71 $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
72 if ($id) {
73 $this->_contributionIds = array($id);
74 $this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
75 $this->_single = TRUE;
76 $this->assign('totalSelectedContributions', 1);
b5c3483d 77
78 // set the redirection after actions
79 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE);
80 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
81 "action=view&reset=1&id={$id}&cid={$contactId}&context=contribution&selectedChild=contribute"
82 );
83
84 CRM_Core_Session::singleton()->pushUserContext($url);
b8df2a80
RK
85 }
86 else {
87 parent::preProcess();
88 }
dce4c3ea 89
3a1261ac
RK
90 // check that all the contribution ids have status Completed, Pending, Refunded.
91 $this->_contributionStatusId = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
92 $status = array('Completed', 'Pending', 'Refunded');
93 $statusId = array();
94 foreach ($this->_contributionStatusId as $key => $value) {
95 if (in_array($value, $status)) {
2826a42e 96 $statusId[] = $key;
3a1261ac
RK
97 }
98 }
99 $Id = implode(",", $statusId);
100 $query = "SELECT count(*) FROM civicrm_contribution WHERE contribution_status_id NOT IN ($Id) AND {$this->_componentClause}";
b8df2a80
RK
101 $count = CRM_Core_DAO::singleValueQuery($query);
102 if ($count != 0) {
f2d5e719 103 CRM_Core_Error::statusBounce(ts('Please select only contributions with Completed, Pending, Refunded status.'));
b8df2a80 104 }
dce4c3ea 105
b8df2a80
RK
106 // we have all the contribution ids, so now we get the contact ids
107 parent::setContactIDs();
108 $this->assign('single', $this->_single);
dce4c3ea 109
b8df2a80
RK
110 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
111 $urlParams = 'force=1';
112 if (CRM_Utils_Rule::qfKey($qfKey)) {
113 $urlParams .= "&qfKey=$qfKey";
114 }
dce4c3ea 115
b8df2a80
RK
116 $url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
117 $breadCrumb = array(
dce4c3ea 118 array(
119 'url' => $url,
120 'title' => ts('Search Results'),
21dfd5f5 121 ),
dce4c3ea 122 );
123
b8df2a80 124 CRM_Utils_System::appendBreadCrumb($breadCrumb);
830b3e83 125
126 $this->_selectedOutput = CRM_Utils_Request::retrieve('select', 'String', $this);
127 $this->assign('selectedOutput', $this->_selectedOutput);
128
129 if ($this->_selectedOutput == 'email') {
6efffa5d 130 CRM_Utils_System::setTitle(ts('Email Invoice'));
dce4c3ea 131 }
132 else {
6efffa5d
PB
133 CRM_Utils_System::setTitle(ts('Print Contribution Invoice'));
134 }
b8df2a80 135 }
dce4c3ea 136
b8df2a80 137 /**
fe482240 138 * Build the form object.
b8df2a80
RK
139 */
140 public function buildQuickForm() {
6efffa5d 141 $session = CRM_Core_Session::singleton();
33313a73 142 $this->preventAjaxSubmit();
6efffa5d
PB
143 if (CRM_Core_Permission::check('administer CiviCRM')) {
144 $this->assign('isAdmin', 1);
145 }
6f39f13a
PB
146 $contactID = $session->get('userID');
147 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
148 $emails = array();
149 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
dce4c3ea 150 $contactID, 'display_name'
151 );
6f39f13a
PB
152 foreach ($contactEmails as $emailId => $item) {
153 $email = $item['email'];
154 if ($email) {
155 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
6efffa5d 156 }
6f39f13a
PB
157 if (isset($emails[$emailId])) {
158 $emails[$emailId] .= $item['locationType'];
159 if ($item['is_primary']) {
160 $emails[$emailId] .= ' ' . ts('(preferred)');
161 }
162 $emails[$emailId] = htmlspecialchars($emails[$emailId]);
6efffa5d
PB
163 }
164 }
6f39f13a
PB
165 $fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address');
166 foreach ($fromEmailAddress as $key => $email) {
167 $fromEmailAddress[$key] = htmlspecialchars($fromEmailAddress[$key]);
168 }
169 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, $fromEmailAddress);
6f39f13a 170 $this->add('select', 'from_email_address', ts('From Email Address'), array('' => '- select -') + $fromEmail);
830b3e83 171 if ($this->_selectedOutput != 'email') {
172 $this->addElement('radio', 'output', NULL, ts('Email Invoice'), 'email_invoice');
173 $this->addElement('radio', 'output', NULL, ts('PDF Invoice'), 'pdf_invoice');
174 $this->addRule('output', ts('Selection required'), 'required');
175 $this->addFormRule(array('CRM_Contribute_Form_Task_Invoice', 'formRule'));
176 }
177 else {
178 $this->addRule('from_email_address', ts('From Email Address is required'), 'required');
179 }
180
5d51a2f9 181 $this->add('wysiwyg', 'email_comment', ts('If you would like to add personal message to email please add it here. (If sending to more then one receipient the same message will be sent to each contact.)'), array(
dce4c3ea 182 'rows' => 2,
21dfd5f5 183 'cols' => 40,
dce4c3ea 184 ));
6efffa5d 185
8c779cf8
CW
186 $this->addButtons(array(
187 array(
188 'type' => 'upload',
189 'name' => $this->_selectedOutput == 'email' ? ts('Send Email') : ts('Process Invoice(s)'),
190 'isDefault' => TRUE,
191 ),
192 array(
193 'type' => 'cancel',
194 'name' => ts('Cancel'),
195 ),
196 )
197 );
b8df2a80 198 }
6f39f13a
PB
199
200 /**
fe482240 201 * Global validation rules for the form.
6f39f13a 202 *
c490a46a 203 * @param array $values
6f39f13a 204 *
a6c01b45
CW
205 * @return array
206 * list of errors to be posted back to the form
6f39f13a 207 */
00be9182 208 public static function formRule($values) {
6f39f13a 209 $errors = array();
830b3e83 210
211 if ($values['output'] == 'email_invoice' && empty($values['from_email_address'])) {
212 $errors['from_email_address'] = ts("From Email Address is required");
6f39f13a 213 }
830b3e83 214
6f39f13a 215 return $errors;
b8df2a80 216 }
dce4c3ea 217
218 /**
fe482240 219 * Process the form after the input has been submitted and validated.
b8df2a80
RK
220 */
221 public function postProcess() {
6efffa5d 222 $params = $this->controller->exportValues($this->_name);
b5c3483d 223 $this->printPDF($this->_contributionIds, $params, $this->_contactIds, $this);
6efffa5d
PB
224 }
225
dce4c3ea 226 /**
95cdcc0f 227 * Process the PDf and email with activity and attachment on click of Print Invoices.
dce4c3ea 228 *
014c4014
TO
229 * @param array $contribIDs
230 * Contribution Id.
231 * @param array $params
232 * Associated array of submitted values.
233 * @param array $contactIds
234 * Contact Id.
235 * @param CRM_Core_Form $form
236 * Form object.
6efffa5d 237 */
00be9182 238 public static function printPDF($contribIDs, &$params, $contactIds, &$form) {
b8df2a80 239 // get all the details needed to generate a invoice
6efffa5d 240 $messageInvoice = array();
6efffa5d 241 $invoiceTemplate = CRM_Core_Smarty::singleton();
6efffa5d 242 $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
dce4c3ea 243
3a1261ac 244 // gives the status id when contribution status is 'Refunded'
6efffa5d
PB
245 $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
246 $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
f2d5e719
RK
247
248 // getting data from admin page
dce4c3ea 249 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
250
2826a42e 251 foreach ($invoiceElements['details'] as $contribID => $detail) {
b8df2a80 252 $input = $ids = $objects = array();
3a1261ac 253 if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
b8df2a80
RK
254 continue;
255 }
dce4c3ea 256
b8df2a80 257 $input['component'] = $detail['component'];
dce4c3ea 258
b8df2a80 259 $ids['contact'] = $detail['contact'];
2826a42e 260 $ids['contribution'] = $contribID;
b8df2a80
RK
261 $ids['contributionRecur'] = NULL;
262 $ids['contributionPage'] = NULL;
263 $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
264 $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
265 $ids['event'] = CRM_Utils_Array::value('event', $detail);
dce4c3ea 266
3a1261ac 267 if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
b8df2a80
RK
268 CRM_Core_Error::fatal();
269 }
dce4c3ea 270
353ffa53 271 $contribution = &$objects['contribution'];
dce4c3ea 272
b8df2a80
RK
273 $input['amount'] = $contribution->total_amount;
274 $input['invoice_id'] = $contribution->invoice_id;
275 $input['receive_date'] = $contribution->receive_date;
b8df2a80
RK
276 $input['contribution_status_id'] = $contribution->contribution_status_id;
277 $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
dce4c3ea 278
b8df2a80 279 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
dce4c3ea 280
b8df2a80
RK
281 $addressParams = array('contact_id' => $contribution->contact_id);
282 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
dce4c3ea 283
d75f2f47 284 // to get billing address if present
b8df2a80
RK
285 $billingAddress = array();
286 foreach ($addressDetails as $key => $address) {
287 if ((isset($address['is_billing']) && $address['is_billing'] == 1) && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
288 $billingAddress[$address['contact_id']] = $address;
289 break;
290 }
291 elseif (($address['is_billing'] == 0 && $address['is_primary'] == 1) || (isset($address['is_billing']) && $address['is_billing'] == 1) && $address['contact_id'] == $contribution->contact_id) {
292 $billingAddress[$address['contact_id']] = $address;
293 }
294 }
dce4c3ea 295
6efffa5d
PB
296 if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
297 $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
298 }
299 else {
300 $stateProvinceAbbreviation = '';
301 }
dce4c3ea 302
3a1261ac 303 if ($contribution->contribution_status_id == $refundedStatusId) {
933c5f44 304 $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id;
b8df2a80 305 }
933c5f44 306 $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
dce4c3ea 307
b8df2a80
RK
308 //to obtain due date for PDF invoice
309 $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
310 $invoiceDate = date("F j, Y");
dce4c3ea 311 $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
312
b8df2a80 313 if ($input['component'] == 'contribute') {
2826a42e 314 $eid = $contribID;
dce4c3ea 315 $etable = 'contribution';
e3bc5abd 316 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE);
dce4c3ea 317 }
b8df2a80
RK
318 else {
319 $eid = $contribution->_relatedObjects['participant']->id;
320 $etable = 'participant';
25d0c647 321 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, FALSE, '', TRUE);
b8df2a80 322 }
dce4c3ea 323
d75f2f47 324 //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
b8df2a80 325 $amountDue = ($input['amount'] - $input['amount']);
dce4c3ea 326
d75f2f47 327 // retreiving the subtotal and sum of same tax_rate
b8df2a80
RK
328 $dataArray = array();
329 $subTotal = 0;
330 foreach ($lineItem as $entity_id => $taxRate) {
dce4c3ea 331 if (isset($dataArray[(string) $taxRate['tax_rate']])) {
332 $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
b8df2a80
RK
333 }
334 else {
dce4c3ea 335 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
b8df2a80
RK
336 }
337 $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
338 }
dce4c3ea 339
b8df2a80
RK
340 // to email the invoice
341 $mailDetails = array();
342 $values = array();
343 if ($contribution->_component == 'event') {
344 $daoName = 'CRM_Event_DAO_Event';
345 $pageId = $contribution->_relatedObjects['event']->id;
346 $mailElements = array(
dce4c3ea 347 'title',
348 'confirm_from_name',
349 'confirm_from_email',
350 'cc_confirm',
351 'bcc_confirm',
352 );
b8df2a80 353 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
b8df2a80
RK
354 $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
355 $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
356 $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
357 $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
358 $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
dce4c3ea 359
b8df2a80
RK
360 $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
361 }
362 elseif ($contribution->_component == 'contribute') {
363 $daoName = 'CRM_Contribute_DAO_ContributionPage';
364 $pageId = $contribution->contribution_page_id;
365 $mailElements = array(
dce4c3ea 366 'title',
367 'receipt_from_name',
368 'receipt_from_email',
369 'cc_receipt',
370 'bcc_receipt',
371 );
b8df2a80 372 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
6efffa5d 373
dce4c3ea 374 $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
6efffa5d
PB
375 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
376 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
377 $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
378 $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
379
380 $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
b8df2a80 381 }
d88a0337 382 $source = $contribution->source;
dce4c3ea 383
b8df2a80 384 $config = CRM_Core_Config::singleton();
c4d3b8d3 385 if (!isset($params['forPage'])) {
d88a0337
PD
386 $config->doNotAttachPDFReceipt = 1;
387 }
388
389 // get organization address
390 $domain = CRM_Core_BAO_Domain::getDomain();
48fcab8e 391 $locParams = array('contact_id' => $domain->contact_id);
b69fc6b5 392 $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
d88a0337 393 if (isset($locationDefaults['address'][1]['state_province_id'])) {
dce4c3ea 394 $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
d88a0337
PD
395 }
396 else {
397 $stateProvinceAbbreviationDomain = '';
398 }
399 if (isset($locationDefaults['address'][1]['country_id'])) {
dce4c3ea 400 $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
d88a0337
PD
401 }
402 else {
403 $countryDomain = '';
404 }
6efffa5d 405
b8df2a80
RK
406 // parameters to be assign for template
407 $tplParams = array(
dce4c3ea 408 'title' => $title,
409 'component' => $input['component'],
410 'id' => $contribution->id,
411 'source' => $source,
412 'invoice_id' => $invoiceId,
9f8fe885 413 'resourceBase' => $config->userFrameworkResourceURL,
dce4c3ea 414 'defaultCurrency' => $config->defaultCurrency,
415 'amount' => $contribution->total_amount,
416 'amountDue' => $amountDue,
417 'invoice_date' => $invoiceDate,
418 'dueDate' => $dueDate,
419 'notes' => CRM_Utils_Array::value('notes', $prefixValue),
420 'display_name' => $contribution->_relatedObjects['contact']->display_name,
421 'lineItem' => $lineItem,
422 'dataArray' => $dataArray,
423 'refundedStatusId' => $refundedStatusId,
424 'contribution_status_id' => $contribution->contribution_status_id,
425 'subTotal' => $subTotal,
426 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
427 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
428 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
429 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
430 'stateProvinceAbbreviation' => $stateProvinceAbbreviation,
431 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
432 'is_pay_later' => $contribution->is_pay_later,
433 'organization_name' => $contribution->_relatedObjects['contact']->organization_name,
434 'domain_organization' => $domain->name,
435 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])),
436 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])),
437 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])),
438 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])),
439 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])),
440 'domain_state' => $stateProvinceAbbreviationDomain,
441 'domain_country' => $countryDomain,
442 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])),
443 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])),
444 );
dc0bdd34 445
c4d3b8d3
PD
446 if (isset($creditNoteId)) {
447 $tplParams['creditnote_id'] = $creditNoteId;
448 }
d75f2f47 449
c119e8ae 450 $pdfFileName = "{$invoiceId}.pdf";
b8df2a80 451 $sendTemplateParams = array(
dce4c3ea 452 'groupName' => 'msg_tpl_workflow_contribution',
453 'valueName' => 'contribution_invoice_receipt',
454 'contactId' => $contribution->contact_id,
455 'tplParams' => $tplParams,
c119e8ae 456 'PDFFilename' => $pdfFileName,
dce4c3ea 457 );
6f39f13a 458 $session = CRM_Core_Session::singleton();
e14cf9e2 459 $contactID = $session->get('userID');
3f81ea25 460 //CRM-16319 - we dont store in userID in case the user is doing multiple
461 //transactions etc
e14cf9e2 462 if (empty($contactID)) {
463 $contactID = $session->get('transaction.userID');
464 }
6f39f13a
PB
465 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
466 $emails = array();
467 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
dce4c3ea 468 $contactID, 'display_name'
469 );
6f39f13a
PB
470
471 foreach ($contactEmails as $emailId => $item) {
472 $email = $item['email'];
473 if ($email) {
474 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
475 }
476 }
477 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
dce4c3ea 478
6efffa5d
PB
479 // from email address
480 if (isset($params['from_email_address'])) {
6f39f13a 481 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
6efffa5d 482 }
b8df2a80 483 // condition to check for download PDF Invoice or email Invoice
3a1261ac 484 if ($invoiceElements['createPdf']) {
b8df2a80 485 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
c4d3b8d3 486 if (isset($params['forPage'])) {
d88a0337
PD
487 return $html;
488 }
b8df2a80 489 else {
d88a0337
PD
490 $mail = array(
491 'subject' => $subject,
dce4c3ea 492 'body' => $message,
d88a0337 493 'html' => $html,
dce4c3ea 494 );
d88a0337
PD
495 if ($mail['html']) {
496 $messageInvoice[] = $mail['html'];
dce4c3ea 497 }
d88a0337
PD
498 else {
499 $messageInvoice[] = nl2br($mail['body']);
500 }
b8df2a80
RK
501 }
502 }
503 elseif ($contribution->_component == 'contribute') {
504 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
dce4c3ea 505
506 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
6efffa5d 507 $sendTemplateParams['from'] = $fromEmailAddress;
b8df2a80
RK
508 $sendTemplateParams['toEmail'] = $email;
509 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
510 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
dce4c3ea 511
512 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6efffa5d 513 // functions call for adding activity with attachment
c119e8ae 514 $pdfFileName = "{$invoiceId}.pdf";
515 $fileName = self::putFile($html, $pdfFileName);
6efffa5d 516 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
b8df2a80
RK
517 }
518 elseif ($contribution->_component == 'event') {
519 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
dce4c3ea 520
521 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
6efffa5d 522 $sendTemplateParams['from'] = $fromEmailAddress;
b8df2a80
RK
523 $sendTemplateParams['toEmail'] = $email;
524 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
525 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
dce4c3ea 526
527 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6efffa5d 528 // functions call for adding activity with attachment
c119e8ae 529 $pdfFileName = "{$invoiceId}.pdf";
530 $fileName = self::putFile($html, $pdfFileName);
6efffa5d 531 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
b8df2a80 532 }
dce4c3ea 533
534 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
933c5f44 535 if ($contribution->contribution_status_id == $refundedStatusId) {
dce4c3ea 536 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
933c5f44 537 }
6efffa5d 538 $invoiceTemplate->clearTemplateVars();
b8df2a80 539 }
dce4c3ea 540
3a1261ac 541 if ($invoiceElements['createPdf']) {
c4d3b8d3 542 if (isset($params['forPage'])) {
d88a0337
PD
543 return $html;
544 }
545 else {
c119e8ae 546 $pdfFileName = "{$invoiceId}.pdf";
547 CRM_Utils_PDF_Utils::html2pdf($messageInvoice, $pdfFileName, FALSE, array(
dce4c3ea 548 'margin_top' => 10,
549 'margin_left' => 65,
21dfd5f5 550 'metric' => 'px',
dce4c3ea 551 ));
d88a0337 552 // functions call for adding activity with attachment
c119e8ae 553 $fileName = self::putFile($html, $pdfFileName);
413796ce 554 self::addActivities($subject, $contactIds, $fileName, $params);
6efffa5d 555
d88a0337
PD
556 CRM_Utils_System::civiExit();
557 }
b8df2a80
RK
558 }
559 else {
3a1261ac
RK
560 if ($invoiceElements['suppressedEmails']) {
561 $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 => $invoiceElements['suppressedEmails']));
b8df2a80
RK
562 $msgTitle = ts('Email Error');
563 $msgType = 'error';
564 }
565 else {
566 $status = ts('Your mail has been sent.');
567 $msgTitle = ts('Sent');
568 $msgType = 'success';
569 }
570 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
571 }
572 }
6efffa5d 573
dce4c3ea 574 /**
fe482240 575 * Add activity for Email Invoice and the PDF Invoice.
6efffa5d 576 *
014c4014
TO
577 * @param string $subject
578 * Activity subject.
579 * @param array $contactIds
580 * Contact Id.
581 * @param string $fileName
582 * Gives the location with name of the file.
583 * @param array $params
584 * For invoices.
6efffa5d
PB
585 *
586 */
413796ce 587 static public function addActivities($subject, $contactIds, $fileName, $params) {
dce4c3ea 588 $session = CRM_Core_Session::singleton();
589 $userID = $session->get('userID');
6efffa5d
PB
590 $config = CRM_Core_Config::singleton();
591 $config->doNotAttachPDFReceipt = 1;
413796ce 592
593 if (!empty($params['output']) && $params['output'] == 'pdf_invoice') {
6efffa5d 594 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
413796ce 595 'Downloaded Invoice',
6efffa5d
PB
596 'name'
597 );
dce4c3ea 598 }
92e4c2a5 599 else {
6efffa5d 600 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
413796ce 601 'Emailed Invoice',
6efffa5d
PB
602 'name'
603 );
604 }
413796ce 605
6efffa5d
PB
606 $activityParams = array(
607 'subject' => $subject,
608 'source_contact_id' => $userID,
609 'target_contact_id' => $contactIds,
610 'activity_type_id' => $activityTypeID,
611 'activity_date_time' => date('YmdHis'),
dce4c3ea 612 'attachFile_1' => array(
613 'uri' => $fileName,
614 'type' => 'application/pdf',
615 'location' => $fileName,
616 'upload_date' => date('YmdHis'),
617 ),
6efffa5d 618 );
dce4c3ea 619 CRM_Activity_BAO_Activity::create($activityParams);
6efffa5d 620 }
dce4c3ea 621
622 /**
fe482240 623 * Create the Invoice file in upload folder for attachment.
dce4c3ea 624 *
76e7a76c 625 * @param string $html
014c4014 626 * Content for pdf in html format.
6efffa5d 627 *
03110609 628 * @return string
76e7a76c 629 * Name of file which is in pdf format
6efffa5d 630 */
c119e8ae 631 static public function putFile($html, $name = 'Invoice.pdf') {
33313a73 632 require_once "vendor/dompdf/dompdf/dompdf_config.inc.php";
6efffa5d
PB
633 $doc = new DOMPDF();
634 $doc->load_html($html);
635 $doc->render();
636 $html = $doc->output();
637 $config = CRM_Core_Config::singleton();
c119e8ae 638 $fileName = $config->uploadDir . $name;
dce4c3ea 639 file_put_contents($fileName, $html);
6efffa5d
PB
640 return $fileName;
641 }
b5c3483d 642
643 /**
644 * Callback to perform action on Print Invoice button.
645 */
00be9182 646 public static function getPrintPDF() {
b5c3483d 647 $contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
648 $contributionIDs = array($contributionId);
649 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
650 $params = array('output' => 'pdf_invoice');
651 CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId, CRM_Core_DAO::$_nullObject);
652 }
96025800 653
b8df2a80 654}