Merge pull request #6431 from JMAConsulting/CRM-16526
[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();
307 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
308 }
309 else {
310 $creditNoteId = $contribution->creditnote_id;
311 }
312 }
313 $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
314
315 //to obtain due date for PDF invoice
316 $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
317 $invoiceDate = date("F j, Y");
318 $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
319
320 if ($input['component'] == 'contribute') {
321 $eid = $contribID;
322 $etable = 'contribution';
323 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE);
324 }
325 else {
326 $eid = $contribution->_relatedObjects['participant']->id;
327 $etable = 'participant';
328 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, FALSE, '', TRUE);
329 }
330
331 //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
332 $amountDue = ($input['amount'] - $input['amount']);
333
334 // retreiving the subtotal and sum of same tax_rate
335 $dataArray = array();
336 $subTotal = 0;
337 foreach ($lineItem as $entity_id => $taxRate) {
338 if (isset($dataArray[(string) $taxRate['tax_rate']])) {
339 $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
340 }
341 else {
342 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
343 }
344 $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
345 }
346
347 // to email the invoice
348 $mailDetails = array();
349 $values = array();
350 if ($contribution->_component == 'event') {
351 $daoName = 'CRM_Event_DAO_Event';
352 $pageId = $contribution->_relatedObjects['event']->id;
353 $mailElements = array(
354 'title',
355 'confirm_from_name',
356 'confirm_from_email',
357 'cc_confirm',
358 'bcc_confirm',
359 );
360 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
361 $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
362 $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
363 $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
364 $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
365 $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
366
367 $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
368 }
369 elseif ($contribution->_component == 'contribute') {
370 $daoName = 'CRM_Contribute_DAO_ContributionPage';
371 $pageId = $contribution->contribution_page_id;
372 $mailElements = array(
373 'title',
374 'receipt_from_name',
375 'receipt_from_email',
376 'cc_receipt',
377 'bcc_receipt',
378 );
379 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
380
381 $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
382 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
383 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
384 $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
385 $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
386
387 $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
388 }
389 $source = $contribution->source;
390
391 $config = CRM_Core_Config::singleton();
392 if (!isset($params['forPage'])) {
393 $config->doNotAttachPDFReceipt = 1;
394 }
395
396 // get organization address
397 $domain = CRM_Core_BAO_Domain::getDomain();
398 $locParams = array('contact_id' => $domain->contact_id);
399 $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
400 if (isset($locationDefaults['address'][1]['state_province_id'])) {
401 $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
402 }
403 else {
404 $stateProvinceAbbreviationDomain = '';
405 }
406 if (isset($locationDefaults['address'][1]['country_id'])) {
407 $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
408 }
409 else {
410 $countryDomain = '';
411 }
412
413 // parameters to be assign for template
414 $tplParams = array(
415 'title' => $title,
416 'component' => $input['component'],
417 'id' => $contribution->id,
418 'source' => $source,
419 'invoice_id' => $invoiceId,
420 'resourceBase' => $config->userFrameworkResourceURL,
421 'defaultCurrency' => $config->defaultCurrency,
422 'amount' => $contribution->total_amount,
423 'amountDue' => $amountDue,
424 'invoice_date' => $invoiceDate,
425 'dueDate' => $dueDate,
426 'notes' => CRM_Utils_Array::value('notes', $prefixValue),
427 'display_name' => $contribution->_relatedObjects['contact']->display_name,
428 'lineItem' => $lineItem,
429 'dataArray' => $dataArray,
430 'refundedStatusId' => $refundedStatusId,
431 'cancelledStatusId' => $cancelledStatusId,
432 'contribution_status_id' => $contribution->contribution_status_id,
433 'subTotal' => $subTotal,
434 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
435 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
436 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
437 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
438 'stateProvinceAbbreviation' => $stateProvinceAbbreviation,
439 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
440 'is_pay_later' => $contribution->is_pay_later,
441 'organization_name' => $contribution->_relatedObjects['contact']->organization_name,
442 'domain_organization' => $domain->name,
443 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])),
444 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])),
445 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])),
446 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])),
447 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])),
448 'domain_state' => $stateProvinceAbbreviationDomain,
449 'domain_country' => $countryDomain,
450 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])),
451 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])),
452 );
453
454 if (isset($creditNoteId)) {
455 $tplParams['creditnote_id'] = $creditNoteId;
456 }
457
458 $pdfFileName = "{$invoiceId}.pdf";
459 $sendTemplateParams = array(
460 'groupName' => 'msg_tpl_workflow_contribution',
461 'valueName' => 'contribution_invoice_receipt',
462 'contactId' => $contribution->contact_id,
463 'tplParams' => $tplParams,
464 'PDFFilename' => $pdfFileName,
465 );
466 $session = CRM_Core_Session::singleton();
467 $contactID = $session->get('userID');
468 //CRM-16319 - we dont store in userID in case the user is doing multiple
469 //transactions etc
470 if (empty($contactID)) {
471 $contactID = $session->get('transaction.userID');
472 }
473 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
474 $emails = array();
475 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
476 $contactID, 'display_name'
477 );
478
479 foreach ($contactEmails as $emailId => $item) {
480 $email = $item['email'];
481 if ($email) {
482 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
483 }
484 }
485 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
486
487 // from email address
488 if (isset($params['from_email_address'])) {
489 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
490 }
491 // condition to check for download PDF Invoice or email Invoice
492 if ($invoiceElements['createPdf']) {
493 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
494 if (isset($params['forPage'])) {
495 return $html;
496 }
497 else {
498 $mail = array(
499 'subject' => $subject,
500 'body' => $message,
501 'html' => $html,
502 );
503 if ($mail['html']) {
504 $messageInvoice[] = $mail['html'];
505 }
506 else {
507 $messageInvoice[] = nl2br($mail['body']);
508 }
509 }
510 }
511 elseif ($contribution->_component == 'contribute') {
512 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
513
514 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
515 $sendTemplateParams['from'] = $fromEmailAddress;
516 $sendTemplateParams['toEmail'] = $email;
517 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
518 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
519
520 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
521 // functions call for adding activity with attachment
522 $pdfFileName = "{$invoiceId}.pdf";
523 $fileName = self::putFile($html, $pdfFileName);
524 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
525 }
526 elseif ($contribution->_component == 'event') {
527 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
528
529 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
530 $sendTemplateParams['from'] = $fromEmailAddress;
531 $sendTemplateParams['toEmail'] = $email;
532 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
533 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
534
535 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
536 // functions call for adding activity with attachment
537 $pdfFileName = "{$invoiceId}.pdf";
538 $fileName = self::putFile($html, $pdfFileName);
539 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
540 }
541
542 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
543 $invoiceTemplate->clearTemplateVars();
544 }
545
546 if ($invoiceElements['createPdf']) {
547 if (isset($params['forPage'])) {
548 return $html;
549 }
550 else {
551 $pdfFileName = "{$invoiceId}.pdf";
552 CRM_Utils_PDF_Utils::html2pdf($messageInvoice, $pdfFileName, FALSE, array(
553 'margin_top' => 10,
554 'margin_left' => 65,
555 'metric' => 'px',
556 ));
557 // functions call for adding activity with attachment
558 $fileName = self::putFile($html, $pdfFileName);
559 self::addActivities($subject, $contactIds, $fileName, $params);
560
561 CRM_Utils_System::civiExit();
562 }
563 }
564 else {
565 if ($invoiceElements['suppressedEmails']) {
566 $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']));
567 $msgTitle = ts('Email Error');
568 $msgType = 'error';
569 }
570 else {
571 $status = ts('Your mail has been sent.');
572 $msgTitle = ts('Sent');
573 $msgType = 'success';
574 }
575 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
576 }
577 }
578
579 /**
580 * Add activity for Email Invoice and the PDF Invoice.
581 *
582 * @param string $subject
583 * Activity subject.
584 * @param array $contactIds
585 * Contact Id.
586 * @param string $fileName
587 * Gives the location with name of the file.
588 * @param array $params
589 * For invoices.
590 *
591 */
592 static public function addActivities($subject, $contactIds, $fileName, $params) {
593 $session = CRM_Core_Session::singleton();
594 $userID = $session->get('userID');
595 $config = CRM_Core_Config::singleton();
596 $config->doNotAttachPDFReceipt = 1;
597
598 if (!empty($params['output']) && $params['output'] == 'pdf_invoice') {
599 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
600 'Downloaded Invoice',
601 'name'
602 );
603 }
604 else {
605 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
606 'Emailed Invoice',
607 'name'
608 );
609 }
610
611 $activityParams = array(
612 'subject' => $subject,
613 'source_contact_id' => $userID,
614 'target_contact_id' => $contactIds,
615 'activity_type_id' => $activityTypeID,
616 'activity_date_time' => date('YmdHis'),
617 'attachFile_1' => array(
618 'uri' => $fileName,
619 'type' => 'application/pdf',
620 'location' => $fileName,
621 'upload_date' => date('YmdHis'),
622 ),
623 );
624 CRM_Activity_BAO_Activity::create($activityParams);
625 }
626
627 /**
628 * Create the Invoice file in upload folder for attachment.
629 *
630 * @param string $html
631 * Content for pdf in html format.
632 *
633 * @return string
634 * Name of file which is in pdf format
635 */
636 static public function putFile($html, $name = 'Invoice.pdf') {
637 require_once "vendor/dompdf/dompdf/dompdf_config.inc.php";
638 $doc = new DOMPDF();
639 $doc->load_html($html);
640 $doc->render();
641 $html = $doc->output();
642 $config = CRM_Core_Config::singleton();
643 $fileName = $config->uploadDir . $name;
644 file_put_contents($fileName, $html);
645 return $fileName;
646 }
647
648 /**
649 * Callback to perform action on Print Invoice button.
650 */
651 public static function getPrintPDF() {
652 $contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
653 $contributionIDs = array($contributionId);
654 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
655 $params = array('output' => 'pdf_invoice');
656 CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId, CRM_Core_DAO::$_nullObject);
657 }
658
659 }