Refactor redundant code with reusable function
[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);
41e050b3 247 $cancelledStatusId = CRM_Utils_Array::key('Cancelled', $contributionStatusID);
f2d5e719
RK
248
249 // getting data from admin page
dce4c3ea 250 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
251
2826a42e 252 foreach ($invoiceElements['details'] as $contribID => $detail) {
b8df2a80 253 $input = $ids = $objects = array();
3a1261ac 254 if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
b8df2a80
RK
255 continue;
256 }
dce4c3ea 257
b8df2a80 258 $input['component'] = $detail['component'];
dce4c3ea 259
b8df2a80 260 $ids['contact'] = $detail['contact'];
2826a42e 261 $ids['contribution'] = $contribID;
b8df2a80
RK
262 $ids['contributionRecur'] = NULL;
263 $ids['contributionPage'] = NULL;
264 $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
265 $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
266 $ids['event'] = CRM_Utils_Array::value('event', $detail);
dce4c3ea 267
3a1261ac 268 if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
b8df2a80
RK
269 CRM_Core_Error::fatal();
270 }
dce4c3ea 271
353ffa53 272 $contribution = &$objects['contribution'];
dce4c3ea 273
b8df2a80
RK
274 $input['amount'] = $contribution->total_amount;
275 $input['invoice_id'] = $contribution->invoice_id;
276 $input['receive_date'] = $contribution->receive_date;
b8df2a80
RK
277 $input['contribution_status_id'] = $contribution->contribution_status_id;
278 $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
dce4c3ea 279
b8df2a80 280 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
dce4c3ea 281
b8df2a80
RK
282 $addressParams = array('contact_id' => $contribution->contact_id);
283 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
dce4c3ea 284
d75f2f47 285 // to get billing address if present
b8df2a80
RK
286 $billingAddress = array();
287 foreach ($addressDetails as $key => $address) {
288 if ((isset($address['is_billing']) && $address['is_billing'] == 1) && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
289 $billingAddress[$address['contact_id']] = $address;
290 break;
291 }
292 elseif (($address['is_billing'] == 0 && $address['is_primary'] == 1) || (isset($address['is_billing']) && $address['is_billing'] == 1) && $address['contact_id'] == $contribution->contact_id) {
293 $billingAddress[$address['contact_id']] = $address;
294 }
295 }
dce4c3ea 296
6efffa5d
PB
297 if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
298 $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
299 }
300 else {
301 $stateProvinceAbbreviation = '';
302 }
dce4c3ea 303
41e050b3 304 if ($contribution->contribution_status_id == $refundedStatusId || $contribution->contribution_status_id == $cancelledStatusId) {
7a48a449 305 if (is_null($contribution->creditnote_id)) {
1844808f 306 $creditNoteId = CRM_Contribute_BAO_Contribution::createCreditNoteId($contribution->id);
7a48a449
GC
307 }
308 else {
309 $creditNoteId = $contribution->creditnote_id;
310 }
b8df2a80 311 }
933c5f44 312 $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
dce4c3ea 313
b8df2a80
RK
314 //to obtain due date for PDF invoice
315 $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
316 $invoiceDate = date("F j, Y");
dce4c3ea 317 $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
318
b8df2a80 319 if ($input['component'] == 'contribute') {
2826a42e 320 $eid = $contribID;
dce4c3ea 321 $etable = 'contribution';
e3bc5abd 322 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE);
dce4c3ea 323 }
b8df2a80
RK
324 else {
325 $eid = $contribution->_relatedObjects['participant']->id;
326 $etable = 'participant';
25d0c647 327 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, FALSE, '', TRUE);
b8df2a80 328 }
dce4c3ea 329
d75f2f47 330 //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
b8df2a80 331 $amountDue = ($input['amount'] - $input['amount']);
dce4c3ea 332
d75f2f47 333 // retreiving the subtotal and sum of same tax_rate
b8df2a80
RK
334 $dataArray = array();
335 $subTotal = 0;
336 foreach ($lineItem as $entity_id => $taxRate) {
dce4c3ea 337 if (isset($dataArray[(string) $taxRate['tax_rate']])) {
338 $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
b8df2a80
RK
339 }
340 else {
dce4c3ea 341 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
b8df2a80
RK
342 }
343 $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
344 }
dce4c3ea 345
b8df2a80
RK
346 // to email the invoice
347 $mailDetails = array();
348 $values = array();
349 if ($contribution->_component == 'event') {
350 $daoName = 'CRM_Event_DAO_Event';
351 $pageId = $contribution->_relatedObjects['event']->id;
352 $mailElements = array(
dce4c3ea 353 'title',
354 'confirm_from_name',
355 'confirm_from_email',
356 'cc_confirm',
357 'bcc_confirm',
358 );
b8df2a80 359 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
b8df2a80
RK
360 $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
361 $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
362 $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
363 $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
364 $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
dce4c3ea 365
b8df2a80
RK
366 $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
367 }
368 elseif ($contribution->_component == 'contribute') {
369 $daoName = 'CRM_Contribute_DAO_ContributionPage';
370 $pageId = $contribution->contribution_page_id;
371 $mailElements = array(
dce4c3ea 372 'title',
373 'receipt_from_name',
374 'receipt_from_email',
375 'cc_receipt',
376 'bcc_receipt',
377 );
b8df2a80 378 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
6efffa5d 379
dce4c3ea 380 $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
6efffa5d
PB
381 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
382 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
383 $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
384 $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
385
386 $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
b8df2a80 387 }
d88a0337 388 $source = $contribution->source;
dce4c3ea 389
b8df2a80 390 $config = CRM_Core_Config::singleton();
c4d3b8d3 391 if (!isset($params['forPage'])) {
d88a0337
PD
392 $config->doNotAttachPDFReceipt = 1;
393 }
394
395 // get organization address
396 $domain = CRM_Core_BAO_Domain::getDomain();
48fcab8e 397 $locParams = array('contact_id' => $domain->contact_id);
b69fc6b5 398 $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
d88a0337 399 if (isset($locationDefaults['address'][1]['state_province_id'])) {
dce4c3ea 400 $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
d88a0337
PD
401 }
402 else {
403 $stateProvinceAbbreviationDomain = '';
404 }
405 if (isset($locationDefaults['address'][1]['country_id'])) {
dce4c3ea 406 $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
d88a0337
PD
407 }
408 else {
409 $countryDomain = '';
410 }
6efffa5d 411
b8df2a80
RK
412 // parameters to be assign for template
413 $tplParams = array(
dce4c3ea 414 'title' => $title,
415 'component' => $input['component'],
416 'id' => $contribution->id,
417 'source' => $source,
418 'invoice_id' => $invoiceId,
9f8fe885 419 'resourceBase' => $config->userFrameworkResourceURL,
dce4c3ea 420 'defaultCurrency' => $config->defaultCurrency,
421 'amount' => $contribution->total_amount,
422 'amountDue' => $amountDue,
423 'invoice_date' => $invoiceDate,
424 'dueDate' => $dueDate,
425 'notes' => CRM_Utils_Array::value('notes', $prefixValue),
426 'display_name' => $contribution->_relatedObjects['contact']->display_name,
427 'lineItem' => $lineItem,
428 'dataArray' => $dataArray,
429 'refundedStatusId' => $refundedStatusId,
41e050b3 430 'cancelledStatusId' => $cancelledStatusId,
dce4c3ea 431 'contribution_status_id' => $contribution->contribution_status_id,
432 'subTotal' => $subTotal,
433 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
434 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
435 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
436 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
437 'stateProvinceAbbreviation' => $stateProvinceAbbreviation,
438 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
439 'is_pay_later' => $contribution->is_pay_later,
440 'organization_name' => $contribution->_relatedObjects['contact']->organization_name,
441 'domain_organization' => $domain->name,
442 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])),
443 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])),
444 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])),
445 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])),
446 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])),
447 'domain_state' => $stateProvinceAbbreviationDomain,
448 'domain_country' => $countryDomain,
449 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])),
450 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])),
451 );
dc0bdd34 452
c4d3b8d3
PD
453 if (isset($creditNoteId)) {
454 $tplParams['creditnote_id'] = $creditNoteId;
455 }
d75f2f47 456
c119e8ae 457 $pdfFileName = "{$invoiceId}.pdf";
b8df2a80 458 $sendTemplateParams = array(
dce4c3ea 459 'groupName' => 'msg_tpl_workflow_contribution',
460 'valueName' => 'contribution_invoice_receipt',
461 'contactId' => $contribution->contact_id,
462 'tplParams' => $tplParams,
c119e8ae 463 'PDFFilename' => $pdfFileName,
dce4c3ea 464 );
6f39f13a 465 $session = CRM_Core_Session::singleton();
e14cf9e2 466 $contactID = $session->get('userID');
3f81ea25 467 //CRM-16319 - we dont store in userID in case the user is doing multiple
468 //transactions etc
e14cf9e2 469 if (empty($contactID)) {
470 $contactID = $session->get('transaction.userID');
471 }
6f39f13a
PB
472 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
473 $emails = array();
474 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
dce4c3ea 475 $contactID, 'display_name'
476 );
6f39f13a
PB
477
478 foreach ($contactEmails as $emailId => $item) {
479 $email = $item['email'];
480 if ($email) {
481 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
482 }
483 }
484 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
dce4c3ea 485
6efffa5d
PB
486 // from email address
487 if (isset($params['from_email_address'])) {
6f39f13a 488 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
6efffa5d 489 }
b8df2a80 490 // condition to check for download PDF Invoice or email Invoice
3a1261ac 491 if ($invoiceElements['createPdf']) {
b8df2a80 492 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
c4d3b8d3 493 if (isset($params['forPage'])) {
d88a0337
PD
494 return $html;
495 }
b8df2a80 496 else {
d88a0337
PD
497 $mail = array(
498 'subject' => $subject,
dce4c3ea 499 'body' => $message,
d88a0337 500 'html' => $html,
dce4c3ea 501 );
d88a0337
PD
502 if ($mail['html']) {
503 $messageInvoice[] = $mail['html'];
dce4c3ea 504 }
d88a0337
PD
505 else {
506 $messageInvoice[] = nl2br($mail['body']);
507 }
b8df2a80
RK
508 }
509 }
510 elseif ($contribution->_component == 'contribute') {
511 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
dce4c3ea 512
513 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
6efffa5d 514 $sendTemplateParams['from'] = $fromEmailAddress;
b8df2a80
RK
515 $sendTemplateParams['toEmail'] = $email;
516 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
517 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
dce4c3ea 518
519 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6efffa5d 520 // functions call for adding activity with attachment
c119e8ae 521 $pdfFileName = "{$invoiceId}.pdf";
522 $fileName = self::putFile($html, $pdfFileName);
6efffa5d 523 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
b8df2a80
RK
524 }
525 elseif ($contribution->_component == 'event') {
526 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
dce4c3ea 527
528 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
6efffa5d 529 $sendTemplateParams['from'] = $fromEmailAddress;
b8df2a80
RK
530 $sendTemplateParams['toEmail'] = $email;
531 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
532 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
dce4c3ea 533
534 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6efffa5d 535 // functions call for adding activity with attachment
c119e8ae 536 $pdfFileName = "{$invoiceId}.pdf";
537 $fileName = self::putFile($html, $pdfFileName);
6efffa5d 538 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
b8df2a80 539 }
dce4c3ea 540
541 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
6efffa5d 542 $invoiceTemplate->clearTemplateVars();
b8df2a80 543 }
dce4c3ea 544
3a1261ac 545 if ($invoiceElements['createPdf']) {
c4d3b8d3 546 if (isset($params['forPage'])) {
d88a0337
PD
547 return $html;
548 }
549 else {
c119e8ae 550 $pdfFileName = "{$invoiceId}.pdf";
551 CRM_Utils_PDF_Utils::html2pdf($messageInvoice, $pdfFileName, FALSE, array(
dce4c3ea 552 'margin_top' => 10,
553 'margin_left' => 65,
21dfd5f5 554 'metric' => 'px',
dce4c3ea 555 ));
d88a0337 556 // functions call for adding activity with attachment
c119e8ae 557 $fileName = self::putFile($html, $pdfFileName);
413796ce 558 self::addActivities($subject, $contactIds, $fileName, $params);
6efffa5d 559
d88a0337
PD
560 CRM_Utils_System::civiExit();
561 }
b8df2a80
RK
562 }
563 else {
3a1261ac
RK
564 if ($invoiceElements['suppressedEmails']) {
565 $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
566 $msgTitle = ts('Email Error');
567 $msgType = 'error';
568 }
569 else {
570 $status = ts('Your mail has been sent.');
571 $msgTitle = ts('Sent');
572 $msgType = 'success';
573 }
574 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
575 }
576 }
6efffa5d 577
dce4c3ea 578 /**
fe482240 579 * Add activity for Email Invoice and the PDF Invoice.
6efffa5d 580 *
014c4014
TO
581 * @param string $subject
582 * Activity subject.
583 * @param array $contactIds
584 * Contact Id.
585 * @param string $fileName
586 * Gives the location with name of the file.
587 * @param array $params
588 * For invoices.
6efffa5d
PB
589 *
590 */
413796ce 591 static public function addActivities($subject, $contactIds, $fileName, $params) {
dce4c3ea 592 $session = CRM_Core_Session::singleton();
593 $userID = $session->get('userID');
6efffa5d
PB
594 $config = CRM_Core_Config::singleton();
595 $config->doNotAttachPDFReceipt = 1;
413796ce 596
597 if (!empty($params['output']) && $params['output'] == 'pdf_invoice') {
6efffa5d 598 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
413796ce 599 'Downloaded Invoice',
6efffa5d
PB
600 'name'
601 );
dce4c3ea 602 }
92e4c2a5 603 else {
6efffa5d 604 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
413796ce 605 'Emailed Invoice',
6efffa5d
PB
606 'name'
607 );
608 }
413796ce 609
6efffa5d
PB
610 $activityParams = array(
611 'subject' => $subject,
612 'source_contact_id' => $userID,
613 'target_contact_id' => $contactIds,
614 'activity_type_id' => $activityTypeID,
615 'activity_date_time' => date('YmdHis'),
dce4c3ea 616 'attachFile_1' => array(
617 'uri' => $fileName,
618 'type' => 'application/pdf',
619 'location' => $fileName,
620 'upload_date' => date('YmdHis'),
621 ),
6efffa5d 622 );
dce4c3ea 623 CRM_Activity_BAO_Activity::create($activityParams);
6efffa5d 624 }
dce4c3ea 625
626 /**
fe482240 627 * Create the Invoice file in upload folder for attachment.
dce4c3ea 628 *
76e7a76c 629 * @param string $html
014c4014 630 * Content for pdf in html format.
6efffa5d 631 *
03110609 632 * @return string
76e7a76c 633 * Name of file which is in pdf format
6efffa5d 634 */
c119e8ae 635 static public function putFile($html, $name = 'Invoice.pdf') {
33313a73 636 require_once "vendor/dompdf/dompdf/dompdf_config.inc.php";
6efffa5d
PB
637 $doc = new DOMPDF();
638 $doc->load_html($html);
639 $doc->render();
640 $html = $doc->output();
641 $config = CRM_Core_Config::singleton();
c119e8ae 642 $fileName = $config->uploadDir . $name;
dce4c3ea 643 file_put_contents($fileName, $html);
6efffa5d
PB
644 return $fileName;
645 }
b5c3483d 646
647 /**
648 * Callback to perform action on Print Invoice button.
649 */
00be9182 650 public static function getPrintPDF() {
b5c3483d 651 $contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
652 $contributionIDs = array($contributionId);
653 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
654 $params = array('output' => 'pdf_invoice');
655 CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId, CRM_Core_DAO::$_nullObject);
656 }
96025800 657
b8df2a80 658}