Merge pull request #6571 from totten/master-bad-camel
[civicrm-core.git] / CRM / Contribute / Form / Task / Invoice.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2015
32 */
33
34 /**
35 * This class provides the functionality to email a group of
36 * contacts.
37 */
38 class CRM_Contribute_Form_Task_Invoice extends CRM_Contribute_Form_Task {
39 /**
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
47 /**
48 * Gives all the statues for conribution.
49 */
50 public $_contributionStatusId;
51
52 /**
53 * Gives the HTML template of PDF Invoice.
54 */
55 public $_messageInvoice;
56
57 /**
58 * This variable is used to assign parameters for HTML template of PDF Invoice.
59 */
60 public $_invoiceTemplate;
61
62 /**
63 * Selected output.
64 */
65 public $_selectedOutput;
66
67 /**
68 * Build all the data structures needed to build the form.
69 *
70 * @return void
71 */
72 public function preProcess() {
73 $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
74 if ($id) {
75 $this->_contributionIds = array($id);
76 $this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
77 $this->_single = TRUE;
78 $this->assign('totalSelectedContributions', 1);
79
80 // set the redirection after actions
81 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE);
82 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
83 "action=view&reset=1&id={$id}&cid={$contactId}&context=contribution&selectedChild=contribute"
84 );
85
86 CRM_Core_Session::singleton()->pushUserContext($url);
87 }
88 else {
89 parent::preProcess();
90 }
91
92 // check that all the contribution ids have status Completed, Pending, Refunded.
93 $this->_contributionStatusId = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
94 $status = array('Completed', 'Pending', 'Refunded');
95 $statusId = array();
96 foreach ($this->_contributionStatusId as $key => $value) {
97 if (in_array($value, $status)) {
98 $statusId[] = $key;
99 }
100 }
101 $Id = implode(",", $statusId);
102 $query = "SELECT count(*) FROM civicrm_contribution WHERE contribution_status_id NOT IN ($Id) AND {$this->_componentClause}";
103 $count = CRM_Core_DAO::singleValueQuery($query);
104 if ($count != 0) {
105 CRM_Core_Error::statusBounce(ts('Please select only contributions with Completed, Pending, Refunded status.'));
106 }
107
108 // we have all the contribution ids, so now we get the contact ids
109 parent::setContactIDs();
110 $this->assign('single', $this->_single);
111
112 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
113 $urlParams = 'force=1';
114 if (CRM_Utils_Rule::qfKey($qfKey)) {
115 $urlParams .= "&qfKey=$qfKey";
116 }
117
118 $url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
119 $breadCrumb = array(
120 array(
121 'url' => $url,
122 'title' => ts('Search Results'),
123 ),
124 );
125
126 CRM_Utils_System::appendBreadCrumb($breadCrumb);
127
128 $this->_selectedOutput = CRM_Utils_Request::retrieve('select', 'String', $this);
129 $this->assign('selectedOutput', $this->_selectedOutput);
130
131 if ($this->_selectedOutput == 'email') {
132 CRM_Utils_System::setTitle(ts('Email Invoice'));
133 }
134 else {
135 CRM_Utils_System::setTitle(ts('Print Contribution Invoice'));
136 }
137 }
138
139 /**
140 * Build the form object.
141 *
142 *
143 * @return void
144 */
145 public function buildQuickForm() {
146 $session = CRM_Core_Session::singleton();
147 $this->preventAjaxSubmit();
148 if (CRM_Core_Permission::check('administer CiviCRM')) {
149 $this->assign('isAdmin', 1);
150 }
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',
155 $contactID, 'display_name'
156 );
157 foreach ($contactEmails as $emailId => $item) {
158 $email = $item['email'];
159 if ($email) {
160 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
161 }
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]);
168 }
169 }
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);
175 $this->add('select', 'from_email_address', ts('From Email Address'), array('' => '- select -') + $fromEmail);
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
186 $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(
187 'rows' => 2,
188 'cols' => 40,
189 ));
190
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 );
203 }
204
205 /**
206 * Global validation rules for the form.
207 *
208 * @param array $values
209 *
210 * @return array
211 * list of errors to be posted back to the form
212 */
213 public static function formRule($values) {
214 $errors = array();
215
216 if ($values['output'] == 'email_invoice' && empty($values['from_email_address'])) {
217 $errors['from_email_address'] = ts("From Email Address is required");
218 }
219
220 return $errors;
221 }
222
223 /**
224 * Process the form after the input has been submitted and validated.
225 *
226 *
227 * @return void
228 */
229 public function postProcess() {
230 $params = $this->controller->exportValues($this->_name);
231 $this->printPDF($this->_contributionIds, $params, $this->_contactIds, $this);
232 }
233
234 /**
235 * Process the PDf and email with activity and attachment.
236 * on click of Print Invoices
237 *
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.
246 */
247 public static function printPDF($contribIDs, &$params, $contactIds, &$form) {
248 // get all the details needed to generate a invoice
249 $messageInvoice = array();
250 $invoiceTemplate = CRM_Core_Smarty::singleton();
251 $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
252
253 // gives the status id when contribution status is 'Refunded'
254 $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
255 $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
256
257 // getting data from admin page
258 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
259
260 foreach ($invoiceElements['details'] as $contribID => $detail) {
261 $input = $ids = $objects = array();
262 if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
263 continue;
264 }
265
266 $input['component'] = $detail['component'];
267
268 $ids['contact'] = $detail['contact'];
269 $ids['contribution'] = $contribID;
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);
275
276 if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
277 CRM_Core_Error::fatal();
278 }
279
280 $contribution = &$objects['contribution'];
281
282 $input['amount'] = $contribution->total_amount;
283 $input['invoice_id'] = $contribution->invoice_id;
284 $input['receive_date'] = $contribution->receive_date;
285 $input['contribution_status_id'] = $contribution->contribution_status_id;
286 $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
287
288 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
289
290 $addressParams = array('contact_id' => $contribution->contact_id);
291 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
292
293 // to get billing address if present
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 }
304
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 }
311
312 if ($contribution->contribution_status_id == $refundedStatusId) {
313 $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id;
314 }
315 $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
316
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");
320 $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
321
322 if ($input['component'] == 'contribute') {
323 $eid = $contribID;
324 $etable = 'contribution';
325 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE);
326 }
327 else {
328 $eid = $contribution->_relatedObjects['participant']->id;
329 $etable = 'participant';
330 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, FALSE, '', TRUE);
331 }
332
333 //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
334 $amountDue = ($input['amount'] - $input['amount']);
335
336 // retreiving the subtotal and sum of same tax_rate
337 $dataArray = array();
338 $subTotal = 0;
339 foreach ($lineItem as $entity_id => $taxRate) {
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);
342 }
343 else {
344 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
345 }
346 $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
347 }
348
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(
356 'title',
357 'confirm_from_name',
358 'confirm_from_email',
359 'cc_confirm',
360 'bcc_confirm',
361 );
362 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
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]);
368
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(
375 'title',
376 'receipt_from_name',
377 'receipt_from_email',
378 'cc_receipt',
379 'bcc_receipt',
380 );
381 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
382
383 $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
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));
390 }
391 $source = $contribution->source;
392
393 $config = CRM_Core_Config::singleton();
394 if (!isset($params['forPage'])) {
395 $config->doNotAttachPDFReceipt = 1;
396 }
397
398 // get organization address
399 $domain = CRM_Core_BAO_Domain::getDomain();
400 $locParams = array('contact_id' => $domain->contact_id);
401 $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
402 if (isset($locationDefaults['address'][1]['state_province_id'])) {
403 $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
404 }
405 else {
406 $stateProvinceAbbreviationDomain = '';
407 }
408 if (isset($locationDefaults['address'][1]['country_id'])) {
409 $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
410 }
411 else {
412 $countryDomain = '';
413 }
414
415 // parameters to be assign for template
416 $tplParams = array(
417 'title' => $title,
418 'component' => $input['component'],
419 'id' => $contribution->id,
420 'source' => $source,
421 'invoice_id' => $invoiceId,
422 'resourceBase' => $config->userFrameworkResourceURL,
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 );
454
455 if (isset($creditNoteId)) {
456 $tplParams['creditnote_id'] = $creditNoteId;
457 }
458
459 $pdfFileName = "{$invoiceId}.pdf";
460 $sendTemplateParams = array(
461 'groupName' => 'msg_tpl_workflow_contribution',
462 'valueName' => 'contribution_invoice_receipt',
463 'contactId' => $contribution->contact_id,
464 'tplParams' => $tplParams,
465 'PDFFilename' => $pdfFileName,
466 );
467 $session = CRM_Core_Session::singleton();
468 $contactID = $session->get('userID');
469 //CRM-16319 - we dont store in userID in case the user is doing multiple
470 //transactions etc
471 if (empty($contactID)) {
472 $contactID = $session->get('transaction.userID');
473 }
474 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
475 $emails = array();
476 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
477 $contactID, 'display_name'
478 );
479
480 foreach ($contactEmails as $emailId => $item) {
481 $email = $item['email'];
482 if ($email) {
483 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
484 }
485 }
486 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
487
488 // from email address
489 if (isset($params['from_email_address'])) {
490 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
491 }
492 // condition to check for download PDF Invoice or email Invoice
493 if ($invoiceElements['createPdf']) {
494 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
495 if (isset($params['forPage'])) {
496 return $html;
497 }
498 else {
499 $mail = array(
500 'subject' => $subject,
501 'body' => $message,
502 'html' => $html,
503 );
504 if ($mail['html']) {
505 $messageInvoice[] = $mail['html'];
506 }
507 else {
508 $messageInvoice[] = nl2br($mail['body']);
509 }
510 }
511 }
512 elseif ($contribution->_component == 'contribute') {
513 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
514
515 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
516 $sendTemplateParams['from'] = $fromEmailAddress;
517 $sendTemplateParams['toEmail'] = $email;
518 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
519 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
520
521 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
522 // functions call for adding activity with attachment
523 $pdfFileName = "{$invoiceId}.pdf";
524 $fileName = self::putFile($html, $pdfFileName);
525 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
526 }
527 elseif ($contribution->_component == 'event') {
528 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
529
530 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
531 $sendTemplateParams['from'] = $fromEmailAddress;
532 $sendTemplateParams['toEmail'] = $email;
533 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
534 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
535
536 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
537 // functions call for adding activity with attachment
538 $pdfFileName = "{$invoiceId}.pdf";
539 $fileName = self::putFile($html, $pdfFileName);
540 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
541 }
542
543 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
544 if ($contribution->contribution_status_id == $refundedStatusId) {
545 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
546 }
547 $invoiceTemplate->clearTemplateVars();
548 }
549
550 if ($invoiceElements['createPdf']) {
551 if (isset($params['forPage'])) {
552 return $html;
553 }
554 else {
555 $pdfFileName = "{$invoiceId}.pdf";
556 CRM_Utils_PDF_Utils::html2pdf($messageInvoice, $pdfFileName, FALSE, array(
557 'margin_top' => 10,
558 'margin_left' => 65,
559 'metric' => 'px',
560 ));
561 // functions call for adding activity with attachment
562 $fileName = self::putFile($html, $pdfFileName);
563 self::addActivities($subject, $contactIds, $fileName, $params);
564
565 CRM_Utils_System::civiExit();
566 }
567 }
568 else {
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']));
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 }
582
583 /**
584 * Add activity for Email Invoice and the PDF Invoice.
585 *
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.
594 *
595 */
596 static public function addActivities($subject, $contactIds, $fileName, $params) {
597 $session = CRM_Core_Session::singleton();
598 $userID = $session->get('userID');
599 $config = CRM_Core_Config::singleton();
600 $config->doNotAttachPDFReceipt = 1;
601
602 if (!empty($params['output']) && $params['output'] == 'pdf_invoice') {
603 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
604 'Downloaded Invoice',
605 'name'
606 );
607 }
608 else {
609 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
610 'Emailed Invoice',
611 'name'
612 );
613 }
614
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'),
621 'attachFile_1' => array(
622 'uri' => $fileName,
623 'type' => 'application/pdf',
624 'location' => $fileName,
625 'upload_date' => date('YmdHis'),
626 ),
627 );
628 CRM_Activity_BAO_Activity::create($activityParams);
629 }
630
631 /**
632 * Create the Invoice file in upload folder for attachment.
633 *
634 * @param string $html
635 * Content for pdf in html format.
636 *
637 * @return string
638 * Name of file which is in pdf format
639 */
640 static public function putFile($html, $name = 'Invoice.pdf') {
641 require_once "vendor/dompdf/dompdf/dompdf_config.inc.php";
642 $doc = new DOMPDF();
643 $doc->load_html($html);
644 $doc->render();
645 $html = $doc->output();
646 $config = CRM_Core_Config::singleton();
647 $fileName = $config->uploadDir . $name;
648 file_put_contents($fileName, $html);
649 return $fileName;
650 }
651
652 /**
653 * Callback to perform action on Print Invoice button.
654 */
655 public static function getPrintPDF() {
656 $contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
657 $contributionIDs = array($contributionId);
658 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
659 $params = array('output' => 'pdf_invoice');
660 CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId, CRM_Core_DAO::$_nullObject);
661 }
662
663 }