commiting uncommited changes on live site
[weblabels.fsf.org.git] / crm.fsf.org / 20131203 / files / sites / all / modules-old / civicrm / CRM / Contribute / Form / Task / Invoice.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2015 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 use Dompdf\Dompdf;
29 use Dompdf\Options;
30 /**
31 *
32 * @package CRM
33 * @copyright CiviCRM LLC (c) 2004-2015
34 *
35 */
36
37 /**
38 * This class provides the functionality to email a group of
39 * contacts.
40 */
41 class CRM_Contribute_Form_Task_Invoice extends CRM_Contribute_Form_Task {
42 /**
43 * Are we operating in "single mode", i.e. updating the task of only
44 * one specific contribution?
45 *
46 * @var boolean
47 */
48 public $_single = FALSE;
49
50 /**
51 * Gives all the statues for conribution.
52 */
53 public $_contributionStatusId;
54
55 /**
56 * Gives the HTML template of PDF Invoice.
57 */
58 public $_messageInvoice;
59
60 /**
61 * This variable is used to assign parameters for HTML template of PDF Invoice.
62 */
63 public $_invoiceTemplate;
64
65 /**
66 * Selected output.
67 */
68 public $_selectedOutput;
69
70 /**
71 * Build all the data structures needed to build the form.
72 *
73 * @return void
74 */
75 public function preProcess() {
76 $id = CRM_Utils_Request::retrieve('id', 'Positive', $this, FALSE);
77 if ($id) {
78 $this->_contributionIds = array($id);
79 $this->_componentClause = " civicrm_contribution.id IN ( $id ) ";
80 $this->_single = TRUE;
81 $this->assign('totalSelectedContributions', 1);
82
83 // set the redirection after actions
84 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', $this, FALSE);
85 $url = CRM_Utils_System::url('civicrm/contact/view/contribution',
86 "action=view&reset=1&id={$id}&cid={$contactId}&context=contribution&selectedChild=contribute"
87 );
88
89 CRM_Core_Session::singleton()->pushUserContext($url);
90 }
91 else {
92 parent::preProcess();
93 }
94
95 // check that all the contribution ids have status Completed, Pending, Refunded.
96 $this->_contributionStatusId = CRM_Contribute_PseudoConstant::contributionStatus(NULL, 'name');
97 $status = array('Completed', 'Pending', 'Refunded');
98 $statusId = array();
99 foreach ($this->_contributionStatusId as $key => $value) {
100 if (in_array($value, $status)) {
101 $statusId[] = $key;
102 }
103 }
104 $Id = implode(",", $statusId);
105 $query = "SELECT count(*) FROM civicrm_contribution WHERE contribution_status_id NOT IN ($Id) AND {$this->_componentClause}";
106 $count = CRM_Core_DAO::singleValueQuery($query);
107 if ($count != 0) {
108 CRM_Core_Error::statusBounce(ts('Please select only contributions with Completed, Pending, Refunded status.'));
109 }
110
111 // we have all the contribution ids, so now we get the contact ids
112 parent::setContactIDs();
113 $this->assign('single', $this->_single);
114
115 $qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this);
116 $urlParams = 'force=1';
117 if (CRM_Utils_Rule::qfKey($qfKey)) {
118 $urlParams .= "&qfKey=$qfKey";
119 }
120
121 $url = CRM_Utils_System::url('civicrm/contribute/search', $urlParams);
122 $breadCrumb = array(
123 array(
124 'url' => $url,
125 'title' => ts('Search Results'),
126 ),
127 );
128
129 CRM_Utils_System::appendBreadCrumb($breadCrumb);
130
131 $this->_selectedOutput = CRM_Utils_Request::retrieve('select', 'String', $this);
132 $this->assign('selectedOutput', $this->_selectedOutput);
133
134 if ($this->_selectedOutput == 'email') {
135 CRM_Utils_System::setTitle(ts('Email Invoice'));
136 }
137 else {
138 CRM_Utils_System::setTitle(ts('Print Contribution Invoice'));
139 }
140 }
141
142 /**
143 * Build the form object.
144 *
145 *
146 * @return void
147 */
148 public function buildQuickForm() {
149 $session = CRM_Core_Session::singleton();
150 $this->preventAjaxSubmit();
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
214 * list of errors to be posted back to the form
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 * Process the PDf and email with activity and attachment.
239 * on click of Print Invoices
240 *
241 * @param array $contribIDs
242 * Contribution Id.
243 * @param array $params
244 * Associated array of submitted values.
245 * @param array $contactIds
246 * Contact Id.
247 * @param CRM_Core_Form $form
248 * Form object.
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 $cancelledStatusId = CRM_Utils_Array::key('Cancelled', $contributionStatusID);
260
261 // getting data from admin page
262 $prefixValue = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::CONTRIBUTE_PREFERENCES_NAME, 'contribution_invoice_settings');
263
264 foreach ($invoiceElements['details'] as $contribID => $detail) {
265 $input = $ids = $objects = array();
266 if (in_array($detail['contact'], $invoiceElements['excludeContactIds'])) {
267 continue;
268 }
269
270 $input['component'] = $detail['component'];
271
272 $ids['contact'] = $detail['contact'];
273 $ids['contribution'] = $contribID;
274 $ids['contributionRecur'] = NULL;
275 $ids['contributionPage'] = NULL;
276 $ids['membership'] = CRM_Utils_Array::value('membership', $detail);
277 $ids['participant'] = CRM_Utils_Array::value('participant', $detail);
278 $ids['event'] = CRM_Utils_Array::value('event', $detail);
279
280 if (!$invoiceElements['baseIPN']->validateData($input, $ids, $objects, FALSE)) {
281 CRM_Core_Error::fatal();
282 }
283
284 $contribution = &$objects['contribution'];
285
286 $input['amount'] = $contribution->total_amount;
287 $input['invoice_id'] = $contribution->invoice_id;
288 $input['receive_date'] = $contribution->receive_date;
289 $input['contribution_status_id'] = $contribution->contribution_status_id;
290 $input['organization_name'] = $contribution->_relatedObjects['contact']->organization_name;
291
292 $objects['contribution']->receive_date = CRM_Utils_Date::isoToMysql($objects['contribution']->receive_date);
293
294 $addressParams = array('contact_id' => $contribution->contact_id);
295 $addressDetails = CRM_Core_BAO_Address::getValues($addressParams);
296
297 // to get billing address if present
298 $billingAddress = array();
299 foreach ($addressDetails as $key => $address) {
300 if ((isset($address['is_billing']) && $address['is_billing'] == 1) && (isset($address['is_primary']) && $address['is_primary'] == 1) && $address['contact_id'] == $contribution->contact_id) {
301 $billingAddress[$address['contact_id']] = $address;
302 break;
303 }
304 elseif (($address['is_billing'] == 0 && $address['is_primary'] == 1) || (isset($address['is_billing']) && $address['is_billing'] == 1) && $address['contact_id'] == $contribution->contact_id) {
305 $billingAddress[$address['contact_id']] = $address;
306 }
307 }
308
309 if (!empty($billingAddress[$contribution->contact_id]['state_province_id'])) {
310 $stateProvinceAbbreviation = CRM_Core_PseudoConstant::stateProvinceAbbreviation($billingAddress[$contribution->contact_id]['state_province_id']);
311 }
312 else {
313 $stateProvinceAbbreviation = '';
314 }
315
316 if ($contribution->contribution_status_id == $refundedStatusId || $contribution->contribution_status_id == $cancelledStatusId) {
317 if (is_null($contribution->creditnote_id)) {
318 $creditNoteId = CRM_Contribute_BAO_Contribution::createCreditNoteId();
319 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'creditnote_id', $creditNoteId);
320 }
321 else {
322 $creditNoteId = $contribution->creditnote_id;
323 }
324 }
325 $invoiceId = CRM_Utils_Array::value('invoice_prefix', $prefixValue) . "" . $contribution->id;
326
327 //to obtain due date for PDF invoice
328 $contributionReceiveDate = date('F j,Y', strtotime(date($input['receive_date'])));
329 $invoiceDate = date("F j, Y");
330 $dueDate = date('F j ,Y', strtotime($contributionReceiveDate . "+" . $prefixValue['due_date'] . "" . $prefixValue['due_date_period']));
331
332 if ($input['component'] == 'contribute') {
333 $eid = $contribID;
334 $etable = 'contribution';
335 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, TRUE);
336 }
337 else {
338 $eid = $contribution->_relatedObjects['participant']->id;
339 $etable = 'participant';
340 $lineItem = CRM_Price_BAO_LineItem::getLineItems($eid, $etable, NULL, TRUE, FALSE, '', TRUE);
341 }
342
343 //TO DO: Need to do changes for partially paid to display amount due on PDF invoice
344 $amountDue = ($input['amount'] - $input['amount']);
345
346 // retreiving the subtotal and sum of same tax_rate
347 $dataArray = array();
348 $subTotal = 0;
349 foreach ($lineItem as $entity_id => $taxRate) {
350 if (isset($dataArray[(string) $taxRate['tax_rate']])) {
351 $dataArray[(string) $taxRate['tax_rate']] = $dataArray[(string) $taxRate['tax_rate']] + CRM_Utils_Array::value('tax_amount', $taxRate);
352 }
353 else {
354 $dataArray[(string) $taxRate['tax_rate']] = CRM_Utils_Array::value('tax_amount', $taxRate);
355 }
356 $subTotal += CRM_Utils_Array::value('subTotal', $taxRate);
357 }
358
359 // to email the invoice
360 $mailDetails = array();
361 $values = array();
362 if ($contribution->_component == 'event') {
363 $daoName = 'CRM_Event_DAO_Event';
364 $pageId = $contribution->_relatedObjects['event']->id;
365 $mailElements = array(
366 'title',
367 'confirm_from_name',
368 'confirm_from_email',
369 'cc_confirm',
370 'bcc_confirm',
371 );
372 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
373 $values['title'] = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
374 $values['confirm_from_name'] = CRM_Utils_Array::value('confirm_from_name', $mailDetails[$contribution->_relatedObjects['event']->id]);
375 $values['confirm_from_email'] = CRM_Utils_Array::value('confirm_from_email', $mailDetails[$contribution->_relatedObjects['event']->id]);
376 $values['cc_confirm'] = CRM_Utils_Array::value('cc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
377 $values['bcc_confirm'] = CRM_Utils_Array::value('bcc_confirm', $mailDetails[$contribution->_relatedObjects['event']->id]);
378
379 $title = CRM_Utils_Array::value('title', $mailDetails[$contribution->_relatedObjects['event']->id]);
380 }
381 elseif ($contribution->_component == 'contribute') {
382 $daoName = 'CRM_Contribute_DAO_ContributionPage';
383 $pageId = $contribution->contribution_page_id;
384 $mailElements = array(
385 'title',
386 'receipt_from_name',
387 'receipt_from_email',
388 'cc_receipt',
389 'bcc_receipt',
390 );
391 CRM_Core_DAO::commonRetrieveAll($daoName, 'id', $pageId, $mailDetails, $mailElements);
392
393 $values['title'] = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
394 $values['receipt_from_name'] = CRM_Utils_Array::value('receipt_from_name', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
395 $values['receipt_from_email'] = CRM_Utils_Array::value('receipt_from_email', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
396 $values['cc_receipt'] = CRM_Utils_Array::value('cc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
397 $values['bcc_receipt'] = CRM_Utils_Array::value('bcc_receipt', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
398
399 $title = CRM_Utils_Array::value('title', CRM_Utils_Array::value($contribution->contribution_page_id, $mailDetails));
400 }
401 $source = $contribution->source;
402
403 $config = CRM_Core_Config::singleton();
404 if (!isset($params['forPage'])) {
405 $config->doNotAttachPDFReceipt = 1;
406 }
407
408 // get organization address
409 $domain = CRM_Core_BAO_Domain::getDomain();
410 $locParams = array('contact_id' => $domain->contact_id);
411 $locationDefaults = CRM_Core_BAO_Location::getValues($locParams);
412 if (isset($locationDefaults['address'][1]['state_province_id'])) {
413 $stateProvinceAbbreviationDomain = CRM_Core_PseudoConstant::stateProvinceAbbreviation($locationDefaults['address'][1]['state_province_id']);
414 }
415 else {
416 $stateProvinceAbbreviationDomain = '';
417 }
418 if (isset($locationDefaults['address'][1]['country_id'])) {
419 $countryDomain = CRM_Core_PseudoConstant::country($locationDefaults['address'][1]['country_id']);
420 }
421 else {
422 $countryDomain = '';
423 }
424
425 // parameters to be assign for template
426 $tplParams = array(
427 'title' => $title,
428 'component' => $input['component'],
429 'id' => $contribution->id,
430 'source' => $source,
431 'invoice_id' => $invoiceId,
432 'resourceBase' => $config->userFrameworkResourceURL,
433 'defaultCurrency' => $config->defaultCurrency,
434 'amount' => $contribution->total_amount,
435 'amountDue' => $amountDue,
436 'invoice_date' => $invoiceDate,
437 'dueDate' => $dueDate,
438 'notes' => CRM_Utils_Array::value('notes', $prefixValue),
439 'display_name' => $contribution->_relatedObjects['contact']->display_name,
440 'lineItem' => $lineItem,
441 'dataArray' => $dataArray,
442 'refundedStatusId' => $refundedStatusId,
443 'cancelledStatusId' => $cancelledStatusId,
444 'contribution_status_id' => $contribution->contribution_status_id,
445 'subTotal' => $subTotal,
446 'street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
447 'supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
448 'supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
449 'city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
450 'stateProvinceAbbreviation' => $stateProvinceAbbreviation,
451 'postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value($contribution->contact_id, $billingAddress)),
452 'is_pay_later' => $contribution->is_pay_later,
453 'organization_name' => $contribution->_relatedObjects['contact']->organization_name,
454 'domain_organization' => $domain->name,
455 'domain_street_address' => CRM_Utils_Array::value('street_address', CRM_Utils_Array::value('1', $locationDefaults['address'])),
456 'domain_supplemental_address_1' => CRM_Utils_Array::value('supplemental_address_1', CRM_Utils_Array::value('1', $locationDefaults['address'])),
457 'domain_supplemental_address_2' => CRM_Utils_Array::value('supplemental_address_2', CRM_Utils_Array::value('1', $locationDefaults['address'])),
458 'domain_city' => CRM_Utils_Array::value('city', CRM_Utils_Array::value('1', $locationDefaults['address'])),
459 'domain_postal_code' => CRM_Utils_Array::value('postal_code', CRM_Utils_Array::value('1', $locationDefaults['address'])),
460 'domain_state' => $stateProvinceAbbreviationDomain,
461 'domain_country' => $countryDomain,
462 'domain_email' => CRM_Utils_Array::value('email', CRM_Utils_Array::value('1', $locationDefaults['email'])),
463 'domain_phone' => CRM_Utils_Array::value('phone', CRM_Utils_Array::value('1', $locationDefaults['phone'])),
464 );
465
466 if (isset($creditNoteId)) {
467 $tplParams['creditnote_id'] = $creditNoteId;
468 }
469
470 $pdfFileName = "{$invoiceId}.pdf";
471 $sendTemplateParams = array(
472 'groupName' => 'msg_tpl_workflow_contribution',
473 'valueName' => 'contribution_invoice_receipt',
474 'contactId' => $contribution->contact_id,
475 'tplParams' => $tplParams,
476 'PDFFilename' => $pdfFileName,
477 );
478 $session = CRM_Core_Session::singleton();
479 $contactID = $session->get('userID');
480 //CRM-16319 - we dont store in userID in case the user is doing multiple
481 //transactions etc
482 if (empty($contactID)) {
483 $contactID = $session->get('transaction.userID');
484 }
485 // Fix Invoice email doesnot send out when completed payment using Paypal
486 if (empty($contactID)) {
487 $contactID = current($contactIds);
488 }
489 $contactEmails = CRM_Core_BAO_Email::allEmails($contactID);
490 $emails = array();
491 $fromDisplayName = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact',
492 $contactID, 'display_name'
493 );
494
495 foreach ($contactEmails as $emailId => $item) {
496 $email = $item['email'];
497 if ($email) {
498 $emails[$emailId] = '"' . $fromDisplayName . '" <' . $email . '> ';
499 }
500 }
501 $fromEmail = CRM_Utils_Array::crmArrayMerge($emails, CRM_Core_OptionGroup::values('from_email_address'));
502
503 // from email address
504 if (isset($params['from_email_address'])) {
505 $fromEmailAddress = CRM_Utils_Array::value($params['from_email_address'], $fromEmail);
506 }
507 // condition to check for download PDF Invoice or email Invoice
508 if ($invoiceElements['createPdf']) {
509 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
510 if (isset($params['forPage'])) {
511 return $html;
512 }
513 else {
514 $mail = array(
515 'subject' => $subject,
516 'body' => $message,
517 'html' => $html,
518 );
519 if ($mail['html']) {
520 $messageInvoice[] = $mail['html'];
521 }
522 else {
523 $messageInvoice[] = nl2br($mail['body']);
524 }
525 }
526 }
527 elseif ($contribution->_component == 'contribute') {
528 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
529
530 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
531 $sendTemplateParams['from'] = $fromEmailAddress;
532 $sendTemplateParams['toEmail'] = $email;
533 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_receipt', $values);
534 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_receipt', $values);
535
536 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
537 // functions call for adding activity with attachment
538 $pdfFileName = "{$invoiceId}.pdf";
539 $fileName = self::putFile($html, $pdfFileName);
540 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
541 }
542 elseif ($contribution->_component == 'event') {
543 $email = CRM_Contact_BAO_Contact::getPrimaryEmail($contribution->contact_id);
544
545 $sendTemplateParams['tplParams'] = array_merge($tplParams, array('email_comment' => $invoiceElements['params']['email_comment']));
546 $sendTemplateParams['from'] = $fromEmailAddress;
547 $sendTemplateParams['toEmail'] = $email;
548 $sendTemplateParams['cc'] = CRM_Utils_Array::value('cc_confirm', $values);
549 $sendTemplateParams['bcc'] = CRM_Utils_Array::value('bcc_confirm', $values);
550
551 list($sent, $subject, $message, $html) = CRM_Core_BAO_MessageTemplate::sendTemplate($sendTemplateParams);
552 // functions call for adding activity with attachment
553 $pdfFileName = "{$invoiceId}.pdf";
554 $fileName = self::putFile($html, $pdfFileName);
555 self::addActivities($subject, $contribution->contact_id, $fileName, $params);
556 }
557
558 CRM_Core_DAO::setFieldValue('CRM_Contribute_DAO_Contribution', $contribution->id, 'invoice_id', $invoiceId);
559 $invoiceTemplate->clearTemplateVars();
560 }
561
562 if ($invoiceElements['createPdf']) {
563 if (isset($params['forPage'])) {
564 return $html;
565 }
566 else {
567 $pdfFileName = "{$invoiceId}.pdf";
568 CRM_Utils_PDF_Utils::html2pdf($messageInvoice, $pdfFileName, FALSE, array(
569 'margin_top' => 10,
570 'margin_left' => 65,
571 'metric' => 'px',
572 ));
573 // functions call for adding activity with attachment
574 $fileName = self::putFile($html, $pdfFileName);
575 self::addActivities($subject, $contactIds, $fileName, $params);
576
577 CRM_Utils_System::civiExit();
578 }
579 }
580 else {
581 if ($invoiceElements['suppressedEmails']) {
582 $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']));
583 $msgTitle = ts('Email Error');
584 $msgType = 'error';
585 }
586 else {
587 $status = ts('Your mail has been sent.');
588 $msgTitle = ts('Sent');
589 $msgType = 'success';
590 }
591 CRM_Core_Session::setStatus($status, $msgTitle, $msgType);
592 }
593 }
594
595 /**
596 * Add activity for Email Invoice and the PDF Invoice.
597 *
598 * @param string $subject
599 * Activity subject.
600 * @param array $contactIds
601 * Contact Id.
602 * @param string $fileName
603 * Gives the location with name of the file.
604 * @param array $params
605 * For invoices.
606 *
607 */
608 static public function addActivities($subject, $contactIds, $fileName, $params) {
609 $session = CRM_Core_Session::singleton();
610 $userID = $session->get('userID');
611 $config = CRM_Core_Config::singleton();
612 $config->doNotAttachPDFReceipt = 1;
613
614 if (!empty($params['output']) && $params['output'] == 'pdf_invoice') {
615 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
616 'Downloaded Invoice',
617 'name'
618 );
619 }
620 else {
621 $activityTypeID = CRM_Core_OptionGroup::getValue('activity_type',
622 'Emailed Invoice',
623 'name'
624 );
625 }
626
627 $activityParams = array(
628 'subject' => $subject,
629 'source_contact_id' => $userID,
630 'target_contact_id' => $contactIds,
631 'activity_type_id' => $activityTypeID,
632 'activity_date_time' => date('YmdHis'),
633 'attachFile_1' => array(
634 'uri' => $fileName,
635 'type' => 'application/pdf',
636 'location' => $fileName,
637 'upload_date' => date('YmdHis'),
638 ),
639 );
640 CRM_Activity_BAO_Activity::create($activityParams);
641 }
642
643 /**
644 * Create the Invoice file in upload folder for attachment.
645 *
646 * @param string $html
647 * Content for pdf in html format.
648 *
649 * @return string
650 * Name of file which is in pdf format
651 */
652 static public function putFile($html, $name = 'Invoice.pdf') {
653 $options = new Options();
654 $options->set('isRemoteEnabled', TRUE);
655
656 $doc = new DOMPDF($options);
657 $doc->load_html($html);
658 $doc->render();
659 $html = $doc->output();
660 $config = CRM_Core_Config::singleton();
661 $fileName = $config->uploadDir . $name;
662 file_put_contents($fileName, $html);
663 return $fileName;
664 }
665
666 /**
667 * Callback to perform action on Print Invoice button.
668 */
669 public static function getPrintPDF() {
670 $contributionId = CRM_Utils_Request::retrieve('id', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
671 $contributionIDs = array($contributionId);
672 $contactId = CRM_Utils_Request::retrieve('cid', 'Positive', CRM_Core_DAO::$_nullObject, FALSE);
673 $params = array('output' => 'pdf_invoice');
674 CRM_Contribute_Form_Task_Invoice::printPDF($contributionIDs, $params, $contactId, CRM_Core_DAO::$_nullObject);
675 }
676
677 }