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