Merge pull request #9536 from twomice/CRM-19447_activity_details_search
[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-2016 |
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 use Dompdf\Dompdf;
29 use Dompdf\Options;
30
31 /**
32 *
33 * @package CRM
34 * @copyright CiviCRM LLC (c) 2004-2016
35 */
36
37 /**
38 * This class provides the functionality to email a group of
39 * contacts.
40 */
41 class CRM_Contribute_Form_Task_Invoice extends CRM_Contribute_Form_Task {
42 /**
43 * Are we operating in "single mode", i.e. updating the task of only
44 * one specific contribution?
45 *
46 * @var boolean
47 */
48 public $_single = FALSE;
49
50 /**
51 * Gives all the statues for conribution.
52 */
53 public $_contributionStatusId;
54
55 /**
56 * Gives the HTML template of PDF Invoice.
57 */
58 public $_messageInvoice;
59
60 /**
61 * This variable is used to assign parameters for HTML template of PDF Invoice.
62 */
63 public $_invoiceTemplate;
64
65 /**
66 * Selected output.
67 */
68 public $_selectedOutput;
69
70 /**
71 * Build all the data structures needed to build the form.
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 public function buildQuickForm() {
144 $session = CRM_Core_Session::singleton();
145 $this->preventAjaxSubmit();
146 if (CRM_Core_Permission::check('administer CiviCRM')) {
147 $this->assign('isAdmin', 1);
148 }
149 $contactID = $session->get('userID');
150 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
151 $emails = array();
152 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
153 $contactID, 'display_name'
154 );
155 foreach ($contactEmails as $emailId => $item) {
156 $email = $item['email'];
157 if ($email) {
158 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
159 }
160 if (isset($emails[$emailId])) {
161 $emails[$emailId] .= $item['locationType'];
162 if ($item['is_primary']) {
163 $emails[$emailId] .= ' ' . ts('(preferred)');
164 }
165 $emails[$emailId] = htmlspecialchars($emails[$emailId]);
166 }
167 }
168 $fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address');
169 foreach ($fromEmailAddress as $key => $email) {
170 $fromEmailAddress[$key] = htmlspecialchars($fromEmailAddress[$key]);
171 }
172 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, $fromEmailAddress);
173 $this->add('select', 'from_email_address', ts('From Email Address'), array('' => '- select -') + $fromEmail);
174 if ($this->_selectedOutput != 'email') {
175 $this->addElement('radio', 'output', NULL, ts('Email Invoice'), 'email_invoice');
176 $this->addElement('radio', 'output', NULL, ts('PDF Invoice'), 'pdf_invoice');
177 $this->addRule('output', ts('Selection required'), 'required');
178 $this->addFormRule(array('CRM_Contribute_Form_Task_Invoice', 'formRule'));
179 }
180 else {
181 $this->addRule('from_email_address', ts('From Email Address is required'), 'required');
182 }
183
184 $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(
185 'rows' => 2,
186 'cols' => 40,
187 ));
188
189 $this->addButtons(array(
190 array(
191 'type' => 'upload',
192 'name' => $this->_selectedOutput == 'email' ? ts('Send Email') : ts('Process Invoice(s)'),
193 'isDefault' => TRUE,
194 ),
195 array(
196 'type' => 'cancel',
197 'name' => ts('Cancel'),
198 ),
199 )
200 );
201 }
202
203 /**
204 * Global validation rules for the form.
205 *
206 * @param array $values
207 *
208 * @return array
209 * list of errors to be posted back to the form
210 */
211 public static function formRule($values) {
212 $errors = array();
213
214 if ($values['output'] == 'email_invoice' && empty($values['from_email_address'])) {
215 $errors['from_email_address'] = ts("From Email Address is required");
216 }
217
218 return $errors;
219 }
220
221 /**
222 * Process the form after the input has been submitted and validated.
223 */
224 public function postProcess() {
225 $params = $this->controller->exportValues($this->_name);
226 self::printPDF($this->_contributionIds, $params, $this->_contactIds);
227 }
228
229 /**
230 * Process the PDf and email with activity and attachment on click of Print Invoices.
231 *
232 * @param array $contribIDs
233 * Contribution Id.
234 * @param array $params
235 * Associated array of submitted values.
236 * @param array $contactIds
237 * Contact Id.
238 */
239 public static function printPDF($contribIDs, &$params, $contactIds) {
240 // get all the details needed to generate a invoice
241 $messageInvoice = array();
242 $invoiceTemplate = CRM_Core_Smarty::singleton();
243 $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
244
245 // gives the status id when contribution status is 'Refunded'
246 $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
247 $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
248 $cancelledStatusId = CRM_Utils_Array::key('Cancelled', $contributionStatusID);
249 $pendingStatusId = CRM_Utils_Array::key('Pending', $contributionStatusID);
250
251 // getting data from admin page
252 $prefixValue = Civi::settings()->get('contribution_invoice_settings');
253
254 foreach ($invoiceElements['details'] as $contribID => $detail) {
255 $input = $ids = $objects = array();
256 if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
257 continue;
258 }
259
260 $input['component'] = $detail['component'];
261
262 $ids['contact'] = $detail['contact'];
263 $ids['contribution'] = $contribID;
264 $ids['contributionRecur'] = NULL;
265 $ids['contributionPage'] = NULL;
266 $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
267 $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
268 $ids['event'] = CRM_Utils_Array::value('event', $detail);
269
270 if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
271 CRM_Core_Error::fatal();
272 }
273
274 $contribution = &$objects['contribution'];
275
276 $input['amount'] = $contribution->total_amount;
277 $input['invoice_id'] = $contribution->invoice_id;
278 $input['receive_date'] = $contribution->receive_date;
279 $input['contribution_status_id'] = $contribution->contribution_status_id;
280 $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
281
282 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
283
284 $addressParams = array('contact_id' => $contribution->contact_id);
285 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
286
287 // to get billing address if present
288 $billingAddress = array();
289 foreach ($addressDetails as $key => $address) {
290 if ((isset($address['is_billing']) && $address['is_billing'] == 1) && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
291 $billingAddress[$address['contact_id']] = $address;
292 break;
293 }
294 elseif (($address['is_billing'] == 0 && $address['is_primary'] == 1) || (isset($address['is_billing']) && $address['is_billing'] == 1) && $address['contact_id'] == $contribution->contact_id) {
295 $billingAddress[$address['contact_id']] = $address;
296 }
297 }
298
299 if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
300 $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
301 }
302 else {
303 $stateProvinceAbbreviation = '';
304 }
305
306 if ($contribution->contribution_status_id == $refundedStatusId || $contribution->contribution_status_id == $cancelledStatusId) {
307 if (is_null($contribution->creditnote_id)) {
308 $creditNoteId = CRM_Contribute_BAO_Contribution::createCreditNoteId();
309 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
310 }
311 else {
312 $creditNoteId = $contribution->creditnote_id;
313 }
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 $lineItem = CRM_Price_BAO_LineItem::getLineItemsByContributionID($contribID);
324 }
325 else {
326 $eid = $contribution->_relatedObjects['participant']->id;
327 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, 'participant', 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 'pendingStatusId' => $pendingStatusId,
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 // Fix Invoice email doesnot send out when completed payment using Paypal
474 if (empty($contactID)) {
475 $contactID = current($contactIds);
476 }
477 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
478 $emails = array();
479 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
480 $contactID, 'display_name'
481 );
482
483 foreach ($contactEmails as $emailId => $item) {
484 $email = $item['email'];
485 if ($email) {
486 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
487 }
488 }
489 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
490
491 // from email address
492 if (isset($params['from_email_address'])) {
493 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
494 }
495 // condition to check for download PDF Invoice or email Invoice
496 if ($invoiceElements['createPdf']) {
497 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
498 if (isset($params['forPage'])) {
499 return $html;
500 }
501 else {
502 $mail = array(
503 'subject' => $subject,
504 'body' => $message,
505 'html' => $html,
506 );
507 if ($mail['html']) {
508 $messageInvoice[] = $mail['html'];
509 }
510 else {
511 $messageInvoice[] = nl2br($mail['body']);
512 }
513 }
514 }
515 elseif ($contribution->_component == 'contribute') {
516 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
517
518 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
519 $sendTemplateParams['from'] = $fromEmailAddress;
520 $sendTemplateParams['toEmail'] = $email;
521 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
522 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
523
524 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
525 // functions call for adding activity with attachment
526 $pdfFileName = "{$invoiceId}.pdf";
527 $fileName = self::putFile($html, $pdfFileName);
528 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
529 }
530 elseif ($contribution->_component == 'event') {
531 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
532
533 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
534 $sendTemplateParams['from'] = $fromEmailAddress;
535 $sendTemplateParams['toEmail'] = $email;
536 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
537 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
538
539 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
540 // functions call for adding activity with attachment
541 $pdfFileName = "{$invoiceId}.pdf";
542 $fileName = self::putFile($html, $pdfFileName);
543 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
544 }
545
546 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
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 * @param string $name
638 *
639 * @return string
640 * Name of file which is in pdf format
641 */
642 static public function putFile($html, $name = 'Invoice.pdf') {
643 $options = new Options();
644 $options->set('isRemoteEnabled', TRUE);
645
646 $doc = new DOMPDF($options);
647 $doc->load_html($html);
648 $doc->render();
649 $html = $doc->output();
650 $config = CRM_Core_Config::singleton();
651 $fileName = $config->uploadDir . $name;
652 file_put_contents($fileName, $html);
653 return $fileName;
654 }
655
656 /**
657 * Callback to perform action on Print Invoice button.
658 */
659 public static function getPrintPDF() {
660 $contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
661 $contributionIDs = array($contributionId);
662 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
663 $params = array('output' => 'pdf_invoice');
664 CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId);
665 }
666
667 }