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