File manager - Edit - /home/verseaumee/ptitsanes/plugins/solidres/experience/components/com_solidres/controllers/bookform.php
Back
<?php /** ------------------------------------------------------------------------ SOLIDRES - Accommodation booking extension for Joomla ------------------------------------------------------------------------ * @author Solidres Team <contact@solidres.com> * @website https://www.solidres.com * @copyright Copyright (C) 2013 - 2019 Solidres. All Rights Reserved. * @license GNU General Public License version 3, or later ------------------------------------------------------------------------ */ defined('_JEXEC') or die; use Joomla\Registry\Registry; use Joomla\CMS\Helper\MediaHelper; class SolidresControllerBookForm extends JControllerLegacy { protected $dataContext; public function __construct(array $config = array()) { parent::__construct($config); if ($context = $this->input->get('context')) { $this->dataContext = $context; } else { $this->dataContext = 'com_solidres.bookform.data'; if ($moduleId = $this->input->get('moduleId', 0, 'uint')) { $db = \JFactory::getDbo(); $query = $db->getQuery(true) ->select('COUNT(*)') ->from($db->quoteName('#__modules')) ->where($db->quoteName('id') . ' = ' . (int) $moduleId) ->where($db->quoteName('published') . ' = 1') ->where($db->quoteName('client_id') . ' = 0') ->where($db->quoteName('module') . ' = ' . $db->quote('mod_sr_experience_bookform')); if ($db->setQuery($query)->loadResult()) { $this->dataContext .= $moduleId; } } } } public function currencyFormat() { JLoader::import('solidres.currency.currency'); $price = (float) $this->input->getFloat('price', 0.00); echo SRExperienceHelper::priceFormat($price); JFactory::getApplication()->close(); } protected function calculateDeposit(&$summary) { $depositAmount = 0.00; $depositArray = $summary['depositArray']; if (isset($depositArray['required']) && $depositArray['required'] && (float) $depositArray['amount'] > 0.00 ) { $amount = $summary['grandTotal'] - $summary['discounts']; if ($depositArray['percentage']) { if (empty($depositArray['includeExtraCost'])) { $amount -= ($summary['extraCost'] + $summary['extraTax']); } $depositAmount = ((float) $depositArray['amount'] * $amount) / 100; } else { $depositAmount = (float) $depositArray['amount']; if (!empty($depositArray['includeExtraCost'])) { $depositAmount += ($summary['extraCost'] + $summary['extraTax']); } } } $summary['depositAmount'] = $depositAmount; } public function processData() { $app = JFactory::getApplication(); $isAjax = $app->input->get('isAjax'); $data = $app->input->get('jform', array(), 'array'); try { $bookData = $app->getUserState($this->dataContext, array()); if (!isset($data['participants'])) { $data['participants'] = 0; } if (!isset($data['use_children_price'])) { $data['use_children_price'] = 0; } if (!SRExperienceHelper::validateDate($data['date'], (int) $data['experience_id'])) { throw new RuntimeException(JText::_('SR_DATE_INVALID')); } $item = SRExperienceHelper::getItem($data['experience_id']); $taxRate = is_float($item->tax_rate) ? (float) $item->tax_rate : 0.00; $participants = (int) $data['participants']; $childBasePrice = isset($item->pricing['children']['base']) ? (float) $item->pricing['children']['base'] : 0.00; $solidresConfig = JComponentHelper::getParams('com_solidres'); $showPriceWithTaxes = $solidresConfig->get('show_price_with_tax'); $discountPreTaxes = $solidresConfig->get('discount_pre_tax'); $childrenPriceDisplay = array(); if (!empty($item->tariffs[$data['date']]['adults'])) { $adultCombinePrice = null; foreach ($item->tariffs[$data['date']]['adults'] as $adultPrice) { if ($participants >= (int) $adultPrice['quantity']) { $adultPriceDisplay = (float) $adultPrice['price']; $adultCombinePrice = $adultPriceDisplay * $participants; } } } if (!empty($item->tariffs[$data['date']]['children'])) { $childrenPrice = array( 'children' => array('base' => $childBasePrice), ); foreach ($item->tariffs[$data['date']]['children'] as $childPrice) { $childrenPrice['children']['extra'][$childPrice['from'] . '_' . $childPrice['to']][$childPrice['quantity']] = $childPrice['price']; } $item->pricing = array_merge($item->pricing, $childrenPrice); } $subTotal = isset($adultCombinePrice) ? $adultCombinePrice : SRExperienceHelper::getPrice($item->pricing_base, $item->pricing, $participants); if (!isset($adultPriceDisplay)) { $adultPriceDisplay = SRExperienceHelper::getPrice($item->pricing_base, $item->pricing, $participants) / $participants; } if ($showPriceWithTaxes) { $adultPriceDisplay += $taxRate * $adultPriceDisplay; } $summary = array( 'adults' => array( 'quantity' => (int) $data['participants'], 'subTotal' => $subTotal, ), 'children' => array(), 'childrenQuantity' => 0, 'childrenSubTotal' => 0.00, 'extraCost' => 0.00, 'extraTax' => 0.00, 'appliedDiscountsAmount' => 0.00, 'discounts' => 0.00, 'depositAmount' => 0.00, 'surchargeAmount' => 0.00, 'supplementAmount' => 0.00, 'paymentDiscount' => 0.00, 'taxes' => $taxRate * $subTotal, 'subTotal' => $subTotal, 'grandTotal' => $subTotal, 'depositArray' => array( 'required' => $item->deposit_required, 'percentage' => $item->deposit_is_percentage, 'includeExtraCost' => $item->deposit_incl_extra_cost, 'amount' => (float) $item->deposit_amount, ), ); // Discount $appliedDiscounts = []; if (SRPlugin::isEnabled('discount')) { $app->triggerEvent('onSolidresExperienceCalculateDiscount', [$item, $data, &$appliedDiscounts]); } $data['appliedDiscounts'] = $appliedDiscounts; $data['summary'] = &$summary; if ($data['use_children_price'] && !empty($data['children_price'])) { $basePrice = (float) $item->pricing['children']['base']; $maxParticipant = (int) $item->max_participant; foreach ($data['children_price'] as $range => $quantity) { while ($quantity + $data['participants'] > $maxParticipant) { $quantity--; } if ($quantity > 0) { $data['children_price'][$range] = $quantity; if (isset($item->pricing['children']['extra'][$range])) { foreach ($item->pricing['children']['extra'][$range] as $qty => $price) { if ($quantity >= (int) $qty) { $basePrice = (float) $price; } } } $base = $basePrice * $quantity; $summary['taxes'] += $base * $taxRate; $summary['subTotal'] += $base; $summary['grandTotal'] += $base; $summary['childrenSubTotal'] += $base; $summary['childrenQuantity'] += $quantity; $summary['children'][$range] = array( 'quantity' => $quantity, 'subTotal' => $base, ); if ($showPriceWithTaxes) { $childrenPriceDisplay[$range] = SRExperienceHelper::priceFormat($basePrice + ($basePrice * $taxRate)); } else { $childrenPriceDisplay[$range] = SRExperienceHelper::priceFormat($basePrice); } } else { unset($data['children_price'][$range]); } } } $data['extrasOrigin'] = array(); if (!empty($item->extras)) { SRLayoutHelper::addIncludePath(SRPlugin::getPluginPath('experience') . '/layouts'); if (SRPlugin::isEnabled('advancedextra')) { JPluginHelper::importPlugin('solidres', 'advancedextra'); $app->triggerEvent('onSolidresExpExtraPrepare', array($item, $data)); } foreach ($item->extras as $extra) { $extra->taxes = is_float($extra->tax_rate) ? ((float) $extra->price * $extra->tax_rate) : 0.00; $data['extrasOrigin'][$extra->id] = $extra; } } if (empty($data['extras'])) { $data['extras'] = array(); } if (isset($bookData['extrasCalculated'])) { unset($bookData['extrasCalculated']); } if ($data['extras'] && !empty($data['extrasOrigin'])) { $data['extrasCalculated'] = array(); foreach ($data['extras'] as $id => $extraArray) { if (!isset($data['extrasOrigin'][$id]) || (!isset($extraArray['use']) && $data['extrasOrigin'][$id]->mandatory)) { throw new RuntimeException(JText::sprintf('SR_EXP_EXTRA_ERR_EXTRA_REQUIRED_FORMAT', $data['extrasOrigin'][$id]->name)); } if (empty($extraArray['use'])) { unset($data['extras'][$id]); continue; } $extra = $data['extrasOrigin'][$id]; $quantity = (int) @$extraArray['quantity']; if ($quantity < 1 || $quantity > (int) $extra->max_quantity) { throw new RuntimeException(JText::sprintf('SR_EXP_EXTRA_ERR_INVALID_QUANTITY_FORMAT', $extra->name)); } if ($extra->price > 0.00) { $summary['extraCost'] += ($extra->price * $quantity); } if ($extra->taxes > 0.00) { $summary['extraTax'] += ($extra->taxes * $quantity); } $data['extrasCalculated'][$id] = array( 'id' => $id, 'name' => $extra->name, 'description' => isset($extra->extraDesc) ? trim(json_encode($extra->extraDesc)) : '', 'quantity' => $quantity, 'price' => $extra->price, 'taxes' => $extra->taxes, ); } } if ($summary['adults']['quantity'] === 1 && empty($summary['children']) && !empty($item->params['enable_single_supplement']) && !empty($item->params['single_supplement_value']) ) { $supplement = (float) $item->params['single_supplement_value']; if (empty($item->params['single_supplement_is_percent'])) { $summary['supplementAmount'] = $supplement; } else { $summary['supplementAmount'] = ($subTotal * $supplement) / 100; } if ($summary['supplementAmount'] > 0.00) { $summary['taxes'] += $taxRate * $summary['supplementAmount']; } } $summary['grandTotal'] += $summary['taxes'] + $summary['extraCost'] + $summary['extraTax'] + $summary['supplementAmount']; foreach ($data['extrasOrigin'] as $id => $extra) { $data['extrasOrigin'][$id]->detailBox = SRLayoutHelper::render('experience.bookform.extra', array( 'extra' => $extra, 'summary' => $summary, 'calculated' => isset($data['extrasCalculated'][$id]) ? $data['extrasCalculated'][$id] : null, )); } $this->calculateDeposit($summary); $discountAmount = 0.00; $grandTotalForDiscount = $summary['grandTotal']; if ($discountPreTaxes) { $grandTotalForDiscount -= ($summary['taxes'] + $summary['extraTax']); } if (!empty($data['appliedDiscounts'])) { foreach ($data['appliedDiscounts'] as $appliedDiscount) { $value = (float) $appliedDiscount->value; if ($appliedDiscount->is_percent) { $appliedDiscount->amount = ($grandTotalForDiscount * $value) / 100; } else { $appliedDiscount->amount = $value; } $grandTotalForDiscount -= $appliedDiscount->amount; $discountAmount += $appliedDiscount->amount; } $summary['appliedDiscountsAmount'] = $discountAmount; // Keep when apply the coupon $summary['discounts'] = $discountAmount; // Real discount amount } $data = array_merge($bookData, $data); $app->setUserState($this->dataContext, $data); $minParticipants = (int) $item->min_participant; $maxParticipants = (int) $item->max_participant; $totalParticipants = $participants + $summary['childrenQuantity']; if ($totalParticipants < $minParticipants || $totalParticipants > $maxParticipants) { throw new RuntimeException(JText::sprintf('SR_EXP_ERR_INVALID_SCALE_WARNING_FORMAT', $minParticipants, $maxParticipants)); } $response = array( 'showChildPriceDisplay' => count($childrenPriceDisplay) > 0, 'adultPriceDisplay' => SRExperienceHelper::priceFormat($adultPriceDisplay) . ' <small>' . JText::_('SR_EXP_PRICE_X_ADULT') . '</small>', 'childPriceDisplay' => SRLayoutHelper::render('experience.bookform.pricing', array( 'childrenPrice' => $childrenPriceDisplay, )), 'formHtml' => SRLayoutHelper::render('experience.bookform.form', array( 'bookData' => $data, 'item' => $item, )), 'discountAmount' => $discountAmount, ); if (!empty($summary['supplementAmount'])) { $supplementAmount = $summary['supplementAmount']; if ($supplementAmount > 0.00 && $showPriceWithTaxes) { $supplementAmount += ($taxRate * $supplementAmount); } $response['supplementAmountFormatted'] = JText::sprintf('SR_EXP_SUPPLEMENT_' . ($supplementAmount > 0.00 ? 'ADD' : 'SUB') . '_FORMAT', SRExperienceHelper::priceFormat($supplementAmount)); } if ($showPriceWithTaxes) { $response['originTotalFormat'] = SRExperienceHelper::priceFormat($summary['grandTotal']); $response['totalFormat'] = SRExperienceHelper::priceFormat($summary['grandTotal'] - $discountAmount); } else { $response['originTotalFormat'] = SRExperienceHelper::priceFormat($summary['subTotal'] + $summary['extraCost'] + $summary['supplementAmount']); $response['totalFormat'] = SRExperienceHelper::priceFormat($summary['subTotal'] + $summary['extraCost'] + $summary['supplementAmount'] - $discountAmount); } } catch (RuntimeException $e) { $response = $e; } if ($isAjax) { echo new JResponseJson($response); $app->close(); } if ($response instanceof RuntimeException) { $app->enqueueMessage($response->getMessage(), 'warning'); $redirect = base64_decode($app->input->getBase64('return')); if (!$redirect || !JUri::isInternal($redirect)) { $redirect = JUri::root(); } $app->redirect($redirect); } $app->redirect(JRoute::_('index.php?option=com_solidres&view=bookform&context=' . base64_encode($this->dataContext), false)); } public function process() { SRExperienceHelper::checkSubmitToken(); JModelLegacy::addIncludePath(SRPlugin::getSitePath('experience') . '/models', 'SolidresModel'); /** * @var $app JApplicationCms * @var $model SolidresModelBookForm */ $app = JFactory::getApplication(); $model = JModelLegacy::getInstance('BookForm', 'SolidresModel', array('ignore_request' => true)); $data = $this->input->get('jform', array(), 'array'); $form = $model->getForm($data, false); $return = base64_decode($this->input->getBase64('return')); if (!JUri::isInternal($return)) { $return = JRoute::_('index.php?option=com_solidres&view=bookform', false); } if (!$form) { $this->setRedirect($return, $model->getError(), 'error'); return false; } if ($files = $app->input->files->get('jform', [], 'array')) { JLoader::register('Joomla\\CMS\\Helper\\MediaHelper', JPATH_LIBRARIES . '/src/Helper/MediaHelper.php'); $mediaHelper = new MediaHelper; $countFiles = 0; foreach ($files as $name => $file) { if (empty($file['tmp_name'])) { continue; } $countFiles++; if (!isset($data[$name])) { if ($file['error'] == 1 || !$mediaHelper->canUpload($file, 'com_media') ) { $app->redirect($return); } $data[$name] = $file; } } if ($countFiles) { $contentLength = (int) $_SERVER['CONTENT_LENGTH']; $postMaxSize = $mediaHelper->toBytes(ini_get('post_max_size')); $memoryLimit = $mediaHelper->toBytes(ini_get('memory_limit')); if (($postMaxSize > 0 && $contentLength > $postMaxSize) || ($memoryLimit != -1 && $contentLength > $memoryLimit)) { $app->enqueueMessage(JText::_('SR_ERROR_WARN_FILE_TOO_LARGE'), 'error'); $app->redirect($return); } } } $userStateData = (array) $app->getUserState($this->dataContext, array()); $data = array_merge($userStateData, $data); $validData = $model->validate($form, $data); if ($validData === false) { // Get the validation messages. $errors = $model->getErrors(); // Push up to three validation messages out to the user. for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) { if ($errors[$i] instanceof Exception) { $app->enqueueMessage($errors[$i]->getMessage(), 'warning'); } else { $app->enqueueMessage($errors[$i], 'warning'); } } // Save the data in the session. $app->setUserState($this->dataContext, $data); // Redirect back to the edit screen. $this->setRedirect($return); return false; } $item = SRExperienceHelper::getItem($data['experience_id']); $timeSlots = SRExperienceHelper::parseTimeSlots($item->timeslots, false); $timeSlotId = isset($data['timeSlotId']) ? (int) $data['timeSlotId'] : 0; $validData['participants'] = (int) $data['participants'] + (int) $data['summary']['childrenQuantity']; $mustConfirm = !empty($item->params['exp_toc_article']) || !empty($item->params['exp_privacy_article']); if ($mustConfirm && empty($data['confirm_terms_and_conditions'])) { if (!empty($item->params['exp_toc_article']) && !empty($item->params['exp_privacy_article'])) { $message = JText::sprintf('SR_EXP_WARNING_CONFIRM_MESSAGE', JText::_('SR_EXP_TOC_N_PRIVACY')); } elseif (!empty($item->params['exp_toc_article'])) { $message = JText::sprintf('SR_EXP_WARNING_CONFIRM_MESSAGE', JText::_('SR_EXP_TOC_LABEL')); } else { $message = JText::sprintf('SR_EXP_WARNING_CONFIRM_MESSAGE', JText::_('SR_EXP_PRIVACY_POLICY')); } $app->enqueueMessage($message, 'warning'); $app->redirect($return); } if ($timeSlots) { if ($timeSlotId > 0 && isset($timeSlots[$timeSlotId]) && (int) $timeSlots[$timeSlotId]->guide_state === 1 ) { $timeSlot = $timeSlots[$timeSlotId]; $key = $validData['date'] . ':' . $timeSlot->guide_id . ':' . $timeSlot->from . ':' . $timeSlot->to . ':' . $timeSlot->w_day; if (isset($timeSlot->guideAvailableSizes[$key])) { $timeValid = (!$item->is_private && $timeSlot->guideAvailableSizes[$key]['experienceId'] == $data['experience_id'] && $timeSlot->guideAvailableSizes[$key]['slots'] >= $validData['participants']); } else { $timeValid = true; } if ($timeValid) { $validData['time_slot_id'] = $timeSlotId; $validData['guide_id'] = (int) $timeSlot->guide_id; $validData['guide_name'] = $timeSlot->guide_name; $validData['time_slot_from'] = $timeSlot->from; $validData['time_slot_to'] = $timeSlot->to; $validData['time_slot_w_day'] = $timeSlot->w_day; } } else { $timeValid = false; } if (!$timeValid) { $app->setUserState($this->dataContext, $data); $app->enqueueMessage(JText::_('SR_ERR_EMPTY_TOUR_TIME'), 'error'); $app->redirect($item->link); return false; } } elseif (isset($item->available_sizes[$validData['date']]) && ($item->is_private || (int) $item->available_sizes[$validData['date']] < (int) $validData['participants']) ) { $this->setRedirect($return, JText::_('SR_DATE_INVALID'), 'error'); return false; } $validData = array_merge($userStateData, $validData); // Coupon if (!empty ($validData['coupons'])) { foreach ($validData['coupons'] as $code => $coupon) { if ($coupon['applied']) { $validData['coupon_code'] = $code; $validData['coupon_id'] = (int) $coupon['id']; $validData['coupon_amount'] = (float) $coupon['amount']; break; } } } if ($item->disable_registration) { $validData['register'] = false; } if (!empty($item->params['collect_guest_info']) && !empty($data['guests'])) { $validData['guests'] = $data['guests']; } $payments = SRExperienceHelper::getPayments($validData['experience_id'], $validData); if (!empty($payments) && isset($validData['payment_method_id']) && !isset($payments[$validData['payment_method_id']]) ) { $app->setUserState($this->dataContext, $validData); $this->setRedirect($return, JText::_('SR_EXPERIENCE_ERROR_NO_PAYMENT'), 'error'); return false; } $payment = null; $handler = null; if (isset($payments[$validData['payment_method_id']])) { $payment = $payments[$validData['payment_method_id']]; $class = 'PlgExperiencePayment' . ucfirst($payment->element); $handler = call_user_func(array($class, 'getHandler'), $payment->element); } $returnError = function ($message) use ($app, $validData, $return) { // Save the data in the session. $app->setUserState($this->dataContext, $validData); // Redirect back to the edit screen. $app->enqueueMessage($message, 'error'); $app->redirect($return); return false; }; if ($handler instanceof SRExpPayment) { try { if (is_callable(array($handler, 'validate')) && !$handler->validate($payment)) { return $returnError(JText::_('SR_EXP_PAYMENT_VALIDATE_FAIL')); } } catch (Exception $e) { return $returnError($e->getMessage()); } $payment->card['data'] = isset($data[$payment->element]) ? $data[$payment->element] : array(); } foreach ($model->getCustomFields() as $field) { if ($field->field_name === 'customer_email2' && (empty($validData['customer_email2']) || $validData['customer_email2'] !== $validData['customer_email']) ) { return $returnError(JText::_('SR_EXP_EMAIL_NOT_MATCH_MESSAGE')); } } $validData['privacyConsent'] = empty($data['privacyConsent']) ? false : true; $app->triggerEvent('onSolidresExperienceReservationBeforeSave', array($payment, &$validData)); $saveTableData = $model->save($validData); if ($saveTableData === false) { return $returnError(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $model->getError())); } $formBuffer = ''; if ($handler instanceof SRExpPayment) { try { if (is_callable(array($handler, 'finished'))) { $formBuffer = call_user_func_array(array($handler, 'finished'), array($saveTableData, $payment)); } else { /** @deprecated 1.0.0 onSolidresExperiencePaymentPrepareForm Use finished method instead */ $formBuffer = call_user_func_array(array($handler, 'onSolidresExperiencePaymentPrepareForm'), array($saveTableData, $payment)); } } catch (Exception $e) { $app->enqueueMessage($e->getMessage(), 'warning'); } } $app->triggerEvent('onSolidresExperienceReservationAfterSave', [$saveTableData, $payment, &$formBuffer]); if (empty($formBuffer)) { $message = JText::_('SR_EXP_DEFAULT_SUCCESS_MESSAGE'); $formBuffer = SRExpPayment::parseReplaceMessage($saveTableData, $message); } SRExperienceHelper::setPaymentFormData($formBuffer); $app->redirect($return); } public function paymentCallback() { $app = JFactory::getApplication(); $reservationId = (int) $app->input->getUint('reservation_id'); if ($reservationId > 0) { JTable::addIncludePath(SRPlugin::getAdminPath('experience') . '/tables'); $reservationTable = JTable::getInstance('ExpReservation', 'SolidresTable'); if ($reservationTable->load($reservationId)) { $payments = SRExperienceHelper::getPayments($reservationTable->experience_id); $paymentId = $reservationTable->payment_method_id; if (isset($payments[$paymentId])) { JPluginHelper::importPlugin('experiencepayment', $payments[$paymentId]->element); $app->triggerEvent('onSolidresExperiencePaymentCallBack', array($reservationTable, $payments[$paymentId])); } } } $app->close(); } public function requestBooking() { JSession::checkToken('get') or jexit(JText::_('JINVALID_TOKEN')); $app = JFactory::getApplication(); $response = array( 'status' => 'error', 'message' => 'The system send email is disabled', ); try { JTable::addIncludePath(SRPlugin::getAdminPath('experience') . '/tables'); $expTable = JTable::getInstance('Experience', 'SolidresTable'); $experienceId = (int) $this->input->getUint('experienceId'); if ($experienceId > 0 && $expTable->load($experienceId)) { $name = $this->input->getString('fullname'); $phone = $this->input->getString('phone'); $email = $this->input->getString('email'); $message = $this->input->getString('message'); $params = new Registry($expTable->params); if (!$params->get('show_inquiry_form')) { throw new Exception('The inquiry form was disabled for this experience.'); } if ($params->get('use_captcha')) { JPluginHelper::importPlugin('captcha', 'recaptcha'); $results = $app->triggerEvent('onCheckAnswer'); if (in_array(false, $results, true)) { throw new Exception('Invalid captcha'); } } $recipients = array(); if ($expTable->get('contact_email') && filter_var($expTable->get('contact_email'), FILTER_VALIDATE_EMAIL)) { $recipients[] = $expTable->get('contact_email'); } if (empty($recipients)) { throw new Exception('Recipients not found.'); } $mailer = JFactory::getMailer(); $mailer->setSender(array( $app->get('mailfrom'), $app->get('fromname') )); $mailer->addRecipient($recipients); $mailer->isHtml(false); $mailer->setSubject(JText::plural('SR_EXP_INQUIRY_FORM_SEND_MAIL_SUBJECT', strtoupper($name), strtoupper($expTable->name))); $body = $params->get('email_content_format'); if (empty($body)) { $body = 'Hi, You have a new booking inquiry for ' . ucfirst($expTable->name) . ' via ' . $app->get('sitename') . ': Name: ' . $name . ' Email: ' . $email . ' Phone: ' . $phone . ' Message: ' . $message . ' Cheers,'; } else { $body = str_replace( array('{site_name}', '{tour_name}', '{name}', '{phone}', '{email}', '{message}'), array($app->get('sitename'), ucfirst($expTable->name), $name, $phone, $email, $message), $body ); } $mailer->setBody($body); if ($mailer->send()) { $response = array( 'status' => 'success', 'message' => JText::_('SR_EXP_INQUIRY_FORM_SEND_MAIL_SUCCESS_MESSAGE') ); } } } catch (Exception $e) { $response = array( 'status' => 'error', 'message' => $e->getMessage() ); } echo json_encode($response); $app->close(); } public function loadAvailableDates() { try { $experience = SRExperienceHelper::getItem($this->input->get('experienceId', 0, 'uint')); if (empty($experience->id)) { throw new RuntimeException(JText::_('SR_ITEMS_NOT_FOUND')); } SRLayoutHelper::addIncludePath(SRPlugin::getPluginPath('experience') . '/layouts'); $response = SRLayoutHelper::render('experience.bookform.available', array( 'experience' => $experience, )); } catch (Exception $e) { $response = new RuntimeException($e->getMessage()); } echo new JResponseJson($response); JFactory::getApplication()->close(); } public function checkCoupon() { $app = JFactory::getApplication(); $data = $app->getUserState($this->dataContext, array()); try { $code = $app->input->get('code', '', 'TRIM'); $itemId = $app->input->get('experienceId', 0, 'UINT'); if (!isset($data['coupons'])) { $data['coupons'] = array(); } $adminPath = SRPlugin::getAdminPath('experience'); JModelLegacy::addIncludePath($adminPath . '/models', 'SolidresModel'); JTable::addIncludePath($adminPath . '/tables'); $model = JModelLegacy::getInstance('ExpCoupon', 'SolidresModel', array('ignore_request' => true)); $table = JTable::getInstance('Experience', 'SolidresTable'); $coupon = $model->getItem(array('coupon_code' => $code, 'scope' => 1, 'state' => 1)); if (!$itemId || !$table->load($itemId)) { throw new RuntimeException(JText::_('SR_ERROR_TOUR_NOT_FOUND')); } $params = new \Joomla\Registry\Registry($table->params); $userId = (int) JFactory::getUser()->id; $userGroup = $coupon->customer_group_id ?: 0; $accessGroup = true; if ($userGroup) { if ($userId > 0) { if (SRPlugin::isEnabled('user')) { JTable::addIncludePath(SRPlugin::getAdminPath('user') . '/tables'); $customerTable = JTable::getInstance('Customer', 'SolidresTable'); if ($customerTable->load(array('user_id' => $userId))) { $accessGroup = ($customerTable->customer_group_id == $userGroup); } else { $accessGroup = false; } } } else { $accessGroup = false; } } $bookDate = strtotime($data['date']); $nowDate = strtotime(JFactory::getDate('now')->toSql()); $response = array('refresh' => false); if (!$params->get('enable_coupon', 1) || (!empty($coupon->experience_ids) && !in_array($itemId, (array) $coupon->experience_ids)) || $nowDate < strtotime($coupon->valid_from) || $nowDate > strtotime($coupon->valid_to) || (!empty($coupon->valid_from_checkin) && $bookDate < strtotime($coupon->valid_from_checkin)) || (!empty($coupon->valid_to_checkin) && $bookDate > strtotime($coupon->valid_to_checkin)) || (is_numeric($coupon->quantity) && (int) $coupon->quantity < 1) || !$accessGroup ) { $response['valid'] = false; $response['message'] = JText::_('SR_COUPON_REJECTED'); if (isset($data['coupons'][$code])) { unset($data['coupons'][$code]); $response['refresh'] = true; } } else { $response['valid'] = true; $response['message'] = JText::_('SR_COUPON_ACCEPTED'); $data['coupons'][$code] = array( 'id' => $coupon->id, 'amount' => (float) $coupon->amount, 'percentage' => (bool) $coupon->is_percent, 'applied' => false, ); } } catch (RuntimeException $e) { $response = $e; } $app->setUserState($this->dataContext, $data); echo new JResponseJson($response); $app->close(); } public function applyCoupon($redirect = true) { $app = JFactory::getApplication(); $data = $app->getUserState($this->dataContext, array()); $discounts = isset($data['summary']['appliedDiscountsAmount']) ? $data['summary']['appliedDiscountsAmount'] : 0.00; if (!isset($data['coupons'])) { $data['coupons'] = array(); } $grandTotal = isset($data['summary']['grandTotal']) ? $data['summary']['grandTotal'] : 0.00; $code = $app->input->get('code', '', 'TRIM'); $return = base64_decode($app->input->getBase64('return', base64_encode(JUri::root()))); foreach ($data['coupons'] as $c => $coupon) { if ($c == $code) { $data['coupons'][$c]['applied'] = true; $app->enqueueMessage(JText::sprintf('SR_EXP_COUPON_APPLIED_FORMAT', $code)); } else { $data['coupons'][$c]['applied'] = false; } if ($data['coupons'][$c]['applied']) { if ($coupon['percentage']) { $discounts += ($coupon['amount'] * $grandTotal) / 100; } else { $discounts += $coupon['amount']; } } } $data['summary']['discounts'] = $discounts; $this->calculateDeposit($data['summary']); $app->setUserState($this->dataContext, $data); if ($redirect) { $app->redirect($return); } } public function removeCoupon() { $app = JFactory::getApplication(); $data = $app->getUserState($this->dataContext, array()); if (!isset($data['coupons'])) { $data['coupons'] = array(); } $grandTotal = isset($data['summary']['grandTotal']) ? $data['summary']['grandTotal'] : 0.00; $discounts = isset($data['summary']['discounts']) ? $data['summary']['discounts'] : 0.00; $code = $app->input->get('code', '', 'TRIM'); $return = base64_decode($app->input->getBase64('return', JRoute::_('index.php'))); foreach ($data['coupons'] as $c => $coupon) { if ($c == $code) { if ($coupon['percentage']) { $discounts -= ($coupon['amount'] * $grandTotal) / 100; } else { $discounts -= $coupon['amount']; } if ($discounts < 0.00) { $discounts = 0.00; } unset($data['coupons'][$c]); $app->enqueueMessage(JText::sprintf('SR_EXP_COUPON_REMOVED_FORMAT', $code)); break; } } $data['summary']['discounts'] = $discounts; $this->calculateDeposit($data['summary']); $app->setUserState($this->dataContext, $data); $app->redirect($return); } public function loadPaymentSurcharge() { $app = JFactory::getApplication(); $paymentIdMethod = (int) $app->input->get('paymentMethodId', 0, 'uint'); $configScopeId = (int) $app->input->get('configScopeId', 0, 'uint'); $data = $app->getUserState($this->dataContext, []); try { $payment = SRExperienceHelper::getPayment($paymentIdMethod, $configScopeId); if (!$payment) { throw new RuntimeException('Payment ID: ' . $paymentIdMethod . ' not exists.'); } $item = SRExperienceHelper::getItem($configScopeId); if (!$item) { throw new RuntimeException('Experience ID: ' . $configScopeId . ' not exists.'); } if ($data['summary']['depositAmount'] > 0.00) { $amount = $data['summary']['depositAmount']; } else { $amount = $data['summary']['grandTotal']; } $baseRateValue = (float) $payment->params->get('base_rate_value', 0); $paymentDiscount = 0.00; $surchargeAmount = 0.00; switch ((int) $payment->params->get('base_rate', 0)) { case 1: $surchargeAmount = $baseRateValue; break; case 2: $paymentDiscount = $baseRateValue; break; case 3: $surchargeAmount = ($baseRateValue * $amount) / 100; break; case 4: $paymentDiscount = ($baseRateValue * $amount) / 100; break; } $response = array( 'paymentName' => $payment->label, 'surchargeAmount' => $surchargeAmount, 'paymentDiscount' => $paymentDiscount, ); if (!isset($data['summary'])) { $data['summary'] = array(); } $data['summary'] = array_merge($data['summary'], $response); $app->setUserState($this->dataContext, $data); SRLayoutHelper::addIncludePath(SRPlugin::getPluginPath('experience') . '/layouts'); $response['surchargeAmountFormat'] = SRExperienceHelper::priceFormat($surchargeAmount); $response['paymentDiscountFormat'] = SRExperienceHelper::priceFormat($paymentDiscount); $response['summaryHTML'] = SRLayoutHelper::render('experience.bookform.summary', array( 'data' => $data, 'item' => $item, )); } catch (RuntimeException $e) { $response = $e; } echo new JResponseJson($response); $app->close(); } }
| ver. 1.4 |
Github
|
.
| PHP 8.5.7 | Generation time: 0 |
proxy
|
phpinfo
|
Settings