Merge pull request #47 from pratikshad/VAT-578-messagetemplate
[civicrm-core.git] / CRM / Contribute / Form / Task / Invoice.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
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 * @access public
52 */
53 public $_contributionStatusId;
54
55 /**
56 * gives the HTML template of PDF Invoice
57 *
58 * @access public
59 */
60 public $_messageInvoice;
61
62 /**
63 * This variable is used to assign parameters for HTML template of PDF Invoice
64 *
65 * @access public
66 */
67 public $_invoiceTemplate;
68 /**
69 * build all the data structures needed to build the form
70 *
71 * @return void
72 * @access public
73 */
74 function preProcess() {
75 $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
76 if ($id) {
77 $this->_contributionIds = array($id);
78 $this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
79 $this->_single = TRUE;
80 $this->assign('totalSelectedContributions', 1);
81 }
82 else {
83 parent::preProcess();
84 }
85
86 // check that all the contribution ids have status Completed, Pending, Refunded.
87 $this->_contributionStatusId = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
88 $status = array('Completed', 'Pending', 'Refunded');
89 $statusId = array();
90 foreach ($this->_contributionStatusId as $key => $value) {
91 if (in_array($value, $status)) {
92 $statusId[] = $key;
93 }
94 }
95 $Id = implode(",", $statusId);
96 $query = "SELECT count(*) FROM civicrm_contribution WHERE contribution_status_id NOT IN ($Id) AND {$this->_componentClause}";
97 $count = CRM_Core_DAO::singleValueQuery($query);
98 if ($count != 0) {
99 CRM_Core_Error::statusBounce(ts('Please select only contributions with Completed, Pending, Refunded status.'));
100 }
101
102 // we have all the contribution ids, so now we get the contact ids
103 parent::setContactIDs();
104 $this->assign('single', $this->_single);
105
106 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
107 $urlParams = 'force=1';
108 if (CRM_Utils_Rule::qfKey($qfKey)) {
109 $urlParams .= "&qfKey=$qfKey";
110 }
111
112 $url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
113 $breadCrumb = array(
114 array('url' => $url,
115 'title' => ts('Search Results'),
116 ));
117
118 CRM_Utils_System::appendBreadCrumb($breadCrumb);
119 if (in_array("email", $this->urlPath)) {
120 CRM_Utils_System::setTitle(ts('Email Invoice'));
121 } else {
122 CRM_Utils_System::setTitle(ts('Print Contribution Invoice'));
123 }
124 }
125
126 /**
127 * Build the form
128 *
129 * @access public
130 *
131 * @return void
132 */
133 public function buildQuickForm() {
134 $session = CRM_Core_Session::singleton();
135 if (CRM_Core_Permission::check('administer CiviCRM')) {
136 $this->assign('isAdmin', 1);
137 }
138 $contactID = $session->get('userID');
139 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
140 $emails = array();
141 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
142 $contactID, 'display_name'
143 );
144 foreach ($contactEmails as $emailId => $item) {
145 $email = $item['email'];
146 if ($email) {
147 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
148 }
149 if (isset($emails[$emailId])) {
150 $emails[$emailId] .= $item['locationType'];
151 if ($item['is_primary']) {
152 $emails[$emailId] .= ' ' . ts('(preferred)');
153 }
154 $emails[$emailId] = htmlspecialchars($emails[$emailId]);
155 }
156 }
157 $fromEmailAddress = CRM_Core_OptionGroup::values('from_email_address');
158 foreach ($fromEmailAddress as $key => $email) {
159 $fromEmailAddress[$key] = htmlspecialchars($fromEmailAddress[$key]);
160 }
161 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, $fromEmailAddress);
162
163 $this->addElement('radio', 'output', NULL, ts('Email Invoice'), 'email_invoice');
164 $this->addElement('radio', 'output', NULL, ts('PDF Invoice'), 'pdf_invoice');
165 $this->add('select', 'from_email_address', ts('From Email Address'), array('' => '- select -') + $fromEmail);
166 $this->addFormRule(array('CRM_Contribute_Form_Task_Invoice', 'formRule'));
167 $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('rows' => 2, 'cols' => 40));
168
169 if (in_array("email", $this->urlPath)) {
170 $this->addButtons(array(
171 array(
172 'type' => 'next',
173 'name' => ts('Email Invoice'),
174 'isDefault' => TRUE,
175 ),
176 array(
177 'type' => 'back',
178 'name' => ts('Cancel'),
179 ),
180 )
181 );
182 } else {
183 $this->addButtons(array(
184 array(
185 'type' => 'next',
186 'name' => ts('Process Invoice(s)'),
187 'isDefault' => TRUE,
188 ),
189 array(
190 'type' => 'back',
191 'name' => ts('Cancel'),
192 ),
193 )
194 );
195 }
196 }
197
198 /**
199 * global validation rules for the form
200 *
201 * @param $values
202 *
203 * @internal param array $fields posted values of the form
204 *
205 * @return array list of errors to be posted back to the form
206 * @static
207 * @access public
208 */
209 static function formRule($values) {
210 $errors = array();
211 if (!$values['from_email_address']) {
212 if (in_array("Email Invoice", $values)) {
213 $errors['from_email_address'] = ts("From Email Address is required");
214 }
215 else {
216 if (in_array("email_invoice", $values)) {
217 $errors['from_email_address'] = ts("From Email Address is required");
218 }
219 else {
220 $errors['output'] = ts("Selection required");
221 }
222 }
223 }
224 return $errors;
225 }
226
227 /**
228 * process the form after the input has been submitted and validated
229 *
230 * @access public
231 *
232 * @return void
233 */
234 public function postProcess() {
235 $params = $this->controller->exportValues($this->_name);
236 $this->printPDF($this->_contributionIds, $params, $this->_contactIds);
237 }
238
239 /**
240 *
241 * process the PDf and email with activity and attachment
242 * on click of Print Invoices
243 *
244 * @param array $contribIDs Contribution Id
245 * @param array $params for pdf or email invoices
246 * @param array $contactIds Contact Id
247 * @static
248 *
249 */
250 static function printPDF($contribIDs, $params, $contactIds) {
251 // get all the details needed to generate a invoice
252 $messageInvoice = array();
253
254 $invoiceTemplate = CRM_Core_Smarty::singleton();
255
256 $invoiceElements = CRM_Contribute_Form_Task_PDF::getElements($contribIDs, $params, $contactIds);
257
258 // gives the status id when contribution status is 'Refunded'
259 $contributionStatusID = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
260 $refundedStatusId = CRM_Utils_Array::key('Refunded', $contributionStatusID);
261
262 // getting data from admin page
263 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME,'contribution_invoice_settings');
264
265 foreach ($invoiceElements['details'] as $contribID => $detail) {
266 $input = $ids = $objects = array();
267
268 if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
269 continue;
270 }
271
272 $input['component'] = $detail['component'];
273
274 $ids['contact'] = $detail['contact'];
275 $ids['contribution'] = $contribID;
276 $ids['contributionRecur'] = NULL;
277 $ids['contributionPage'] = NULL;
278 $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
279 $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
280 $ids['event'] = CRM_Utils_Array::value('event', $detail);
281
282 if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
283 CRM_Core_Error::fatal();
284 }
285
286 $contribution = &$objects['contribution'];
287
288 $input['amount'] = $contribution->total_amount;
289 $input['invoice_id'] = $contribution->invoice_id;
290 $input['receive_date'] = $contribution->receive_date;
291 $input['contribution_status_id'] = $contribution->contribution_status_id;
292 $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
293
294 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
295
296 $addressParams = array('contact_id' => $contribution->contact_id);
297 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
298
299 // to get billing address if present
300 $billingAddress = array();
301 foreach ($addressDetails as $key => $address) {
302 if ((isset($address['is_billing']) && $address['is_billing'] == 1) && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
303 $billingAddress[$address['contact_id']] = $address;
304 break;
305 }
306 elseif (($address['is_billing'] == 0 && $address['is_primary'] == 1) || (isset($address['is_billing']) && $address['is_billing'] == 1) && $address['contact_id'] == $contribution->contact_id) {
307 $billingAddress[$address['contact_id']] = $address;
308 }
309 }
310
311 if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
312 $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
313 }
314 else {
315 $stateProvinceAbbreviation = '';
316 }
317
318 if ($contribution->contribution_status_id == $refundedStatusId) {
319 $creditNoteId = CRM_Utils_Array::value('credit_notes_prefix', $prefixValue) . "" . $contribution->id;
320 }
321 $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
322
323 //to obtain due date for PDF invoice
324 $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
325 $invoiceDate = date("F j, Y");
326 $dueDate = date('F j ,Y', strtotime($contributionReceiveDate. "+" .$prefixValue['due_date']. "" .$prefixValue['due_date_period']));
327
328 if ($input['component'] == 'contribute') {
329 $eid = $contribID;
330 $etable = 'contribution';
331 }
332 else {
333 $eid = $contribution->_relatedObjects['participant']->id;
334 $etable = 'participant';
335 }
336
337 //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
338 $amountDue = ($input['amount'] - $input['amount']);
339
340 // retreiving the subtotal and sum of same tax_rate
341 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable);
342 $dataArray = array();
343 $subTotal = 0;
344 foreach ($lineItem as $entity_id => $taxRate) {
345 if (isset($dataArray[(string)$taxRate['tax_rate']])) {
346 $dataArray[(string)$taxRate['tax_rate']] = $dataArray[(string)$taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
347 }
348 else {
349 $dataArray[(string)$taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
350 }
351 $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
352 }
353
354 // to email the invoice
355 $mailDetails = array();
356 $values = array();
357 if ($contribution->_component == 'event') {
358 $daoName = 'CRM_Event_DAO_Event';
359 $pageId = $contribution->_relatedObjects['event']->id;
360 $mailElements = array(
361 'title',
362 'confirm_from_name',
363 'confirm_from_email',
364 'cc_confirm',
365 'bcc_confirm',
366 );
367 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
368 $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
369 $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
370 $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
371 $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
372 $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
373
374 $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
375 }
376 elseif ($contribution->_component == 'contribute') {
377 $daoName = 'CRM_Contribute_DAO_ContributionPage';
378 $pageId = $contribution->contribution_page_id;
379 $mailElements = array(
380 'title',
381 'receipt_from_name',
382 'receipt_from_email',
383 'cc_receipt',
384 'bcc_receipt',
385 );
386 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
387
388 $values['title'] = CRM_Utils_Array::value('title',CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
389 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
390 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
391 $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
392 $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
393
394 $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
395 }
396 $source = $contribution->source;
397
398 $config = CRM_Core_Config::singleton();
399 if (!isset($params['forPage'])) {
400 $config->doNotAttachPDFReceipt = 1;
401 }
402
403 // get organization address
404 $domain = CRM_Core_BAO_Domain::getDomain();
405 $locParams = array('contact_id' => $domain->id);
406 $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
407 if (isset($locationDefaults['address'][1]['state_province_id'])) {
408 $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
409 }
410 else {
411 $stateProvinceAbbreviationDomain = '';
412 }
413 if (isset($locationDefaults['address'][1]['country_id'])) {
414 $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
415 }
416 else {
417 $countryDomain = '';
418 }
419
420 // parameters to be assign for template
421 $tplParams = array(
422 'title' => $title,
423 'component' => $input['component'],
424 'id' => $contribution->id,
425 'source' => $source,
426 'invoice_id' => $invoiceId,
427 'imageUploadURL' => $config->imageUploadURL,
428 'defaultCurrency' => $config->defaultCurrency,
429 'amount' => $contribution->total_amount,
430 'amountDue' => $amountDue,
431 'invoice_date' => $invoiceDate,
432 'dueDate' => $dueDate,
433 'notes' => CRM_Utils_Array::value('notes', $prefixValue),
434 'display_name' => $contribution->_relatedObjects['contact']->display_name,
435 'lineItem' => $lineItem,
436 'dataArray' => $dataArray,
437 'refundedStatusId' => $refundedStatusId,
438 'contribution_status_id' => $contribution->contribution_status_id,
439 'subTotal' => $subTotal,
440 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id,$billingAddress)),
441 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id,$billingAddress)),
442 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id,$billingAddress)),
443 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id,$billingAddress)),
444 'stateProvinceAbbreviation' => $stateProvinceAbbreviation,
445 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id,$billingAddress)),
446 'is_pay_later' => $contribution->is_pay_later,
447 'organization_name' => $contribution->_relatedObjects['contact']->organization_name,
448 'domain_organization' => $domain->name,
449 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])),
450 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])),
451 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])),
452 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])),
453 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])),
454 'domain_state' => $stateProvinceAbbreviationDomain,
455 'domain_country' => $countryDomain,
456 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])),
457 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])),
458 );
459 if (isset($creditNoteId)) {
460 $tplParams['creditnote_id'] = $creditNoteId;
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 $updateInvoiceId = CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
539 if ($contribution->contribution_status_id == $refundedStatusId) {
540 $updateInvoiceId = 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('margin_top'=>10, 'margin_left'=>65, 'metric'=>'px'));
551 // functions call for adding activity with attachment
552 $fileName = self::putFile($html);
553 self::addActivities($subject, $contactIds, $fileName, $params['output']);
554
555 CRM_Utils_System::civiExit();
556 }
557 }
558 else {
559 if ($invoiceElements['suppressedEmails']) {
560 $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']));
561 $msgTitle = ts('Email Error');
562 $msgType = 'error';
563 }
564 else {
565 $status = ts('Your mail has been sent.');
566 $msgTitle = ts('Sent');
567 $msgType = 'success';
568 }
569 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
570 }
571 }
572
573 /**
574 *
575 * This function is use for adding activity for
576 * Email Invoice and the PDF Invoice
577 *
578 * @param string $subject Activity subject
579 * @param array $contactIds Contact Id
580 * @param string $fileName gives the location with name of the file
581 * @param array $output for invoices
582 *
583 */
584 public function addActivities($subject, $contactIds, $fileName, $output) {
585 $session = CRM_Core_Session::singleton();
586 $userID = $session->get('userID');
587 $config = CRM_Core_Config::singleton();
588 $config->doNotAttachPDFReceipt = 1;
589 if ($output['output'] == 'email_invoice' || (is_array($output) && array_key_exists("from_email_address", $output))) {
590 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
591 'Emailed Invoice',
592 'name'
593 );
594 } else {
595 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
596 'Downloaded Invoice',
597 'name'
598 );
599 }
600 $activityParams = array(
601 'subject' => $subject,
602 'source_contact_id' => $userID,
603 'target_contact_id' => $contactIds,
604 'activity_type_id' => $activityTypeID,
605 'activity_date_time' => date('YmdHis'),
606 'attachFile_1' => array ('uri' => $fileName,
607 'type' => 'application/pdf',
608 'location' => $fileName,
609 'upload_date' => date('YmdHis'),
610 ),
611 );
612 $activity = CRM_Activity_BAO_Activity::create($activityParams);
613 }
614
615 /**
616 *
617 * This function is use for creating the Invoice file in upload folder
618 * for attachment
619 *
620 * @param $html content for pdf in html format
621 *
622 * return $fileName of file which is in pdf format
623 *
624 */
625 public function putFile($html) {
626 require_once("packages/dompdf/dompdf_config.inc.php");
627 spl_autoload_register('DOMPDF_autoload');
628 $doc = new DOMPDF();
629 $doc->load_html($html);
630 $doc->render();
631 $html = $doc->output();
632 $config = CRM_Core_Config::singleton();
633 $fileName = $config->uploadDir.'Invoice.pdf';
634 $file = file_put_contents($fileName, $html);
635 return $fileName;
636 }
637
638 }
639