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