INFRA-132 - Remove extra newlines from the bottom of docblocks
[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 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 * @return void
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 *
144 * @return void
145 */
146 public function buildQuickForm() {
147 $session = CRM_Core_Session::singleton();
148 if (CRM_Core_Permission::check('administer CiviCRM')) {
149 $this->assign('isAdmin', 1);
150 }
151 $contactID = $session->get('userID');
152 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
153 $emails = array();
154 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
155 $contactID, 'display_name'
156 );
157 foreach ($contactEmails as $emailId => $item) {
158 $email = $item['email'];
159 if ($email) {
160 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
161 }
162 if (isset($emails[$emailId])) {
163 $emails[$emailId] .= $item['locationType'];
164 if ($item['is_primary']) {
165 $emails[$emailId] .= ' ' . ts('(preferred)');
166 }
167 $emails[$emailId] = htmlspecialchars($emails[$emailId]);
168 }
169 }
170 $fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address');
171 foreach ($fromEmailAddress as $key => $email) {
172 $fromEmailAddress[$key] = htmlspecialchars($fromEmailAddress[$key]);
173 }
174 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, $fromEmailAddress);
175 $this->add('select', 'from_email_address', ts('From Email Address'), array('' => '- select -') + $fromEmail);
176 if ($this->_selectedOutput != 'email') {
177 $this->addElement('radio', 'output', NULL, ts('Email Invoice'), 'email_invoice');
178 $this->addElement('radio', 'output', NULL, ts('PDF Invoice'), 'pdf_invoice');
179 $this->addRule('output', ts('Selection required'), 'required');
180 $this->addFormRule(array('CRM_Contribute_Form_Task_Invoice', 'formRule'));
181 }
182 else {
183 $this->addRule('from_email_address', ts('From Email Address is required'), 'required');
184 }
185
186 $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(
187 'rows' => 2,
188 'cols' => 40,
189 ));
190
191 $this->addButtons(array(
192 array(
193 'type' => 'upload',
194 'name' => $this->_selectedOutput == 'email' ? ts('Send Email') : ts('Process Invoice(s)'),
195 'isDefault' => TRUE,
196 ),
197 array(
198 'type' => 'cancel',
199 'name' => ts('Cancel'),
200 ),
201 )
202 );
203 }
204
205 /**
206 * Global validation rules for the form
207 *
208 * @param array $values
209 *
210 * @return array
211 * list of errors to be posted back to the form
212 * @static
213 */
214 public static function formRule($values) {
215 $errors = array();
216
217 if ($values['output'] == 'email_invoice' && empty($values['from_email_address'])) {
218 $errors['from_email_address'] = ts("From Email Address is required");
219 }
220
221 return $errors;
222 }
223
224 /**
225 * Process the form after the input has been submitted and validated
226 *
227 *
228 * @return void
229 */
230 public function postProcess() {
231 $params = $this->controller->exportValues($this->_name);
232 $this->printPDF($this->_contributionIds, $params, $this->_contactIds, $this);
233 }
234
235 /**
236 *
237 * process the PDf and email with activity and attachment
238 * on click of Print Invoices
239 *
240 * @param array $contribIDs
241 * Contribution Id.
242 * @param array $params
243 * Associated array of submitted values.
244 * @param array $contactIds
245 * Contact Id.
246 * @param CRM_Core_Form $form
247 * Form object.
248 * @static
249 */
250 public static function printPDF($contribIDs, &$params, $contactIds, &$form) {
251 // get all the details needed to generate a invoice
252 $messageInvoice = array();
253 $invoiceTemplate = CRM_Core_Smarty::singleton();
254 $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
255
256 // gives the status id when contribution status is 'Refunded'
257 $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
258 $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
259
260 // getting data from admin page
261 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
262
263 foreach ($invoiceElements['details'] as $contribID => $detail) {
264 $input = $ids = $objects = array();
265 if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
266 continue;
267 }
268
269 $input['component'] = $detail['component'];
270
271 $ids['contact'] = $detail['contact'];
272 $ids['contribution'] = $contribID;
273 $ids['contributionRecur'] = NULL;
274 $ids['contributionPage'] = NULL;
275 $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
276 $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
277 $ids['event'] = CRM_Utils_Array::value('event', $detail);
278
279 if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
280 CRM_Core_Error::fatal();
281 }
282
283 $contribution = & $objects['contribution'];
284
285 $input['amount'] = $contribution->total_amount;
286 $input['invoice_id'] = $contribution->invoice_id;
287 $input['receive_date'] = $contribution->receive_date;
288 $input['contribution_status_id'] = $contribution->contribution_status_id;
289 $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
290
291 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
292
293 $addressParams = array('contact_id' => $contribution->contact_id);
294 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
295
296 // to get billing address if present
297 $billingAddress = array();
298 foreach ($addressDetails as $key => $address) {
299 if ((isset($address['is_billing']) && $address['is_billing'] == 1) && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
300 $billingAddress[$address['contact_id']] = $address;
301 break;
302 }
303 elseif (($address['is_billing'] == 0 && $address['is_primary'] == 1) || (isset($address['is_billing']) && $address['is_billing'] == 1) && $address['contact_id'] == $contribution->contact_id) {
304 $billingAddress[$address['contact_id']] = $address;
305 }
306 }
307
308 if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
309 $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
310 }
311 else {
312 $stateProvinceAbbreviation = '';
313 }
314
315 if ($contribution->contribution_status_id == $refundedStatusId) {
316 $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id;
317 }
318 $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
319
320 //to obtain due date for PDF invoice
321 $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
322 $invoiceDate = date("F j, Y");
323 $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
324
325 if ($input['component'] == 'contribute') {
326 $eid = $contribID;
327 $etable = 'contribution';
328 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE);
329 }
330 else {
331 $eid = $contribution->_relatedObjects['participant']->id;
332 $etable = 'participant';
333 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable);
334 }
335
336 //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
337 $amountDue = ($input['amount'] - $input['amount']);
338
339 // retreiving the subtotal and sum of same tax_rate
340 $dataArray = array();
341 $subTotal = 0;
342 foreach ($lineItem as $entity_id => $taxRate) {
343 if (isset($dataArray[(string) $taxRate['tax_rate']])) {
344 $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
345 }
346 else {
347 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
348 }
349 $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
350 }
351
352 // to email the invoice
353 $mailDetails = array();
354 $values = array();
355 if ($contribution->_component == 'event') {
356 $daoName = 'CRM_Event_DAO_Event';
357 $pageId = $contribution->_relatedObjects['event']->id;
358 $mailElements = array(
359 'title',
360 'confirm_from_name',
361 'confirm_from_email',
362 'cc_confirm',
363 'bcc_confirm',
364 );
365 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
366 $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
367 $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
368 $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
369 $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
370 $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
371
372 $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
373 }
374 elseif ($contribution->_component == 'contribute') {
375 $daoName = 'CRM_Contribute_DAO_ContributionPage';
376 $pageId = $contribution->contribution_page_id;
377 $mailElements = array(
378 'title',
379 'receipt_from_name',
380 'receipt_from_email',
381 'cc_receipt',
382 'bcc_receipt',
383 );
384 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
385
386 $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
387 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
388 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
389 $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
390 $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
391
392 $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
393 }
394 $source = $contribution->source;
395
396 $config = CRM_Core_Config::singleton();
397 if (!isset($params['forPage'])) {
398 $config->doNotAttachPDFReceipt = 1;
399 }
400
401 // get organization address
402 $domain = CRM_Core_BAO_Domain::getDomain();
403 $locParams = array('contact_id' => $domain->id);
404 $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
405 if (isset($locationDefaults['address'][1]['state_province_id'])) {
406 $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
407 }
408 else {
409 $stateProvinceAbbreviationDomain = '';
410 }
411 if (isset($locationDefaults['address'][1]['country_id'])) {
412 $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
413 }
414 else {
415 $countryDomain = '';
416 }
417
418 // parameters to be assign for template
419 $tplParams = array(
420 'title' => $title,
421 'component' => $input['component'],
422 'id' => $contribution->id,
423 'source' => $source,
424 'invoice_id' => $invoiceId,
425 'resourceBase' => $config->userFrameworkResourceURL,
426 'defaultCurrency' => $config->defaultCurrency,
427 'amount' => $contribution->total_amount,
428 'amountDue' => $amountDue,
429 'invoice_date' => $invoiceDate,
430 'dueDate' => $dueDate,
431 'notes' => CRM_Utils_Array::value('notes', $prefixValue),
432 'display_name' => $contribution->_relatedObjects['contact']->display_name,
433 'lineItem' => $lineItem,
434 'dataArray' => $dataArray,
435 'refundedStatusId' => $refundedStatusId,
436 'contribution_status_id' => $contribution->contribution_status_id,
437 'subTotal' => $subTotal,
438 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
439 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
440 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
441 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
442 'stateProvinceAbbreviation' => $stateProvinceAbbreviation,
443 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
444 'is_pay_later' => $contribution->is_pay_later,
445 'organization_name' => $contribution->_relatedObjects['contact']->organization_name,
446 'domain_organization' => $domain->name,
447 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])),
448 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])),
449 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])),
450 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])),
451 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])),
452 'domain_state' => $stateProvinceAbbreviationDomain,
453 'domain_country' => $countryDomain,
454 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])),
455 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])),
456 );
457
458 if (isset($creditNoteId)) {
459 $tplParams['creditnote_id'] = $creditNoteId;
460 }
461
462 $sendTemplateParams = array(
463 'groupName' => 'msg_tpl_workflow_contribution',
464 'valueName' => 'contribution_invoice_receipt',
465 'contactId' => $contribution->contact_id,
466 'tplParams' => $tplParams,
467 'PDFFilename' => 'Invoice.pdf',
468 );
469 $session = CRM_Core_Session::singleton();
470 $contactID = $session->get('userID');
471 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
472 $emails = array();
473 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
474 $contactID, 'display_name'
475 );
476
477 foreach ($contactEmails as $emailId => $item) {
478 $email = $item['email'];
479 if ($email) {
480 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
481 }
482 }
483 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
484
485 // from email address
486 if (isset($params['from_email_address'])) {
487 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
488 }
489 // condition to check for download PDF Invoice or email Invoice
490 if ($invoiceElements['createPdf']) {
491 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
492 if (isset($params['forPage'])) {
493 return $html;
494 }
495 else {
496 $mail = array(
497 'subject' => $subject,
498 'body' => $message,
499 'html' => $html,
500 );
501 if ($mail['html']) {
502 $messageInvoice[] = $mail['html'];
503 }
504 else {
505 $messageInvoice[] = nl2br($mail['body']);
506 }
507 }
508 }
509 elseif ($contribution->_component == 'contribute') {
510 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
511
512 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
513 $sendTemplateParams['from'] = $fromEmailAddress;
514 $sendTemplateParams['toEmail'] = $email;
515 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
516 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
517
518 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
519 // functions call for adding activity with attachment
520 $fileName = self::putFile($html);
521 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
522 }
523 elseif ($contribution->_component == 'event') {
524 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
525
526 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
527 $sendTemplateParams['from'] = $fromEmailAddress;
528 $sendTemplateParams['toEmail'] = $email;
529 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
530 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
531
532 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
533 // functions call for adding activity with attachment
534 $fileName = self::putFile($html);
535 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
536 }
537
538 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
539 if ($contribution->contribution_status_id == $refundedStatusId) {
540 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
541 }
542 $invoiceTemplate->clearTemplateVars();
543 }
544
545 if ($invoiceElements['createPdf']) {
546 if (isset($params['forPage'])) {
547 return $html;
548 }
549 else {
550 CRM_Utils_PDF_Utils::html2pdf($messageInvoice, 'Invoice.pdf', FALSE, array(
551 'margin_top' => 10,
552 'margin_left' => 65,
553 'metric' => 'px',
554 ));
555 // functions call for adding activity with attachment
556 $fileName = self::putFile($html);
557 self::addActivities($subject, $contactIds, $fileName, $params);
558
559 CRM_Utils_System::civiExit();
560 }
561 }
562 else {
563 if ($invoiceElements['suppressedEmails']) {
564 $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']));
565 $msgTitle = ts('Email Error');
566 $msgType = 'error';
567 }
568 else {
569 $status = ts('Your mail has been sent.');
570 $msgTitle = ts('Sent');
571 $msgType = 'success';
572 }
573 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
574 }
575 }
576
577 /**
578 *
579 * This function is use for adding activity for
580 * Email Invoice and the PDF Invoice
581 *
582 * @param string $subject
583 * Activity subject.
584 * @param array $contactIds
585 * Contact Id.
586 * @param string $fileName
587 * Gives the location with name of the file.
588 * @param array $params
589 * For invoices.
590 *
591 * @static
592 */
593 static public function addActivities($subject, $contactIds, $fileName, $params) {
594 $session = CRM_Core_Session::singleton();
595 $userID = $session->get('userID');
596 $config = CRM_Core_Config::singleton();
597 $config->doNotAttachPDFReceipt = 1;
598
599 if (!empty($params['output']) && $params['output'] == 'pdf_invoice') {
600 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
601 'Downloaded Invoice',
602 'name'
603 );
604 }
605 else {
606 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
607 'Emailed Invoice',
608 'name'
609 );
610 }
611
612 $activityParams = array(
613 'subject' => $subject,
614 'source_contact_id' => $userID,
615 'target_contact_id' => $contactIds,
616 'activity_type_id' => $activityTypeID,
617 'activity_date_time' => date('YmdHis'),
618 'attachFile_1' => array(
619 'uri' => $fileName,
620 'type' => 'application/pdf',
621 'location' => $fileName,
622 'upload_date' => date('YmdHis'),
623 ),
624 );
625 CRM_Activity_BAO_Activity::create($activityParams);
626 }
627
628 /**
629 *
630 * This function is use for creating the Invoice file in upload folder
631 * for attachment
632 *
633 * @param $html
634 * Content for pdf in html format.
635 *
636 * return $fileName of file which is in pdf format
637 *
638 * @return string
639 */
640 static public function putFile($html) {
641 require_once "packages/dompdf/dompdf_config.inc.php";
642 spl_autoload_register('DOMPDF_autoload');
643 $doc = new DOMPDF();
644 $doc->load_html($html);
645 $doc->render();
646 $html = $doc->output();
647 $config = CRM_Core_Config::singleton();
648 $fileName = $config->uploadDir . 'Invoice.pdf';
649 file_put_contents($fileName, $html);
650 return $fileName;
651 }
652
653 /**
654 * Callback to perform action on Print Invoice button.
655 */
656 public static function getPrintPDF() {
657 $contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
658 $contributionIDs = array($contributionId);
659 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
660 $params = array('output' => 'pdf_invoice');
661 CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId, CRM_Core_DAO::$_nullObject);
662 }
663 }