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