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