CRM-16119: Fix Contact custom data multiple save/more buttons translation.
[civicrm-core.git] / CRM / Contribute / Form / Task / Invoice.php
CommitLineData
b8df2a80
RK
1<?php
2/*
3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
b8df2a80
RK
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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
31 * @copyright CiviCRM LLC (c) 2004-2014
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
PB
466 $session = CRM_Core_Session::singleton();
467 $contactID = $session->get('userID');
468 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
469 $emails = array();
470 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
dce4c3ea 471 $contactID, 'display_name'
472 );
6f39f13a
PB
473
474 foreach ($contactEmails as $emailId => $item) {
475 $email = $item['email'];
476 if ($email) {
477 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
478 }
479 }
480 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
dce4c3ea 481
6efffa5d
PB
482 // from email address
483 if (isset($params['from_email_address'])) {
6f39f13a 484 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
6efffa5d 485 }
b8df2a80 486 // condition to check for download PDF Invoice or email Invoice
3a1261ac 487 if ($invoiceElements['createPdf']) {
b8df2a80 488 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
c4d3b8d3 489 if (isset($params['forPage'])) {
d88a0337
PD
490 return $html;
491 }
b8df2a80 492 else {
d88a0337
PD
493 $mail = array(
494 'subject' => $subject,
dce4c3ea 495 'body' => $message,
d88a0337 496 'html' => $html,
dce4c3ea 497 );
d88a0337
PD
498 if ($mail['html']) {
499 $messageInvoice[] = $mail['html'];
dce4c3ea 500 }
d88a0337
PD
501 else {
502 $messageInvoice[] = nl2br($mail['body']);
503 }
b8df2a80
RK
504 }
505 }
506 elseif ($contribution->_component == 'contribute') {
507 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
dce4c3ea 508
509 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
6efffa5d 510 $sendTemplateParams['from'] = $fromEmailAddress;
b8df2a80
RK
511 $sendTemplateParams['toEmail'] = $email;
512 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
513 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
dce4c3ea 514
515 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6efffa5d
PB
516 // functions call for adding activity with attachment
517 $fileName = self::putFile($html);
518 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
b8df2a80
RK
519 }
520 elseif ($contribution->_component == 'event') {
521 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
dce4c3ea 522
523 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
6efffa5d 524 $sendTemplateParams['from'] = $fromEmailAddress;
b8df2a80
RK
525 $sendTemplateParams['toEmail'] = $email;
526 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
527 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
dce4c3ea 528
529 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
6efffa5d
PB
530 // functions call for adding activity with attachment
531 $fileName = self::putFile($html);
532 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
b8df2a80 533 }
dce4c3ea 534
535 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
933c5f44 536 if ($contribution->contribution_status_id == $refundedStatusId) {
dce4c3ea 537 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
933c5f44 538 }
6efffa5d 539 $invoiceTemplate->clearTemplateVars();
b8df2a80 540 }
dce4c3ea 541
3a1261ac 542 if ($invoiceElements['createPdf']) {
c4d3b8d3 543 if (isset($params['forPage'])) {
d88a0337
PD
544 return $html;
545 }
546 else {
dce4c3ea 547 CRM_Utils_PDF_Utils::html2pdf($messageInvoice, 'Invoice.pdf', FALSE, array(
548 'margin_top' => 10,
549 'margin_left' => 65,
21dfd5f5 550 'metric' => 'px',
dce4c3ea 551 ));
d88a0337
PD
552 // functions call for adding activity with attachment
553 $fileName = self::putFile($html);
413796ce 554 self::addActivities($subject, $contactIds, $fileName, $params);
6efffa5d 555
d88a0337
PD
556 CRM_Utils_System::civiExit();
557 }
b8df2a80
RK
558 }
559 else {
3a1261ac
RK
560 if ($invoiceElements['suppressedEmails']) {
561 $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
562 $msgTitle = ts('Email Error');
563 $msgType = 'error';
564 }
565 else {
566 $status = ts('Your mail has been sent.');
567 $msgTitle = ts('Sent');
568 $msgType = 'success';
569 }
570 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
571 }
572 }
6efffa5d 573
dce4c3ea 574 /**
fe482240 575 * Add activity for Email Invoice and the PDF Invoice.
6efffa5d 576 *
014c4014
TO
577 * @param string $subject
578 * Activity subject.
579 * @param array $contactIds
580 * Contact Id.
581 * @param string $fileName
582 * Gives the location with name of the file.
583 * @param array $params
584 * For invoices.
6efffa5d
PB
585 *
586 */
413796ce 587 static public function addActivities($subject, $contactIds, $fileName, $params) {
dce4c3ea 588 $session = CRM_Core_Session::singleton();
589 $userID = $session->get('userID');
6efffa5d
PB
590 $config = CRM_Core_Config::singleton();
591 $config->doNotAttachPDFReceipt = 1;
413796ce 592
593 if (!empty($params['output']) && $params['output'] == 'pdf_invoice') {
6efffa5d 594 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
413796ce 595 'Downloaded Invoice',
6efffa5d
PB
596 'name'
597 );
dce4c3ea 598 }
92e4c2a5 599 else {
6efffa5d 600 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
413796ce 601 'Emailed Invoice',
6efffa5d
PB
602 'name'
603 );
604 }
413796ce 605
6efffa5d
PB
606 $activityParams = array(
607 'subject' => $subject,
608 'source_contact_id' => $userID,
609 'target_contact_id' => $contactIds,
610 'activity_type_id' => $activityTypeID,
611 'activity_date_time' => date('YmdHis'),
dce4c3ea 612 'attachFile_1' => array(
613 'uri' => $fileName,
614 'type' => 'application/pdf',
615 'location' => $fileName,
616 'upload_date' => date('YmdHis'),
617 ),
6efffa5d 618 );
dce4c3ea 619 CRM_Activity_BAO_Activity::create($activityParams);
6efffa5d 620 }
dce4c3ea 621
622 /**
fe482240 623 * Create the Invoice file in upload folder for attachment.
dce4c3ea 624 *
76e7a76c 625 * @param string $html
014c4014 626 * Content for pdf in html format.
6efffa5d 627 *
03110609 628 * @return string
76e7a76c 629 * Name of file which is in pdf format
6efffa5d 630 */
dce4c3ea 631 static public function putFile($html) {
874c9be7 632 require_once "packages/dompdf/dompdf_config.inc.php";
6efffa5d
PB
633 spl_autoload_register('DOMPDF_autoload');
634 $doc = new DOMPDF();
635 $doc->load_html($html);
636 $doc->render();
637 $html = $doc->output();
638 $config = CRM_Core_Config::singleton();
dce4c3ea 639 $fileName = $config->uploadDir . 'Invoice.pdf';
640 file_put_contents($fileName, $html);
6efffa5d
PB
641 return $fileName;
642 }
b5c3483d 643
644 /**
645 * Callback to perform action on Print Invoice button.
646 */
00be9182 647 public static function getPrintPDF() {
b5c3483d 648 $contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
649 $contributionIDs = array($contributionId);
650 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
651 $params = array('output' => 'pdf_invoice');
652 CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId, CRM_Core_DAO::$_nullObject);
653 }
96025800 654
b8df2a80 655}