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