Merge pull request #4606 from johanv/CRM-15636-price_set_event_and_contribution
[civicrm-core.git] / CRM / Contribute / Form / Task / Invoice.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
32 *
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 */
52 public $_contributionStatusId;
53
54 /**
55 * Gives the HTML template of PDF Invoice
56 *
57 */
58 public $_messageInvoice;
59
60 /**
61 * This variable is used to assign parameters for HTML template of PDF Invoice
62 *
63 */
64 public $_invoiceTemplate;
65
66 /**
67 * Selected output
68 */
69 public $_selectedOutput;
70
71 /**
72 * Build all the data structures needed to build the form
73 *
74 * @return void
75 */
76 public function preProcess() {
77 $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
78 if ($id) {
79 $this->_contributionIds = array($id);
80 $this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
81 $this->_single = TRUE;
82 $this->assign('totalSelectedContributions', 1);
83
84 // set the redirection after actions
85 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE);
86 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
87 "action=view&reset=1&id={$id}&cid={$contactId}&context=contribution&selectedChild=contribute"
88 );
89
90 CRM_Core_Session::singleton()->pushUserContext($url);
91 }
92 else {
93 parent::preProcess();
94 }
95
96 // check that all the contribution ids have status Completed, Pending, Refunded.
97 $this->_contributionStatusId = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
98 $status = array('Completed', 'Pending', 'Refunded');
99 $statusId = array();
100 foreach ($this->_contributionStatusId as $key => $value) {
101 if (in_array($value, $status)) {
102 $statusId[] = $key;
103 }
104 }
105 $Id = implode(",", $statusId);
106 $query = "SELECT count(*) FROM civicrm_contribution WHERE contribution_status_id NOT IN ($Id) AND {$this->_componentClause}";
107 $count = CRM_Core_DAO::singleValueQuery($query);
108 if ($count != 0) {
109 CRM_Core_Error::statusBounce(ts('Please select only contributions with Completed, Pending, Refunded status.'));
110 }
111
112 // we have all the contribution ids, so now we get the contact ids
113 parent::setContactIDs();
114 $this->assign('single', $this->_single);
115
116 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
117 $urlParams = 'force=1';
118 if (CRM_Utils_Rule::qfKey($qfKey)) {
119 $urlParams .= "&qfKey=$qfKey";
120 }
121
122 $url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
123 $breadCrumb = array(
124 array(
125 'url' => $url,
126 'title' => ts('Search Results'),
127 )
128 );
129
130 CRM_Utils_System::appendBreadCrumb($breadCrumb);
131
132 $this->_selectedOutput = CRM_Utils_Request::retrieve('select', 'String', $this);
133 $this->assign('selectedOutput', $this->_selectedOutput);
134
135 if ($this->_selectedOutput == 'email') {
136 CRM_Utils_System::setTitle(ts('Email Invoice'));
137 }
138 else {
139 CRM_Utils_System::setTitle(ts('Print Contribution Invoice'));
140 }
141 }
142
143 /**
144 * Build the form object
145 *
146 *
147 * @return void
148 */
149 public function buildQuickForm() {
150 $session = CRM_Core_Session::singleton();
151 if (CRM_Core_Permission::check('administer CiviCRM')) {
152 $this->assign('isAdmin', 1);
153 }
154 $contactID = $session->get('userID');
155 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
156 $emails = array();
157 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
158 $contactID, 'display_name'
159 );
160 foreach ($contactEmails as $emailId => $item) {
161 $email = $item['email'];
162 if ($email) {
163 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
164 }
165 if (isset($emails[$emailId])) {
166 $emails[$emailId] .= $item['locationType'];
167 if ($item['is_primary']) {
168 $emails[$emailId] .= ' ' . ts('(preferred)');
169 }
170 $emails[$emailId] = htmlspecialchars($emails[$emailId]);
171 }
172 }
173 $fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address');
174 foreach ($fromEmailAddress as $key => $email) {
175 $fromEmailAddress[$key] = htmlspecialchars($fromEmailAddress[$key]);
176 }
177 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, $fromEmailAddress);
178 $this->add('select', 'from_email_address', ts('From Email Address'), array('' => '- select -') + $fromEmail);
179 if ($this->_selectedOutput != 'email') {
180 $this->addElement('radio', 'output', NULL, ts('Email Invoice'), 'email_invoice');
181 $this->addElement('radio', 'output', NULL, ts('PDF Invoice'), 'pdf_invoice');
182 $this->addRule('output', ts('Selection required'), 'required');
183 $this->addFormRule(array('CRM_Contribute_Form_Task_Invoice', 'formRule'));
184 }
185 else {
186 $this->addRule('from_email_address', ts('From Email Address is required'), 'required');
187 }
188
189 $this->addWysiwyg('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(
190 'rows' => 2,
191 'cols' => 40
192 ));
193
194 $this->addButtons(array(
195 array(
196 'type' => 'upload',
197 'name' => $this->_selectedOutput == 'email' ? ts('Send Email') : ts('Process Invoice(s)'),
198 'isDefault' => TRUE,
199 ),
200 array(
201 'type' => 'cancel',
202 'name' => ts('Cancel'),
203 ),
204 )
205 );
206 }
207
208 /**
209 * Global validation rules for the form
210 *
211 * @param array $values
212 *
213 * @return array list of errors to be posted back to the form
214 * @static
215 */
216 public static function formRule($values) {
217 $errors = array();
218
219 if ($values['output'] == 'email_invoice' && empty($values['from_email_address'])) {
220 $errors['from_email_address'] = ts("From Email Address is required");
221 }
222
223 return $errors;
224 }
225
226 /**
227 * Process the form after the input has been submitted and validated
228 *
229 *
230 * @return void
231 */
232 public function postProcess() {
233 $params = $this->controller->exportValues($this->_name);
234 $this->printPDF($this->_contributionIds, $params, $this->_contactIds, $this);
235 }
236
237 /**
238 *
239 * process the PDf and email with activity and attachment
240 * on click of Print Invoices
241 *
242 * @param array $contribIDs Contribution Id
243 * @param array $params associated array of submitted values
244 * @param array $contactIds Contact Id
245 * @param CRM_Core_Form $form form object
246 * @static
247 *
248 */
249 public static function printPDF($contribIDs, &$params, $contactIds, &$form) {
250 // get all the details needed to generate a invoice
251 $messageInvoice = array();
252 $invoiceTemplate = CRM_Core_Smarty::singleton();
253 $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
254
255 // gives the status id when contribution status is 'Refunded'
256 $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
257 $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
258
259 // getting data from admin page
260 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
261
262 foreach ($invoiceElements['details'] as $contribID => $detail) {
263 $input = $ids = $objects = array();
264 if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
265 continue;
266 }
267
268 $input['component'] = $detail['component'];
269
270 $ids['contact'] = $detail['contact'];
271 $ids['contribution'] = $contribID;
272 $ids['contributionRecur'] = NULL;
273 $ids['contributionPage'] = NULL;
274 $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
275 $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
276 $ids['event'] = CRM_Utils_Array::value('event', $detail);
277
278 if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
279 CRM_Core_Error::fatal();
280 }
281
282 $contribution = & $objects['contribution'];
283
284 $input['amount'] = $contribution->total_amount;
285 $input['invoice_id'] = $contribution->invoice_id;
286 $input['receive_date'] = $contribution->receive_date;
287 $input['contribution_status_id'] = $contribution->contribution_status_id;
288 $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
289
290 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
291
292 $addressParams = array('contact_id' => $contribution->contact_id);
293 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
294
295 // to get billing address if present
296 $billingAddress = array();
297 foreach ($addressDetails as $key => $address) {
298 if ((isset($address['is_billing']) && $address['is_billing'] == 1) && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
299 $billingAddress[$address['contact_id']] = $address;
300 break;
301 }
302 elseif (($address['is_billing'] == 0 && $address['is_primary'] == 1) || (isset($address['is_billing']) && $address['is_billing'] == 1) && $address['contact_id'] == $contribution->contact_id) {
303 $billingAddress[$address['contact_id']] = $address;
304 }
305 }
306
307 if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
308 $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
309 }
310 else {
311 $stateProvinceAbbreviation = '';
312 }
313
314 if ($contribution->contribution_status_id == $refundedStatusId) {
315 $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id;
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);
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->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 '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 $sendTemplateParams = array(
462 'groupName' => 'msg_tpl_workflow_contribution',
463 'valueName' => 'contribution_invoice_receipt',
464 'contactId' => $contribution->contact_id,
465 'tplParams' => $tplParams,
466 'PDFFilename' => 'Invoice.pdf',
467 );
468 $session = CRM_Core_Session::singleton();
469 $contactID = $session->get('userID');
470 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
471 $emails = array();
472 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
473 $contactID, 'display_name'
474 );
475
476 foreach ($contactEmails as $emailId => $item) {
477 $email = $item['email'];
478 if ($email) {
479 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
480 }
481 }
482 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
483
484 // from email address
485 if (isset($params['from_email_address'])) {
486 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
487 }
488 // condition to check for download PDF Invoice or email Invoice
489 if ($invoiceElements['createPdf']) {
490 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
491 if (isset($params['forPage'])) {
492 return $html;
493 }
494 else {
495 $mail = array(
496 'subject' => $subject,
497 'body' => $message,
498 'html' => $html,
499 );
500 if ($mail['html']) {
501 $messageInvoice[] = $mail['html'];
502 }
503 else {
504 $messageInvoice[] = nl2br($mail['body']);
505 }
506 }
507 }
508 elseif ($contribution->_component == 'contribute') {
509 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
510
511 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
512 $sendTemplateParams['from'] = $fromEmailAddress;
513 $sendTemplateParams['toEmail'] = $email;
514 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
515 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
516
517 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
518 // functions call for adding activity with attachment
519 $fileName = self::putFile($html);
520 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
521 }
522 elseif ($contribution->_component == 'event') {
523 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
524
525 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
526 $sendTemplateParams['from'] = $fromEmailAddress;
527 $sendTemplateParams['toEmail'] = $email;
528 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
529 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
530
531 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
532 // functions call for adding activity with attachment
533 $fileName = self::putFile($html);
534 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
535 }
536
537 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
538 if ($contribution->contribution_status_id == $refundedStatusId) {
539 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
540 }
541 $invoiceTemplate->clearTemplateVars();
542 }
543
544 if ($invoiceElements['createPdf']) {
545 if (isset($params['forPage'])) {
546 return $html;
547 }
548 else {
549 CRM_Utils_PDF_Utils::html2pdf($messageInvoice, 'Invoice.pdf', FALSE, array(
550 'margin_top' => 10,
551 'margin_left' => 65,
552 'metric' => 'px'
553 ));
554 // functions call for adding activity with attachment
555 $fileName = self::putFile($html);
556 self::addActivities($subject, $contactIds, $fileName, $params);
557
558 CRM_Utils_System::civiExit();
559 }
560 }
561 else {
562 if ($invoiceElements['suppressedEmails']) {
563 $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']));
564 $msgTitle = ts('Email Error');
565 $msgType = 'error';
566 }
567 else {
568 $status = ts('Your mail has been sent.');
569 $msgTitle = ts('Sent');
570 $msgType = 'success';
571 }
572 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
573 }
574 }
575
576 /**
577 *
578 * This function is use for adding activity for
579 * Email Invoice and the PDF Invoice
580 *
581 * @param string $subject Activity subject
582 * @param array $contactIds Contact Id
583 * @param string $fileName gives the location with name of the file
584 * @param array $params for invoices
585 *
586 * @static
587 */
588 static public function addActivities($subject, $contactIds, $fileName, $params) {
589 $session = CRM_Core_Session::singleton();
590 $userID = $session->get('userID');
591 $config = CRM_Core_Config::singleton();
592 $config->doNotAttachPDFReceipt = 1;
593
594 if (!empty($params['output']) && $params['output'] == 'pdf_invoice') {
595 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
596 'Downloaded Invoice',
597 'name'
598 );
599 }
600 else{
601 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
602 'Emailed Invoice',
603 'name'
604 );
605 }
606
607 $activityParams = array(
608 'subject' => $subject,
609 'source_contact_id' => $userID,
610 'target_contact_id' => $contactIds,
611 'activity_type_id' => $activityTypeID,
612 'activity_date_time' => date('YmdHis'),
613 'attachFile_1' => array(
614 'uri' => $fileName,
615 'type' => 'application/pdf',
616 'location' => $fileName,
617 'upload_date' => date('YmdHis'),
618 ),
619 );
620 CRM_Activity_BAO_Activity::create($activityParams);
621 }
622
623 /**
624 *
625 * This function is use for creating the Invoice file in upload folder
626 * for attachment
627 *
628 * @param $html content for pdf in html format
629 *
630 * return $fileName of file which is in pdf format
631 *
632 * @return string
633 */
634 static public function putFile($html) {
635 require_once("packages/dompdf/dompdf_config.inc.php");
636 spl_autoload_register('DOMPDF_autoload');
637 $doc = new DOMPDF();
638 $doc->load_html($html);
639 $doc->render();
640 $html = $doc->output();
641 $config = CRM_Core_Config::singleton();
642 $fileName = $config->uploadDir . 'Invoice.pdf';
643 file_put_contents($fileName, $html);
644 return $fileName;
645 }
646
647 /**
648 * Callback to perform action on Print Invoice button.
649 */
650 public static function getPrintPDF() {
651 $contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
652 $contributionIDs = array($contributionId);
653 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
654 $params = array('output' => 'pdf_invoice');
655 CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId, CRM_Core_DAO::$_nullObject);
656 }
657 }