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