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