CRM-20851 php notice (#10639)
[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 }
9cad3ff4 315 $invoiceNumber = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
dce4c3ea 316
b8df2a80
RK
317 //to obtain due date for PDF invoice
318 $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
319 $invoiceDate = date("F j, Y");
dce4c3ea 320 $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
321
b8df2a80 322 if ($input['component'] == 'contribute') {
77dbdcbc 323 $lineItem = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contribID);
dce4c3ea 324 }
b8df2a80
RK
325 else {
326 $eid = $contribution->_relatedObjects['participant']->id;
77dbdcbc 327 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, 'participant', NULL, TRUE, FALSE, TRUE);
b8df2a80 328 }
dce4c3ea 329
8f4f19ca
K
330 $resultPayments = civicrm_api3('Payment', 'get', array(
331 'sequential' => 1,
332 'contribution_id' => $contribID,
333 ));
334 $amountPaid = 0;
77680511 335 foreach ($resultPayments['values'] as $singlePayment) {
c12b5af4 336 // Only count payments that have been (status =) completed.
8f4f19ca
K
337 if ($singlePayment['status_id'] == 1) {
338 $amountPaid += $singlePayment['total_amount'];
339 }
340 }
341 $amountDue = ($input['amount'] - $amountPaid);
dce4c3ea 342
8f4f19ca 343 // retrieving the subtotal and sum of same tax_rate
b8df2a80
RK
344 $dataArray = array();
345 $subTotal = 0;
fd9e1183 346 foreach ($lineItem as $taxRate) {
dce4c3ea 347 if (isset($dataArray[(string) $taxRate['tax_rate']])) {
348 $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
b8df2a80
RK
349 }
350 else {
dce4c3ea 351 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
b8df2a80
RK
352 }
353 $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
354 }
dce4c3ea 355
b8df2a80
RK
356 // to email the invoice
357 $mailDetails = array();
358 $values = array();
359 if ($contribution->_component == 'event') {
360 $daoName = 'CRM_Event_DAO_Event';
361 $pageId = $contribution->_relatedObjects['event']->id;
362 $mailElements = array(
dce4c3ea 363 'title',
364 'confirm_from_name',
365 'confirm_from_email',
366 'cc_confirm',
367 'bcc_confirm',
368 );
b8df2a80 369 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
b8df2a80
RK
370 $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
371 $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
372 $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
373 $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
374 $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
dce4c3ea 375
b8df2a80
RK
376 $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
377 }
378 elseif ($contribution->_component == 'contribute') {
379 $daoName = 'CRM_Contribute_DAO_ContributionPage';
380 $pageId = $contribution->contribution_page_id;
381 $mailElements = array(
dce4c3ea 382 'title',
383 'receipt_from_name',
384 'receipt_from_email',
385 'cc_receipt',
386 'bcc_receipt',
387 );
b8df2a80 388 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
6efffa5d 389
dce4c3ea 390 $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
6efffa5d
PB
391 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
392 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
393 $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
394 $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
395
396 $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
b8df2a80 397 }
d88a0337 398 $source = $contribution->source;
dce4c3ea 399
b8df2a80 400 $config = CRM_Core_Config::singleton();
c4d3b8d3 401 if (!isset($params['forPage'])) {
d88a0337
PD
402 $config->doNotAttachPDFReceipt = 1;
403 }
404
405 // get organization address
406 $domain = CRM_Core_BAO_Domain::getDomain();
48fcab8e 407 $locParams = array('contact_id' => $domain->contact_id);
b69fc6b5 408 $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
d88a0337 409 if (isset($locationDefaults['address'][1]['state_province_id'])) {
dce4c3ea 410 $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
d88a0337
PD
411 }
412 else {
413 $stateProvinceAbbreviationDomain = '';
414 }
415 if (isset($locationDefaults['address'][1]['country_id'])) {
dce4c3ea 416 $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
d88a0337
PD
417 }
418 else {
419 $countryDomain = '';
420 }
6efffa5d 421
b8df2a80
RK
422 // parameters to be assign for template
423 $tplParams = array(
dce4c3ea 424 'title' => $title,
425 'component' => $input['component'],
426 'id' => $contribution->id,
427 'source' => $source,
9cad3ff4
CW
428 'invoice_number' => $invoiceNumber,
429 'invoice_id' => $contribution->invoice_id,
9f8fe885 430 'resourceBase' => $config->userFrameworkResourceURL,
dce4c3ea 431 'defaultCurrency' => $config->defaultCurrency,
432 'amount' => $contribution->total_amount,
433 'amountDue' => $amountDue,
77680511 434 'amountPaid' => $amountPaid,
dce4c3ea 435 'invoice_date' => $invoiceDate,
436 'dueDate' => $dueDate,
437 'notes' => CRM_Utils_Array::value('notes', $prefixValue),
438 'display_name' => $contribution->_relatedObjects['contact']->display_name,
439 'lineItem' => $lineItem,
440 'dataArray' => $dataArray,
441 'refundedStatusId' => $refundedStatusId,
2f3e0ab6 442 'pendingStatusId' => $pendingStatusId,
41e050b3 443 'cancelledStatusId' => $cancelledStatusId,
dce4c3ea 444 'contribution_status_id' => $contribution->contribution_status_id,
445 'subTotal' => $subTotal,
446 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
447 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
448 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
207f62c6 449 'supplemental_address_3' => CRM_Utils_Array::value('supplemental_address_3', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
dce4c3ea 450 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
451 'stateProvinceAbbreviation' => $stateProvinceAbbreviation,
452 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
453 'is_pay_later' => $contribution->is_pay_later,
454 'organization_name' => $contribution->_relatedObjects['contact']->organization_name,
455 'domain_organization' => $domain->name,
456 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])),
457 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])),
458 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])),
207f62c6 459 'domain_supplemental_address_3' => CRM_Utils_Array::value('supplemental_address_3', CRM_Utils_Array::value('1', $locationDefaults['address'])),
dce4c3ea 460 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])),
461 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])),
462 'domain_state' => $stateProvinceAbbreviationDomain,
463 'domain_country' => $countryDomain,
464 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])),
465 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])),
466 );
dc0bdd34 467
c4d3b8d3
PD
468 if (isset($creditNoteId)) {
469 $tplParams['creditnote_id'] = $creditNoteId;
470 }
d75f2f47 471
9cad3ff4 472 $pdfFileName = "{$invoiceNumber}.pdf";
b8df2a80 473 $sendTemplateParams = array(
dce4c3ea 474 'groupName' => 'msg_tpl_workflow_contribution',
475 'valueName' => 'contribution_invoice_receipt',
476 'contactId' => $contribution->contact_id,
477 'tplParams' => $tplParams,
c119e8ae 478 'PDFFilename' => $pdfFileName,
dce4c3ea 479 );
6f39f13a 480 $session = CRM_Core_Session::singleton();
e14cf9e2 481 $contactID = $session->get('userID');
3f81ea25 482 //CRM-16319 - we dont store in userID in case the user is doing multiple
483 //transactions etc
e14cf9e2 484 if (empty($contactID)) {
485 $contactID = $session->get('transaction.userID');
486 }
0a6a6d20
C
487 // Fix Invoice email doesnot send out when completed payment using Paypal
488 if (empty($contactID)) {
4d0cca48 489 $contactID = current($contactIds);
0a6a6d20 490 }
6f39f13a
PB
491 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
492 $emails = array();
493 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
dce4c3ea 494 $contactID, 'display_name'
495 );
6f39f13a
PB
496
497 foreach ($contactEmails as $emailId => $item) {
498 $email = $item['email'];
499 if ($email) {
500 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
501 }
502 }
503 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
dce4c3ea 504
6efffa5d
PB
505 // from email address
506 if (isset($params['from_email_address'])) {
6f39f13a 507 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
6efffa5d 508 }
b8df2a80 509 // condition to check for download PDF Invoice or email Invoice
3a1261ac 510 if ($invoiceElements['createPdf']) {
b8df2a80 511 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
c4d3b8d3 512 if (isset($params['forPage'])) {
d88a0337
PD
513 return $html;
514 }
b8df2a80 515 else {
d88a0337
PD
516 $mail = array(
517 'subject' => $subject,
dce4c3ea 518 'body' => $message,
d88a0337 519 'html' => $html,
dce4c3ea 520 );
d88a0337
PD
521 if ($mail['html']) {
522 $messageInvoice[] = $mail['html'];
dce4c3ea 523 }
d88a0337
PD
524 else {
525 $messageInvoice[] = nl2br($mail['body']);
526 }
b8df2a80
RK
527 }
528 }
529 elseif ($contribution->_component == 'contribute') {
530 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
dce4c3ea 531
532 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
6efffa5d 533 $sendTemplateParams['from'] = $fromEmailAddress;
b8df2a80
RK
534 $sendTemplateParams['toEmail'] = $email;
535 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
536 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
dce4c3ea 537
538 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6efffa5d 539 // functions call for adding activity with attachment
9cad3ff4 540 $pdfFileName = "{$invoiceNumber}.pdf";
c119e8ae 541 $fileName = self::putFile($html, $pdfFileName);
6efffa5d 542 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
b8df2a80
RK
543 }
544 elseif ($contribution->_component == 'event') {
545 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
dce4c3ea 546
547 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
6efffa5d 548 $sendTemplateParams['from'] = $fromEmailAddress;
b8df2a80
RK
549 $sendTemplateParams['toEmail'] = $email;
550 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
551 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
dce4c3ea 552
553 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6efffa5d 554 // functions call for adding activity with attachment
9cad3ff4 555 $pdfFileName = "{$invoiceNumber}.pdf";
c119e8ae 556 $fileName = self::putFile($html, $pdfFileName);
6efffa5d 557 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
b8df2a80 558 }
dce4c3ea 559
9cad3ff4 560 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_number', $invoiceNumber);
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') {
6efffa5d 617 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
413796ce 618 'Downloaded Invoice',
6efffa5d
PB
619 'name'
620 );
dce4c3ea 621 }
92e4c2a5 622 else {
6efffa5d 623 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
413796ce 624 'Emailed Invoice',
6efffa5d
PB
625 'name'
626 );
627 }
413796ce 628
6efffa5d
PB
629 $activityParams = array(
630 'subject' => $subject,
631 'source_contact_id' => $userID,
632 'target_contact_id' => $contactIds,
633 'activity_type_id' => $activityTypeID,
634 'activity_date_time' => date('YmdHis'),
dce4c3ea 635 'attachFile_1' => array(
636 'uri' => $fileName,
637 'type' => 'application/pdf',
638 'location' => $fileName,
639 'upload_date' => date('YmdHis'),
640 ),
6efffa5d 641 );
dce4c3ea 642 CRM_Activity_BAO_Activity::create($activityParams);
6efffa5d 643 }
dce4c3ea 644
645 /**
fe482240 646 * Create the Invoice file in upload folder for attachment.
dce4c3ea 647 *
76e7a76c 648 * @param string $html
014c4014 649 * Content for pdf in html format.
6efffa5d 650 *
ad37ac8e 651 * @param string $name
652 *
03110609 653 * @return string
76e7a76c 654 * Name of file which is in pdf format
6efffa5d 655 */
c119e8ae 656 static public function putFile($html, $name = 'Invoice.pdf') {
6ae4d5d7 657 $options = new Options();
4f31930a 658 $options->set('isRemoteEnabled', TRUE);
6ae4d5d7 659
4f31930a 660 $doc = new DOMPDF($options);
6efffa5d
PB
661 $doc->load_html($html);
662 $doc->render();
663 $html = $doc->output();
664 $config = CRM_Core_Config::singleton();
c119e8ae 665 $fileName = $config->uploadDir . $name;
dce4c3ea 666 file_put_contents($fileName, $html);
6efffa5d
PB
667 return $fileName;
668 }
b5c3483d 669
670 /**
671 * Callback to perform action on Print Invoice button.
672 */
00be9182 673 public static function getPrintPDF() {
b5c3483d 674 $contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
675 $contributionIDs = array($contributionId);
676 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
677 $params = array('output' => 'pdf_invoice');
1273d77c 678 CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId);
b5c3483d 679 }
96025800 680
b8df2a80 681}