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