Esempio n. 1
0
 function display($tpl = null)
 {
     $this->context = 'com_solidres.reservation.process';
     $this->config = JComponentHelper::getParams('com_solidres');
     $this->showPoweredByLink = $this->config->get('show_solidres_copyright', '1');
     if ($this->_layout == 'default') {
         $model = $this->getModel();
         $modelName = $model->getName();
         $this->reservation = $model->getItem();
         $this->app = JFactory::getApplication();
         $this->checkin = $model->getState($modelName . '.checkin');
         $this->checkout = $model->getState($modelName . '.checkout');
         $this->totalReservedRoom = $model->getState($modelName . '.totalReservedRoom');
         $this->countries = SolidresHelper::getCountryOptions();
         $this->geoStates = SolidresHelper::getGeoStateOptions($model->getState($modelName . '.countryId'));
         $this->userState = $this->app->getUserState($this->context);
         $this->raid = $model->getState($modelName . '.reservationAssetId');
         $this->uri = JURI::getInstance()->__toString();
         $this->roomTypeObj = SRFactory::get('solidres.roomtype.roomtype');
         $this->numberOfNights = $this->roomTypeObj->calculateDateDiff($this->checkin, $this->checkout);
         JHtml::_('jquery.framework');
     }
     JHtml::stylesheet('com_solidres/assets/main.css', false, true, false);
     if (count($errors = $this->get('Errors'))) {
         JError::raiseError(500, implode("\n", $errors));
         return false;
     }
     parent::display($tpl);
 }
Esempio n. 2
0
 /**
  * Overloaded bind function to pre-process the params.
  *
  * @param	array		$array Named array
  * @param   string 		$ignore
  * @return	null|string	null is operation was satisfactory, otherwise returns an error
  * @see		JTable:bind
  * @since	1.5
  */
 public function bind($array, $ignore = '')
 {
     if (isset($array['params']) && is_array($array['params'])) {
         $registry = new JRegistry();
         $registry->loadArray($array['params']);
         $array['params'] = (string) $registry;
     }
     if (isset($array['metadata']) && is_array($array['metadata'])) {
         $registry = new JRegistry();
         $registry->loadArray($array['metadata']);
         $array['metadata'] = (string) $registry;
     }
     if (!isset($array['lat']) && !isset($array['lng'])) {
         $options = array(0 => $array['address_1'], 1 => $array['city'], 2 => isset($array['geo_state_id']) ? $array['geo_state_id'] : null, 3 => $array['country_id']);
         $coords = SRFactory::getGeoCoder($options)->process();
         if (is_array($coords)) {
             $array['lat'] = $coords['lat'];
             $array['lng'] = $coords['lng'];
         }
     }
     // Bind the rules.
     if (isset($array['rules']) && is_array($array['rules'])) {
         $rules = new JAccessRules($array['rules']);
         $this->setRules($rules);
     }
     return parent::bind($array, $ignore);
 }
Esempio n. 3
0
 public function display($tpl = null)
 {
     $model = $this->getModel();
     $xmlContent = $model->backupAssets();
     $sqlContent = $model->backupSql();
     $version = JFactory::getDate()->toUnix();
     $xmlFilePath = JFactory::getConfig()->get('tmp_path') . '/' . 'xml-' . $version . '.xml';
     $sqlFilePath = JFactory::getConfig()->get('tmp_path') . '/' . 'sql-' . $version . '.sql';
     JFile::write($xmlFilePath, $xmlContent);
     JFile::write($sqlFilePath, $sqlContent);
     $fileDownloadName = 'solidres' . $version . '.zip';
     SRFactory::get('solidres.utilities.ziparchive')->zipFiles(array($xmlFilePath, $sqlFilePath), JFactory::getConfig()->get('tmp_path') . '/' . $fileDownloadName);
     JFile::delete($xmlFilePath);
     JFile::delete($sqlFilePath);
     //make file to download
     header('Content-Type: application/zip');
     header('Content-Disposition: attachment; filename="' . $fileDownloadName);
     header("Content-Transfer-Encoding: binary");
     header('Accept-Ranges: bytes');
     header("Cache-control: private");
     header('Pragma: private');
     header("Expires: " . JFactory::getDate()->toSql());
     header("Content-Length: " . filesize(JFactory::getConfig()->get('tmp_path') . '/' . $fileDownloadName));
     ob_clean();
     flush();
     readfile(JFactory::getConfig()->get('tmp_path') . '/' . $fileDownloadName);
     JFile::delete(JFactory::getConfig()->get('tmp_path') . '/' . $fileDownloadName);
 }
Esempio n. 4
0
 /**
  * Overload the store method
  *
  * @param	boolean	$updateNulls Toggle whether null values should be updated.
  * @return	boolean	True on success, false on failure.
  * @since	1.6
  */
 public function store($updateNulls = false)
 {
     $date = JFactory::getDate();
     $user = JFactory::getUser();
     if ($this->id) {
         $this->modified_date = $date->toSql();
         $this->modified_by = $user->get('id');
     } else {
         if (!intval($this->created_date)) {
             $this->created_date = $date->toSql();
         }
         if (empty($this->created_by)) {
             $this->created_by = $user->get('id');
         }
         $this->code = SRFactory::get('solidres.reservation.reservation')->getCode($this->created_date);
     }
     // Prepare some NULL value
     if (empty($this->coupon_id)) {
         $this->coupon_id = NULL;
     }
     if (empty($this->customer_id)) {
         $this->customer_id = NULL;
     }
     $this->checkin = JFactory::getDate($this->checkin)->toSql();
     $this->checkout = JFactory::getDate($this->checkout)->toSql();
     // Attempt to store the user data.
     return parent::store($updateNulls);
 }
Esempio n. 5
0
    /**
     * Method to get the field input markup.
     *
     * @return	string	The field input markup.
     * @since	1.6
     */
    protected function getInput()
    {
        $roomtypeId = $this->form->getValue('id', NULL, 0);
        $reservationAssetId = $this->form->getValue('reservation_asset_id');
        $html = '';
        if (!empty($reservationAssetId)) {
            $model = JModelLegacy::getInstance('Coupons', 'SolidresModel', array('ignore_request' => true));
            $model->setState('filter.reservation_asset_id', $reservationAssetId);
            $model->setState('filter.date_constraint', 1);
            $listCoupons = $model->getItems();
            $listRoomtypeCouponIds = SRFactory::get('solidres.roomtype.roomtype')->getCoupon($roomtypeId);
            if (!empty($listCoupons)) {
                foreach ($listCoupons as $couponObj) {
                    $html .= '
	            	<p class="coupons-wrapper-line">
	            		<label class="checkbox">
				    	<input type="checkbox"
								value="' . $couponObj->id . '"
								id="checkbox_coupon_id_' . $couponObj->id . '"
								class="checkbox_coupon_class"
								name="jform[coupon_id][]" ' . (in_array($couponObj->id, $listRoomtypeCouponIds) ? 'checked="checked"' : '') . '/>
							' . $couponObj->coupon_name . '
						</label>
					</p>';
                }
            } else {
                $html = JText::_('SR_COUPON_NOT_AVAILABLE_FOR_THIS_RESERVATION_ASSET');
            }
        } else {
            $html = JText::_('SR_COUPON_SELECT_RESERVATION_ASSET_FIRST');
        }
        return $html;
    }
Esempio n. 6
0
 public function show()
 {
     $model = $this->getModel();
     //$modelName = $model->getName();
     $start = $this->input->getUInt('start');
     $limit = $this->input->getUInt('limit');
     $model->setState('list.start', $start);
     $model->setState('list.limit', $limit);
     $results = $model->getItems();
     $srMedia = SRFactory::get('solidres.media.media');
     $html = '';
     if ($results) {
         $html .= '<ul class="media-container clearfix">';
         foreach ($results as $item) {
             $html .= '<li>';
             $html .= '<input class="media-checkbox" type="checkbox" name="media[]" value="' . $item->id . '" />';
             if ($srMedia->isImage($item->mime_type)) {
                 $html .= '<img id="sr_media_' . $item->id . '" title="' . $item->name . '" alt="' . $item->name . '" src="' . SRURI_MEDIA . '/assets/images/system/thumbnails/2/' . $item->value . '" />';
             } elseif ($srMedia->isDocument($item->mime_type)) {
                 $html .= '<img id="sr_media_' . $item->id . '" title="' . $item->name . '" alt="' . $item->name . '" src="' . SRURI_MEDIA . '/assets/images/document.png" />';
             } elseif ($srMedia->isVideo($item->mime_type)) {
                 $html .= '<img id="sr_media_' . $item->id . '" title="' . $item->name . '" alt="' . $item->name . '" src="' . SRURI_MEDIA . '/assets/images/video.png" />';
             }
             $html .= substr($item->name, 0, 20);
             $html .= '</li>';
         }
         $html .= '</ul>';
     }
     echo $html;
     exit;
 }
Esempio n. 7
0
 public function __construct($config = array())
 {
     $config['model_path'] = JPATH_COMPONENT_ADMINISTRATOR . '/models';
     parent::__construct($config);
     $this->couponCode = $this->input->get('coupon_code', 0, 'string');
     $this->raId = $this->input->get('raid', 0, 'int');
     $this->coupon = SRFactory::get('solidres.coupon.coupon');
     $this->jconfig = JFactory::getConfig();
     $this->tzoffset = $this->jconfig->get('offset');
     $this->reservationData = $this->getReservationData();
     $this->customerGroupId = $this->getCustomerGroupId();
     $this->currentDate = JFactory::getDate(date('Y-M-d'), $this->tzoffset)->toUnix();
     $this->checkin = JFactory::getDate(date('Y-M-d', strtotime($this->reservationData->checkin)), $this->tzoffset)->toUnix();
 }
Esempio n. 8
0
 public function save()
 {
     // Check for request forgeries.
     JSession::checkToken('POST') or jexit(JText::_('JINVALID_TOKEN'));
     $date = JFactory::getDate();
     $user = JFactory::getUser();
     $input = JFactory::getApplication()->input;
     JTable::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_solidres/tables');
     $table = JTable::getInstance('ReservationNote', 'SolidresTable');
     $data = array();
     $data['reservation_id'] = $input->getUint('reservation_id', 0);
     $data['text'] = $input->getString('text', '');
     $data['created_date'] = $date->toSql();
     $data['created_by'] = $user->get('id');
     $data['notify_customer'] = $input->getUint('notify_customer', 0);
     $data['visible_in_frontend'] = $input->getUint('visible_in_frontend', 0);
     $table->bind($data);
     $result = $table->store();
     $status = 0;
     if ($result) {
         $status = 1;
     }
     $user = JFactory::getUser($table->created_by);
     // Send email to customer if configured
     $emailSendingResult = '';
     if ($data['notify_customer'] == 1) {
         $mail = SRFactory::get('solidres.mail.mail');
         $messageTemplatePath = SRPATH_LIBRARY . '/mail/en-GB/reservation_note_customer_notify.html';
         // Query some info
         $resTable = JTable::getInstance('Reservation', 'SolidresTable');
         $raTable = JTable::getInstance('ReservationAsset', 'SolidresTable');
         $resTable->load($data['reservation_id']);
         $raTable->load($resTable->reservation_asset_id);
         if (file_exists($messageTemplatePath)) {
             $body = file_get_contents($messageTemplatePath);
         }
         $replacements[$resTable->customer_email] = array('{hotel_name}' => $raTable->name, '{hotel_url}' => $raTable->website, '{customer_firstname}' => $resTable->customer_firstname, '{customer_middlename}' => $resTable->customer_middlename, '{customer_lastname}' => $resTable->customer_lastname, '{email}' => $raTable->email, '{phone}' => $raTable->phone, '{text}' => $data['text']);
         $mail->mailFrom = array($raTable->email => $raTable->name);
         $mail->mailTo = $resTable->customer_email;
         $mail->replacements = $replacements;
         $mail->subject = JText::_('SR_RESERVATION_NOTE_FROM') . $raTable->name;
         $mail->body = $body;
         if (!$mail->send()) {
             $emailSendingResult = 'Could not send email';
         }
     }
     $response = array('status' => $status, 'message' => $emailSendingResult, 'next' => '', 'text' => $table->text, 'created_date' => $table->created_date, 'created_by_username' => $user->get('username'), 'notify_customer' => $table->notify_customer == 1 ? JText::_('JYES') : JText::_('JNO'), 'visible_in_frontend' => $table->visible_in_frontend == 1 ? JText::_('JYES') : JText::_('JNO'));
     echo json_encode($response);
 }
Esempio n. 9
0
 /**
  * Find Room that belong to a RoomType
  *
  * @return void
  */
 public function findRoom()
 {
     $roomTypeId = JFactory::getApplication()->input->get('id', 0, 'int');
     $result = SRFactory::get('solidres.roomtype.roomtype')->getListRooms($roomTypeId);
     $i = 0;
     $json = array();
     if (!empty($result)) {
         foreach ($result as $rs) {
             $json[$i]['id'] = $rs->id;
             $json[$i]['name'] = $rs->label;
             $i++;
         }
     }
     echo json_encode($json);
     die(1);
 }
Esempio n. 10
0
 public function display($tpl = null)
 {
     $this->state = $this->get('State');
     $this->item = $this->get('Item');
     $this->form = $this->get('Form');
     $this->customerGroups = SRFactory::getUserHelper()->getUserGroups();
     $doc = JFactory::getDocument();
     $this->customerGroupOptions = SolidresHelper::getCustomerGroupOptions();
     JText::script('SUN');
     JText::script('MON');
     JText::script('TUE');
     JText::script('WED');
     JText::script('THU');
     JText::script('FRI');
     JText::script('SAT');
     $params = JComponentHelper::getParams('com_solidres');
     $this->currency_id = $params->get('default_currency_id');
     SRHtml::_('jquery.datepicker');
     JHtml::stylesheet('com_solidres/assets/main.css', false, true, false);
     $rowidx = isset($this->item->tariff) ? count($this->item->tariff) : 0;
     $rowIdRoom = isset($this->item->rooms) ? count($this->item->rooms) : 0;
     $customerGroupsJS = '';
     $i = 0;
     foreach ($this->customerGroups as $group) {
         $customerGroupsJS[$i]['id'] = $group->id === NULL ? '' : $group->id;
         $customerGroupsJS[$i]['title'] = $group->name;
         $i++;
     }
     JText::script('SR_FIELD_ROOM_CAN_NOT_DELETE_ROOM');
     $doc->addScriptDeclaration("\n            srUg    = " . json_encode($customerGroupsJS) . ";\n\t\t\tSolidres.jQuery(function(\$) {\n\t\t\t    \$('#toolbar').srRoomType({rowidx : {$rowidx}, rowIdRoom: {$rowIdRoom}, srUg: srUg});\n\t\t\t});\n\t\t");
     if (count($errors = $this->get('Errors'))) {
         JError::raiseError(500, implode("\n", $errors));
         return false;
     }
     $this->addToolbar();
     parent::display($tpl);
 }
Esempio n. 11
0
    function display($tpl = null)
    {
        $model = $this->getModel();
        $this->config = JComponentHelper::getParams('com_solidres');
        $this->defaultGallery = $this->config->get('default_gallery', 'simple_gallery');
        $this->showPoweredByLink = $this->config->get('show_solidres_copyright', '1');
        $this->item = $model->getItem();
        $this->checkin = $model->getState('checkin');
        $this->checkout = $model->getState('checkout');
        $this->adults = $model->getState('adults');
        $this->children = $model->getState('children');
        $this->countryId = $model->getState('country_id');
        $this->geoStateId = $model->getState('geo_state_id');
        $this->roomTypeObj = SRFactory::get('solidres.roomtype.roomtype');
        $this->numberOfNights = $this->roomTypeObj->calculateDateDiff($this->checkin, $this->checkout);
        $this->document = JFactory::getDocument();
        $this->context = 'com_solidres.reservation.process';
        $this->coupon = JFactory::getApplication()->getUserState($this->context . '.coupon');
        JHtml::_('jquery.framework');
        JHtml::_('bootstrap.framework');
        SRHtml::_('jquery.colorbox', 'show_map', '700px', '650px', 'true', 'false');
        JHtml::stylesheet('com_solidres/assets/main.css', false, true, false);
        $this->document->addScriptDeclaration('
			Solidres.jQuery(document).ready(function ($) {
				$(".sr-photo").colorbox({rel:"sr-photo", transition:"fade"});
				$("#sr-change-date").colorbox({inline: true, width:"500px", height: "350px"});
			});
		');
        JText::script('SR_CAN_NOT_REMOVE_COUPON');
        if (count($errors = $this->get('Errors'))) {
            JError::raiseError(500, implode("\n", $errors));
            return false;
        }
        $this->_prepareDocument();
        parent::display($tpl);
    }
Esempio n. 12
0
 /**
  * Allow to processing of category data before it is saved.
  *
  * @param $data
  * @param $table
  * @param $isNew
  *
  * @return  void
  */
 function onCategoryBeforeSave($data, $table, $isNew)
 {
     $dbo = JFactory::getDbo();
     $srNode = SRFactory::getNode();
     $dbo->setQuery('LOCK TABLES ' . $dbo->quoteName('#__sr_categories') . ' WRITE, ' . $dbo->quoteName('#__assets') . ' WRITE');
     if (!$dbo->execute()) {
         $e = new JException(JText::sprintf('plgExtensionSolidres::onCategoryAfterSave Lock table failed', get_class($this), $dbo->getErrorMsg()));
         $this->setError($e);
         return false;
     }
     if ($isNew) {
         $srNode->saveNode($data['parent_id']);
     } else {
         $srNode->updateNode($data);
     }
 }
Esempio n. 13
0
 /**
  * Generate the calendar
  *
  * @access    public
  * @param     string   $year
  * @param     string   $month
  * @param     integer  the month
  * @param     array    $data
  * @internal param \the $array data to be shown in the calendar cells
  * @return    string
  */
 function generate($year = '', $month = '', $roomTypeID, $data = array())
 {
     // Set and validate the supplied month/year
     if ($year == '') {
         $year = date("Y", $this->local_time);
     }
     if ($month == '') {
         $month = date("m", $this->local_time);
     }
     if (strlen($year) == 1) {
         $year = '200' . $year;
     }
     if (strlen($year) == 2) {
         $year = '20' . $year;
     }
     if (strlen($month) == 1) {
         $month = '0' . $month;
     }
     $adjusted_date = $this->adjust_date($month, $year);
     $month = $adjusted_date['month'];
     $year = $adjusted_date['year'];
     // Determine the total days in the month
     $total_days = $this->get_total_days($month, $year);
     // Set the starting day of the week
     $start_days = array('sunday' => 0, 'monday' => 1, 'tuesday' => 2, 'wednesday' => 3, 'thursday' => 4, 'friday' => 5, 'saturday' => 6);
     $start_day = !isset($start_days[$this->start_day]) ? 0 : $start_days[$this->start_day];
     // Set the starting day number
     $local_date = mktime(12, 0, 0, $month, 1, $year);
     $date = getdate($local_date);
     $day = $start_day + 1 - $date["wday"];
     while ($day > 1) {
         $day -= 7;
     }
     // Set the current month/year/day
     // We use this to determine the "today" date
     $cur_year = date("Y", $this->local_time);
     $cur_month = date("m", $this->local_time);
     $cur_day = date("j", $this->local_time);
     $is_current_month = ($cur_year == $year and $cur_month == $month) ? TRUE : FALSE;
     // Generate the template data array
     $this->parse_template();
     // Begin building the calendar output
     $out = $this->temp['table_open'];
     $out .= "\n";
     $out .= "\n";
     $out .= $this->temp['heading_row_start'];
     $out .= "\n";
     // "previous" month link
     if ($this->show_next_prev == TRUE) {
         // Add a trailing slash to the  URL if needed
         $this->next_prev_url = preg_replace("/(.+?)\\/*\$/", "\\1/", $this->next_prev_url);
         $adjusted_date = $this->adjust_date($month - 1, $year);
         $out .= str_replace('{previous_url}', $this->next_prev_url . $adjusted_date['year'] . '/' . $adjusted_date['month'], $this->temp['heading_previous_cell']);
         $out .= "\n";
     }
     // Heading containing the month/year
     $colspan = $this->show_next_prev == TRUE ? 5 : 7;
     $this->temp['heading_title_cell'] = str_replace('{colspan}', $colspan, $this->temp['heading_title_cell']);
     $this->temp['heading_title_cell'] = str_replace('{heading}', $this->get_month_name($month) . "&nbsp;" . $year, $this->temp['heading_title_cell']);
     $out .= $this->temp['heading_title_cell'];
     $out .= "\n";
     // "next" month link
     if ($this->show_next_prev == TRUE) {
         $adjusted_date = $this->adjust_date($month + 1, $year);
         $out .= str_replace('{next_url}', $this->next_prev_url . $adjusted_date['year'] . '/' . $adjusted_date['month'], $this->temp['heading_next_cell']);
     }
     $out .= "\n";
     $out .= $this->temp['heading_row_end'];
     $out .= "\n";
     // Write the cells containing the days of the week
     $out .= "\n";
     $out .= $this->temp['week_row_start'];
     $out .= "\n";
     $day_names = $this->get_day_names();
     for ($i = 0; $i < 7; $i++) {
         if (isset($day_names[($start_day + $i) % 7])) {
             $out .= str_replace('{week_day}', $day_names[($start_day + $i) % 7], $this->temp['week_day_cell']);
         }
     }
     $out .= "\n";
     $out .= $this->temp['week_row_end'];
     $out .= "\n";
     // Build the main body of the calendar
     $solidresRoomType = SRFactory::get('solidres.roomtype.roomtype');
     while ($day <= $total_days) {
         $out .= "\n";
         $out .= $this->temp['cal_row_start'];
         $out .= "\n";
         for ($i = 0; $i < 7; $i++) {
             if ($day > 0 and $day <= $total_days) {
                 $checkin = $year . '-' . $month . '-' . $day;
                 $checkout = date('Y-m-d', strtotime('+1 day', strtotime($checkin)));
                 $availableRooms = $solidresRoomType->getListAvailableRoom($roomTypeID, $checkin, $checkout);
                 $temp = ($is_current_month == TRUE and $day == $cur_day) ? $this->temp['cal_cell_start_today_busy'] : $this->temp['cal_cell_start_busy'];
                 $data[$day]['cell_class'] = '';
                 if (count($availableRooms) == 0) {
                     $data[$day]['cell_class'] = 'busy';
                     $data[$day]['cell_link'] = '#';
                 }
                 $out .= str_replace('{cell_class}', $data[$day]['cell_class'], $temp);
                 if (isset($data[$day]) && isset($data[$day]['cell_link'])) {
                     // Cells with content
                     $temp = ($is_current_month == TRUE and $day == $cur_day) ? $this->temp['cal_cell_content_today'] : $this->temp['cal_cell_content'];
                     $out .= str_replace('{cell_class}', $data[$day]['cell_class'], str_replace('{day}', $day, str_replace('{cell_link}', $data[$day]['cell_link'], $temp)));
                 } else {
                     // Cells with no content
                     $temp = ($is_current_month == TRUE and $day == $cur_day) ? $this->temp['cal_cell_no_content_today'] : $this->temp['cal_cell_no_content'];
                     $out .= str_replace('{day}', $day, $temp);
                 }
             } else {
                 // Blank cells
                 $out .= ($is_current_month == TRUE and $day == $cur_day) ? $this->temp['cal_cell_start_today'] : $this->temp['cal_cell_start'];
                 $out .= $this->temp['cal_cell_blank'];
             }
             $out .= ($is_current_month == TRUE and $day == $cur_day) ? $this->temp['cal_cell_end_today'] : $this->temp['cal_cell_end'];
             $day++;
         }
         $out .= "\n";
         $out .= $this->temp['cal_row_end'];
         $out .= "\n";
     }
     $out .= "\n";
     $out .= $this->temp['table_close'];
     return $out;
 }
Esempio n. 14
0
 /**
  * Method to get a single record.
  *
  * @param	int	$pk The id of the primary key.
  *
  * @return	mixed	Object on success, false on failure.
  * 
  * @since	0.1.0
  */
 public function getItem($pk = null)
 {
     $pk = !empty($pk) ? $pk : (int) $this->getState('reservationasset.id');
     $item = parent::getItem($pk);
     $dispatcher = JDispatcher::getInstance();
     if ($item->id) {
         // Convert the params field to an array.
         $registry = new JRegistry();
         $registry->loadString($item->metadata, 'JSON');
         $item->metadata = $registry->toArray();
         // Get the dispatcher and load the extension plugins.
         JPluginHelper::importPlugin('extension');
         // Import the solidres plugin group. TODO: consolidate these plugin groups
         JPluginHelper::importPlugin('solidres');
         $roomtypesModel = JModelLegacy::getInstance('RoomTypes', 'SolidresModel', array('ignore_request' => true));
         $extrasModel = JModelLegacy::getInstance('Extras', 'SolidresModel', array('ignore_request' => true));
         $customerModel = JModelLegacy::getInstance('Customer', 'SolidresModel', array('ignore_request' => true));
         $mediaListModel = JModelLegacy::getInstance('MediaList', 'SolidresModel', array('ignore_request' => true));
         $roomtypesModel->setState('filter.reservation_asset_id', $item->id);
         $roomtypesModel->setState('filter.state', '1');
         $item->roomTypes = $roomtypesModel->getItems();
         $extrasModel->setState('filter.reservation_asset_id', $item->id);
         $item->extras = $extrasModel->getItems();
         $partner = $customerModel->getItem($item->partner_id);
         $item->partnerName = $partner->firstname . " " . $partner->middlename . " " . $partner->lastname;
         $mediaListModel->setState('filter.reservation_asset_id', $item->id);
         $mediaListModel->setState('filter.room_type_id', NULL);
         $item->media = $mediaListModel->getItems();
         //  ** For front end tasks ** //
         $srRoomType = SRFactory::get('solidres.roomtype.roomtype');
         $checkin = $this->getState('checkin');
         $checkout = $this->getState('checkout');
         if (!empty($checkin) && !empty($checkout)) {
             $app = JFactory::getApplication();
             $context = 'com_solidres.reservation.process';
             $coupon = $app->getUserState($context . '.coupon');
             for ($i = 0, $n = count($item->roomTypes); $i < $n; $i++) {
                 $mediaListModel->setState('filter.reservation_asset_id', NULL);
                 $mediaListModel->setState('filter.room_type_id', $item->roomTypes[$i]->id);
                 $item->roomTypes[$i]->media = $mediaListModel->getItems();
                 // Get the default tariff
                 $defaultTariff = $srRoomType->getPrice($pk, $item->roomTypes[$i]->id, true, false, $checkin, $checkout, $item->currency_id, $coupon);
                 $item->roomTypes[$i]->defaultTariff = $defaultTariff['total_price_tax_excl_formatted'];
                 $item->roomTypes[$i]->defaultTariffIsAppliedCoupon = $defaultTariff['is_applied_coupon'];
                 // Get complex tariff
                 $complexTariff = $srRoomType->getPrice($pk, $item->roomTypes[$i]->id, false, true, $checkin, $checkout, $item->currency_id, $coupon);
                 $item->roomTypes[$i]->complexTariff = $complexTariff['total_price_tax_excl_formatted'];
                 $item->roomTypes[$i]->complexTariffIsAppliedCoupon = $complexTariff['is_applied_coupon'];
                 $item->roomTypes[$i]->totalAvailableRoom = is_array($srRoomType->getListAvailableRoom($item->roomTypes[$i]->id, $checkin, $checkout)) ? count($srRoomType->getListAvailableRoom($item->roomTypes[$i]->id, $checkin, $checkout)) : 0;
                 $item->roomTypes[$i]->tariffBreakDown = $complexTariff['tariff_break_down'];
                 // Get custom fields
                 $results = $dispatcher->trigger('onRoomTypePrepareData', array('com_solidres.roomtype', $item->roomTypes[$i]));
                 if (count($results) && in_array(false, $results, true)) {
                     $this->setError($dispatcher->getError());
                     $item->roomTypes[$i] = false;
                 }
             }
         }
     }
     // Trigger the data preparation event.
     $results = $dispatcher->trigger('onReservationAssetPrepareData', array('com_solidres.reservationasset', $item));
     if (count($results) && in_array(false, $results, true)) {
         $this->setError($dispatcher->getError());
         $item = false;
     }
     return $item;
 }
Esempio n. 15
0
<?php

/*------------------------------------------------------------------------
  Solidres - Hotel booking extension for Joomla
  ------------------------------------------------------------------------
  @Author    Solidres Team
  @Website   http://www.solidres.com
  @Copyright Copyright (C) 2013 Solidres. All Rights Reserved.
  @License   GNU General Public License version 3, or later
------------------------------------------------------------------------*/
defined('_JEXEC') or die;
$srMedia = SRFactory::get('solidres.media.media');
?>
	
<form action="<?php 
JRoute::_('index.php?option=com_solidres');
?>
" method="post" name="adminForm" id="medialibraryform">
	<div class="btn-group">
		<button id="media-library-delete" class="toolbar btn" type="submit">
			<i class="icon-remove"></i> 
			<?php 
echo JText::_('SR_MEDIA_DELETE_BTN');
?>
		</button>
		<button id="media-library-insert" class="toolbar btn">
			<i class="icon-ok"></i> 
			<?php 
echo JText::_('SR_MEDIA_INSERT_BTN');
?>
		</button>
Esempio n. 16
0
 /**
  * Method to upload a file from client side, storing and making thumbnail for images
  *
  * TODO add token check for file uploading
  *
  * @return JSON
  */
 public function upload()
 {
     // Check for request forgeries
     if (!JSession::checkToken('request')) {
         die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "' . JText::_('JINVALID_TOKEN') . '"}, "id" : "id"}');
     }
     $user = JFactory::getUser();
     $srMedia = SRFactory::get('solidres.media.media');
     $date = JFactory::getDate();
     $model = $this->getModel('media');
     $err = NULL;
     $targetDir = SRPATH_MEDIA_IMAGE_SYSTEM;
     $targetThumbDir = SRPATH_MEDIA_IMAGE_SYSTEM . '/thumbnails';
     static $log;
     if ($log == null) {
         $options['format'] = '{DATE}\\t{TIME}\\t{LEVEL}\\t{CODE}\\t{MESSAGE}';
         $options['text_file'] = 'media.php';
         $log = JLog::addLogger($options);
     }
     JLog::add('Start uploading', JLog::DEBUG);
     if (!$user->authorise('core.create', 'com_solidres')) {
         JError::raiseWarning(403, JText::_('SR_ERROR_CREATE_NOT_PERMITTED'));
         return;
     }
     // HTTP headers for no cache etc
     header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
     header("Cache-Control: no-store, no-cache, must-revalidate");
     header("Cache-Control: post-check=0, pre-check=0", false);
     header("Pragma: no-cache");
     // 5 minutes execution time
     @set_time_limit(5 * 60);
     // Uncomment this one to fake upload time
     // usleep(5000);
     // Get parameters
     $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
     $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
     $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
     JLog::add('Original file name ' . $fileName, JLog::DEBUG);
     // Clean the fileName for security reasons
     $_FILES['file']['name'] = JFile::makeSafe($_FILES['file']['name']);
     $fileName = $_FILES['file']['name'];
     JLog::add('Cleaned file name ' . $_FILES['file']['name'], JLog::DEBUG);
     // Look for the content type header
     if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
     }
     if (isset($_SERVER["CONTENT_TYPE"])) {
         $contentType = $_SERVER["CONTENT_TYPE"];
     }
     // Check the target file against our rules to see if it is allow to be uploaded
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     // Do not check the chunk since it is not valid
     if (strpos($contentType, "multipart") !== false && $chunks == 0) {
         if (!SRMediaHelper::canUpload($_FILES['file'], $err)) {
             die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "' . JText::_($err) . '"}, "id" : "id"}');
             //return;
         }
     }
     // Make sure the fileName is unique but only if chunking is disabled
     if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
         $ext = strrpos($fileName, '.');
         $fileName_a = substr($fileName, 0, $ext);
         $fileName_b = substr($fileName, $ext);
         $count = 1;
         while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) {
             $count++;
         }
         $fileName = $fileName_a . '_' . $count . $fileName_b;
     }
     // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
     if (strpos($contentType, "multipart") !== false) {
         if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
             // Open temp file
             $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
             if ($out) {
                 // Read binary input stream and append it to temp file
                 $in = fopen($_FILES['file']['tmp_name'], "rb");
                 if ($in) {
                     while ($buff = fread($in, 4096)) {
                         fwrite($out, $buff);
                     }
                 } else {
                     die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                 }
                 fclose($in);
                 fclose($out);
                 @unlink($_FILES['file']['tmp_name']);
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
             }
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
         }
     } else {
         // Open temp file
         $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
         if ($out) {
             // Read binary input stream and append it to temp file
             $in = fopen("php://input", "rb");
             if ($in) {
                 while ($buff = fread($in, 4096)) {
                     fwrite($out, $buff);
                 }
             } else {
                 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
             }
             fclose($in);
             fclose($out);
         } else {
             die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
         }
     }
     // ONLY PERFORM THESE LAST OPERATIONS WHEN THE FILE IS TOTALLY UPLOADED (NOT PARTLY UPLOADED)
     if ($chunks == 0 || $chunk == $chunks - 1) {
         $uploadedFilePath = $targetDir . '/' . $fileName;
         // Prepare some data for db storing
         $data = array('type' => 'IMAGE', 'value' => $fileName, 'name' => $fileName, 'created_date' => $date->toSql(), 'created_by' => $user->get('id'), 'mime_type' => $srMedia->getMime($uploadedFilePath), 'size' => filesize($uploadedFilePath));
         // Attempt to save the data.
         if (!$model->save($data)) {
             JLog::add('Can not save this file to db: ' . $fileName, JLog::DEBUG);
             die('{"jsonrpc" : "2.0", "error" : {"code": 105, "message": "' . JText::_('SR_ERROR_CAN_NOT_SAVE_DB') . '"}, "id" : "id"}');
         }
         // If media is image, create thumbnail for it
         if (SRMediaHelper::isImage($uploadedFilePath)) {
             $media = new Zebra_Image();
             $media->source_path = $uploadedFilePath;
             $media->target_path = $targetThumbDir . '/1/' . $fileName;
             $media->resize(300, 250);
             $media->target_path = $targetThumbDir . '/2/' . $fileName;
             $media->resize(75, 75);
         }
     }
     die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
 }
Esempio n. 17
0
 /**
  * Get room type information to be display in the reservation confirmation screen
  *
  * @return array $ret An array contain room type information
  */
 public function getRoomType()
 {
     // Construct a simple array of room type ID and its price
     $roomTypePricesMapping = array();
     $app = JFactory::getApplication();
     $srRoomType = SRFactory::get('solidres.roomtype.roomtype');
     $currencyId = $app->getUserState($this->context . '.currency_id');
     $modelName = $this->getName();
     $roomTypes = $this->getState($modelName . '.roomTypes');
     $checkin = $this->getState($modelName . '.checkin');
     $checkout = $this->getState($modelName . '.checkout');
     $reservationAssetId = $this->getState($modelName . '.reservationAssetId');
     $coupon = $app->getUserState($this->context . '.coupon');
     $roomtypeModel = JModelLegacy::getInstance('RoomType', 'SolidresModel', array('ignore_request' => true));
     $extraModel = JModelLegacy::getInstance('Extra', 'SolidresModel', array('ignore_request' => true));
     $totalPriceTaxIncl = 0;
     $totalPriceTaxExcl = 0;
     $totalReservedRoom = 0;
     $ret = array();
     // Get a list of room type based on search conditions
     foreach ($roomTypes as $roomTypeId => $bookedRoomTypeQuantity) {
         if ($bookedRoomTypeQuantity == 0) {
             continue;
         }
         $r = $roomtypeModel->getItem(array('id' => $roomTypeId, 'reservation_asset_id' => $reservationAssetId));
         $ret[$roomTypeId]['name'] = $r->name;
         $ret[$roomTypeId]['description'] = $r->description;
         $ret[$roomTypeId]['occupancy_adult'] = $r->occupancy_adult;
         $ret[$roomTypeId]['occupancy_child'] = $r->occupancy_child;
         $currency['default'] = $srRoomType->getPrice($reservationAssetId, $roomTypeId, true, false, $checkin, $checkout, $currencyId, $coupon);
         $currency['custom'] = $srRoomType->getPrice($reservationAssetId, $roomTypeId, false, true, $checkin, $checkout, $currencyId, $coupon);
         if (!empty($currency['custom'])) {
             $ret[$roomTypeId]['currency'] = $currency['custom'];
         } else {
             $ret[$roomTypeId]['currency'] = $currency['default'];
         }
         $totalPriceTaxIncl += $ret[$roomTypeId]['currency']['total_price_tax_incl'] * $bookedRoomTypeQuantity;
         $totalPriceTaxExcl += $ret[$roomTypeId]['currency']['total_price_tax_excl'] * $bookedRoomTypeQuantity;
         // Prepare extra data for each room
         $roomTypeExtraIds = $srRoomType->getExtra($roomTypeId);
         if (is_array($roomTypeExtraIds)) {
             foreach ($roomTypeExtraIds as $roomTypeExtraId) {
                 $ret[$roomTypeId]['extras'][$roomTypeExtraId] = $extraModel->getItem($roomTypeExtraId);
             }
         }
         // Calculate number of available rooms
         $ret[$roomTypeId]['totalAvailableRoom'] = count($srRoomType->getListAvailableRoom($roomTypeId, $checkin, $checkout));
         $ret[$roomTypeId]['quantity'] = $bookedRoomTypeQuantity;
         $roomTypePricesMapping[$roomTypeId] = array('total_price' => $ret[$roomTypeId]['currency']['total_price'], 'total_price_tax_incl' => $ret[$roomTypeId]['currency']['total_price_tax_incl'], 'total_price_tax_excl' => $ret[$roomTypeId]['currency']['total_price_tax_excl']);
         // Only allow quantity within quota
         if ($bookedRoomTypeQuantity <= $ret[$roomTypeId]['totalAvailableRoom']) {
             $totalReservedRoom += $bookedRoomTypeQuantity;
         } else {
             return false;
         }
     }
     // end room type loop
     $this->setState($modelName . '.totalReservedRoom', $totalReservedRoom);
     $app->setUserState($this->context . '.cost', array('total_price' => $totalPriceTaxIncl, 'total_price_tax_incl' => $totalPriceTaxIncl, 'total_price_tax_excl' => $totalPriceTaxExcl));
     $app->setUserState($this->context . '.room_type_prices_mapping', $roomTypePricesMapping);
     return $ret;
 }
Esempio n. 18
0
 /**
  * Restore the database from uploaded file
  *
  * @param $file
  *
  * @return boolean
  */
 public function restore($file)
 {
     $query = $this->_db->getQuery(true);
     $strQuery = 'SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;';
     $this->_db->setQuery($strQuery);
     $this->_db->execute();
     if ($this->_db->getErrorNum()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     $strQuery = 'DELETE FROM ' . $this->_db->quoteName('#__assets') . ' WHERE name LIKE \'com_solidres%\';';
     $this->_db->setQuery($strQuery);
     $this->_db->execute();
     if ($this->_db->getErrorNum()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     $zipFile = JFactory::getConfig()->get('tmp_path') . '/' . $file['name'];
     JFile::upload($file['tmp_name'], $zipFile);
     SRFactory::get('solidres.utilities.ziparchive')->unZip($zipFile, JFactory::getConfig()->get('tmp_path') . '/zip/');
     JFile::delete($zipFile);
     $listFiles = JFolder::files(JFactory::getConfig()->get('tmp_path') . '/zip');
     $xmlPath = '';
     $sqlPath = '';
     foreach ($listFiles as $f) {
         $path = JFactory::getConfig()->get('tmp_path') . '/zip/' . $f;
         if (JFile::getExt($path) == 'xml') {
             $xmlPath = $path;
         } else {
             $sqlPath = $path;
         }
     }
     $xml = JFactory::getXML($xmlPath);
     foreach ($xml->table as $table) {
         $query->clear();
         $query->select('MAX(id) max_id, MAX(rgt) max_right');
         $query->from($this->_db->quoteName('#__assets'));
         $this->_db->setQuery($query);
         $result = $this->_db->loadObject();
         $newId = (int) $result->max_id + 1;
         $newRight = (int) $result->max_right;
         $subRange = $newId - (int) $table->row[0]['id'];
         $subRight = $newRight - (int) $table->row[0]['lft'];
         $rootRight = $newRight;
         foreach ($table->row as $row) {
             //insert this row to asset
             if ($row['parent_id'] == 1) {
                 //update root node
                 $rootRight = $row['rgt'] + $subRight + 1;
                 $query->clear();
                 $query->update($this->_db->quoteName('#__assets'));
                 $query->set('rgt = ' . $this->_db->quote($rootRight));
                 $query->where('id = 1');
                 $this->_db->setQuery($query);
                 $this->_db->execute();
                 $query->clear();
                 $query->insert($this->_db->quoteName('#__assets'));
                 foreach ($row->attributes() as $k => $v) {
                     if ($k == 'id') {
                         $query->set($k . '=' . $this->_db->quote($v + $subRange));
                     } elseif ($k == 'ltf' || $k == 'rgt') {
                         $query->set($k . '=' . $this->_db->quote($v + $subRight));
                     } else {
                         $query->set($k . '=' . $this->_db->quote(htmlspecialchars_decode($v)));
                     }
                 }
             } else {
                 $query->clear();
                 $query->insert($this->_db->quoteName('#__assets'));
                 foreach ($row->attributes() as $k => $v) {
                     if ($k == 'id' || $k == 'parent_id') {
                         $query->set($k . '=' . $this->_db->quote($v + $subRange));
                     } elseif ($k == 'ltf' || $k == 'rgt') {
                         $query->set($k . '=' . $this->_db->quote($v + $subRight));
                     } else {
                         $query->set($k . '=' . $this->_db->quote(htmlspecialchars_decode($v)));
                     }
                 }
             }
             $this->_db->setQuery($query);
             $this->_db->execute();
             if ($this->_db->getErrorNum()) {
                 $this->setError($this->_db->getErrorMsg());
                 return false;
             }
             //insert into children table
             foreach ($row->childtable as $childtable) {
                 $tableName = $childtable['name'];
                 foreach ($childtable->childrow as $childrow) {
                     $query->clear();
                     $query->insert($tableName);
                     foreach ($childrow->attributes() as $k => $v) {
                         if ($k == 'asset_id') {
                             $query->set($k . '=' . $this->_db->quote($v + $subRange));
                         } elseif ($k == 'id') {
                         } else {
                             $query->set($k . '=' . $this->_db->quote(htmlspecialchars_decode($v)));
                         }
                     }
                     $this->_db->setQuery($query);
                     $this->_db->execute();
                     if ($this->_db->getErrorNum()) {
                         $this->setError($this->_db->getErrorMsg());
                         return false;
                     }
                 }
             }
         }
     }
     if (!($sqlContent = file_get_contents($sqlPath))) {
         $this->setError(JText::_('SR_RESTORE_READ_FILE_ERROR'));
         return false;
     }
     $queries = $this->_splitQueries($sqlContent);
     foreach ($queries as $q) {
         $q = trim($q);
         if (!empty($q) && $q[0] != '#') {
             $this->_db->setQuery($q);
             $this->_db->execute();
             // Check for errors.
             if ($this->_db->getErrorNum()) {
                 $this->setError($this->_db->getErrorMsg());
                 return false;
             }
         }
     }
     JFolder::delete(JFactory::getConfig()->get('tmp_path') . '/zip');
     $strQuery = 'SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS';
     $this->_db->setQuery($strQuery);
     $this->_db->execute();
     if ($this->_db->getErrorNum()) {
         $this->setError($this->_db->getErrorMsg());
         return false;
     }
     return true;
 }
Esempio n. 19
0
 public function backupDb($tableName)
 {
     $utility = SRFactory::get('solidres.utilities.utilities');
     $br = "\n";
     $fields = $this->_db->getTableFields($tableName);
     $arrField = array();
     foreach ($fields[$tableName] as $k => $v) {
         $arrField[] = $k;
     }
     $strQuery = '';
     $tableFields = $utility->myImplodeField($arrField);
     $query = $this->_db->getQuery(true);
     $query->clear();
     $query->select('*');
     $query->from($tableName);
     $this->_db->setQuery($query);
     $result = $this->_db->loadRowList();
     if (empty($result)) {
         return $strQuery . $br . $br . $br;
     }
     $strQuery .= 'INSERT INTO `' . $tableName . '` (' . $tableFields . ') VALUES' . $br;
     for ($i = 0; $i < count($result); $i++) {
         $rsValues = $utility->myImplode($result[$i]);
         $strQuery .= '(' . $rsValues . ')';
         if ($i == count($result) - 1) {
             $strQuery .= ';' . $br;
         } else {
             $strQuery .= ',' . $br;
         }
     }
     return $strQuery . $br . $br . $br;
 }
Esempio n. 20
0
 /**
  * Send email when reservation is completed
  *
  * @since  0.1.0
  *
  * @return boolean Error message or True if email sending completed successfully
  */
 private function sendEmail()
 {
     require_once SRPATH_LIBRARY . '/swift/swift_required.php';
     $messageTemplatePath = array();
     $subject = array();
     $body = array();
     $raTable = JTable::getInstance('ReservationAsset', 'SolidresTable');
     $raTable->load($this->reservationData['raid']);
     $hotelEmail = $raTable->email;
     $hotelName = $raTable->name;
     $customerEmail = $this->reservationData['customer_email'];
     $messageTemplatePath[$customerEmail] = SRPATH_LIBRARY . '/mail/en-GB/reservation_complete.html';
     $subject[$customerEmail] = JText::_('SR_EMAIL_RESERVATION_COMPLETE');
     $messageTemplatePath[$hotelEmail] = SRPATH_LIBRARY . '/mail/en-GB/new_reservation_notification.html';
     $subject[$hotelEmail] = JText::_('SR_EMAIL_NEW_RESERVATION_NOTIFICATION');
     // Send to the customer
     if (file_exists($messageTemplatePath[$customerEmail])) {
         $body[$customerEmail] = file_get_contents($messageTemplatePath[$customerEmail]);
     }
     $replacements[$customerEmail] = array('{hotel_name}' => $hotelName, '{hotel_url}' => $raTable->website, '{customer_firstname}' => $this->reservationData['customer_firstname'], '{customer_middlename}' => $this->reservationData['customer_middlename'], '{customer_lastname}' => $this->reservationData['customer_lastname'], '{code}' => $this->app->getUserState($this->context . '.code'), '{website}' => $raTable->website, '{email}' => $raTable->email, '{phone}' => $raTable->phone);
     $mail = SRFactory::get('solidres.mail.mail');
     $mail->mailFrom = array($hotelEmail => $hotelName);
     $mail->mailTo = $customerEmail;
     $mail->replacements = $replacements;
     $mail->subject = $subject[$customerEmail];
     $mail->body = $body[$customerEmail];
     if (!$mail->send()) {
         return false;
     }
     // Send to the hotel owner
     if (file_exists($messageTemplatePath[$hotelEmail])) {
         $body[$hotelEmail] = file_get_contents($messageTemplatePath[$hotelEmail]);
     }
     $replacements[$hotelEmail] = array('{hotel_name}' => $hotelName, '{hotel_url}' => $raTable->website, '{code}' => $this->app->getUserState($this->context . '.code'), '{reservation_edit_link}' => JUri::base() . 'administrator/index.php?option=com_solidres&view=reservation&layout=edit&id=' . $this->app->getUserState($this->context . '.savedReservationId'));
     $mail2 = SRFactory::get('solidres.mail.mail');
     $mail2->mailFrom = array($hotelEmail => $hotelName);
     $mail2->mailTo = $hotelEmail;
     $mail2->replacements = $replacements;
     $mail2->subject = $subject[$hotelEmail];
     $mail2->body = $body[$hotelEmail];
     if (!$mail2->send()) {
         return false;
     }
     return true;
 }
Esempio n. 21
0
    /**
     * Return html to display confirmation form in one-page reservation, data is retrieved from user session
     *
     * @return string HTML
     */
    public function getHtmlConfirmation()
    {
        JLoader::register('ContentHelperRoute', JPATH_SITE . '/components/com_content/helpers/route.php');
        // TODO replace this manual call with autoloading later
        JLoader::register('SRCurrency', SRPATH_LIBRARY . '/currency/currency.php');
        $this->reservationDetails = $this->app->getUserState($this->context);
        $model = $this->getModel();
        $modelName = $model->getName();
        $checkin = $this->reservationDetails->room['checkin'];
        $checkout = $this->reservationDetails->room['checkout'];
        $raId = $this->reservationDetails->room['raid'];
        $roomTypeObj = SRFactory::get('solidres.roomtype.roomtype');
        $currency = new SRCurrency(0, $this->reservationDetails->currency_id);
        $totalRoomTypeExtraCost = $this->reservationDetails->room['total_extra_price'];
        $numberOfNights = $roomTypeObj->calculateDateDiff($checkin, $checkout);
        $cost = $this->app->getUserState($this->context . '.cost');
        $model->setState($modelName . '.roomTypes', $this->reservationDetails->selected_room_types);
        $model->setState($modelName . '.checkin', $checkin);
        $model->setState($modelName . '.checkout', $checkout);
        $model->setState($modelName . '.reservationAssetId', $raId);
        $task = 'reservation.save';
        if ($this->reservationDetails->payment['payment_method'] == 'paypalexpresscheckout') {
            $task = 'reservationppec.save';
        }
        $roomTypes = $model->getRoomType();
        $html = '
			<div class="reservation-box-inner">
				<form
				    id="sr-reservation-form-confirmation"
				    class=""
					action="' . JRoute::_("index.php?option=com_solidres&task=" . $task) . '"
					method="POST">

					<p>
						' . JText::_("SR_RESERVATION_NOTICE_CONFIRMATION") . '
					</p>

					<div id="reservation-confirmation-box">
						<table class="table">
							<tbody>';
        // Room cost
        foreach ($roomTypes as $roomTypeId => $roomTypeDetail) {
            if ($roomTypeDetail["quantity"] > 0) {
                $tempValue = $roomTypeDetail['currency']['total_price_tax_excl_formatted']->getValue();
                $currency->setValue($tempValue * $roomTypeDetail["quantity"]);
                $html .= '
								<tr>
									<td>
										' . $roomTypeDetail["name"] . '
									</td>
									<td>
										' . $roomTypeDetail["quantity"] . '
									</td>
									<td>
										' . JText::plural("SR_NIGHTS", $numberOfNights) . '
									</td>
									<td class="align-right">
										' . $currency->format() . '
									</td>
								</tr>';
            }
        }
        // Total room cost
        $totalRoomCost = new SRCurrency($cost['total_price_tax_excl'], $this->reservationDetails->currency_id);
        $html .= '
								<tr>
									<td colspan="3">
										' . JText::_("SR_TOTAL_ROOM_COST") . '
									</td>
									<td class="align-right">
										' . $totalRoomCost->format() . '
									</td>
								</tr>';
        // Imposed taxes
        $taxesModel = JModelLegacy::getInstance('Taxes', 'SolidresModel', array('ignore_request' => true));
        $taxesModel->setState('filter.reservation_asset_id', $this->reservationDetails->room['raid']);
        $imposedTaxTypes = $taxesModel->getItems();
        $totalImposedTax = 0;
        foreach ($imposedTaxTypes as $taxType) {
            $imposedAmount = $taxType->rate * $cost['total_price_tax_excl'];
            $totalImposedTax += $imposedAmount;
            $currency->setValue($imposedAmount);
            $taxItem = new SRCurrency($imposedAmount, $this->reservationDetails->currency_id);
            $html .= '
								<tr>
									<td colspan="3">
										' . $taxType->name . '
									</td>
									<td class="align-right">
										 ' . $taxItem->format() . '
									</td>
								</tr>';
        }
        // Extra cost
        $totalExtraCost = new SRCurrency($totalRoomTypeExtraCost, $this->reservationDetails->currency_id);
        $html .= '
								<tr>
									<td colspan="3">
										' . JText::_("SR_TOTAL_EXTRA_COST") . '
									</td>
									<td id="total-extra-cost" class="align-right">
										' . $totalExtraCost->format() . '
									</td>
								</tr>';
        // Grand total cost
        $grandTotal = new SRCurrency($cost['total_price_tax_incl'] + $totalRoomTypeExtraCost, $this->reservationDetails->currency_id);
        $html .= '
								<tr>
									<td colspan="3">
									<strong>' . JText::_("SR_GRAND_TOTAL") . '</strong>
									</td>
									<td class="align-right gra">
										' . $grandTotal->format() . '
									</td>
								</tr>';
        // Terms and conditions
        $bookingConditionsLink = JRoute::_(ContentHelperRoute::getArticleRoute($this->reservationDetails->booking_conditions));
        $privacyPolicyLink = JRoute::_(ContentHelperRoute::getArticleRoute($this->reservationDetails->privacy_policy));
        $html .= '
								<tr>
									<td colspan="4">
										<p>
											<input type="checkbox" id="termsandconditions" data-target="finalbutton" />
											I agree with the
											<a target="_blank" href="' . $bookingConditionsLink . '">Booking conditions</a> and
											<a target="_blank" href="' . $privacyPolicyLink . '">Privacy Policy</a>
										</p>
									</td>
								</tr>';
        $button_data = '';
        if ($this->reservationDetails->payment["payment_method"] == "chequemoney") {
            $button_data = "chequemoney";
        } elseif ($this->reservationDetails->payment["payment_method"] == "paypal") {
            $button_data = "paypal";
        }
        $html .= '
							</tbody>
						</table>
					</div>
					<input type="hidden" name="id" value="' . $raId . '"/>

					<button id="finalbutton" data-payment="' . $button_data . '" class="btn btn-large btn-primary" id="" type="submit" disabled="disabled">
						<i class="icon-checkmark"></i>
						' . JText::_("SR_BUTTON_RESERVATION_FINAL_SUBMIT") . '
					</button>
					' . JHtml::_("form.token") . '
				</form>
			</div>
		';
        echo $html;
        die(1);
    }
Esempio n. 22
0
 /**
  * Get price of a room type from a list of room type's tariff that matches the conditions:
  * 		Customer group
  * 		Checkin && Checkout date
  *
  * @param   int      $reservationAssetId
  * @param   int      $roomTypeId
  * @param   bool     $defaultPrice
  * @param   bool     $dateConstraint
  * @param   string   $checkin
  * @param   string   $checkout
  * @param   int      $currencyId The currency id to calculate
  * @param   array    $coupon An array of coupon information
  *
  * @return  array    An array of SRCurrency for Tax and Without Tax
  */
 public function getPrice($reservationAssetId, $roomTypeId, $defaultPrice = false, $dateConstraint = false, $checkin = '', $checkout = '', $currencyId, $coupon = NULL)
 {
     JModelLegacy::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . '/models', 'SolidresModel');
     JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR . '/tables', 'SolidresTable');
     // TODO replace this manual call with autoloading later
     JLoader::register('SRCurrency', SRPATH_LIBRARY . '/currency/currency.php');
     $user = JFactory::getUser();
     $customerModel = JModelLegacy::getInstance('Customer', 'SolidresModel', array('ignore_request' => true));
     $tariffModel = JModelLegacy::getInstance('Tariff', 'SolidresModel', array('ignore_request' => true));
     $srCoupon = SRFactory::get('solidres.coupon.coupon');
     $taxesModel = JModelLegacy::getInstance('Taxes', 'SolidresModel', array('ignore_request' => true));
     $totalBookingCost = 0;
     $taxesModel->setState('filter.reservation_asset_id', $reservationAssetId);
     $imposedTaxTypes = $taxesModel->getItems();
     if (empty($user->id)) {
         $customerGroupId = NULL;
     } else {
         $customer = $customerModel->getItem(array('user_id' => $user->id));
         $customerGroupId = $customer ? $customer->customer_group_id : NULL;
     }
     $tariffModel->setState('filter.room_type_id', $roomTypeId);
     $tariffModel->setState('filter.customer_group_id', $customerGroupId);
     if ($defaultPrice) {
         $tariffModel->setState('filter.default_price', 1);
         // If we need to get the default price, set customer group to 'NONE'
         $tariffModel->setState('filter.customer_group_id', NULL);
     }
     $bookWeekDays = $this->calculateWeekDay($checkin, $checkout);
     if ($dateConstraint) {
         $tariffModel->setState('filter.date_constraint', 1);
     }
     $isCouponApplicable = false;
     if (isset($coupon) && is_array($coupon)) {
         $isCouponApplicable = $srCoupon->isApplicable($coupon['coupon_id'], $roomTypeId);
     }
     $nightCount = 1;
     $tariffBreakDown = array();
     foreach ($bookWeekDays as $bookWeekDay) {
         $theDay = new DateTime($bookWeekDay);
         $dayInfo = getdate($theDay->format('U'));
         // We calculate per nights, not per day, for example 2011-08-24 to 2012-08-29 is 6 days but only 5 nights
         if ($nightCount < count($bookWeekDays)) {
             if ($dateConstraint) {
                 // Reset these state because we may override it in other steps
                 $tariffModel->setState('filter.date_constraint', 1);
                 $tariffModel->setState('filter.default_price', NULL);
                 $tariffModel->setState('filter.customer_group_id', $customerGroupId);
                 $tariffModel->setState('filter.bookday', JFactory::getDate($bookWeekDay)->toSql());
             }
             $bookWeekDayTariffs = $tariffModel->getItems();
             // Advanced / Complex Tariff : each price for each week day
             if (count($bookWeekDayTariffs) > 1) {
                 $single = false;
             } else {
                 if (count($bookWeekDayTariffs) == 1) {
                     $single = true;
                 } else {
                     if (count($bookWeekDayTariffs) == 0) {
                         $tariffModel->setState('filter.date_constraint', NULL);
                         $tariffModel->setState('filter.default_price', 1);
                         // If we need to get the default price, set customer group to 'NONE'
                         $tariffModel->setState('filter.customer_group_id', NULL);
                         $bookWeekDayTariffs = $tariffModel->getItems();
                         // Advanced / Complex Tariff : each price for each week day
                         if (count($bookWeekDayTariffs) > 1) {
                             $single = false;
                         } else {
                             if (count($bookWeekDayTariffs) == 1) {
                                 $single = true;
                             }
                         }
                     }
                 }
             }
             // Deal with Coupon
             if ($isCouponApplicable) {
                 $result = $this->calculateCostPerDay($bookWeekDayTariffs, $dayInfo, $single, $coupon);
             } else {
                 $result = $this->calculateCostPerDay($bookWeekDayTariffs, $dayInfo, $single, NULL);
             }
             $totalBookingCost += $result['total_booking_cost'];
             $tariffBreakDown += $result['tariff_break_down'];
         }
         $nightCount++;
     }
     if ($totalBookingCost > 0) {
         // Calculate the imposed tax amount
         $totalImposedTaxAmount = 0;
         foreach ($imposedTaxTypes as $taxType) {
             $totalImposedTaxAmount += $totalBookingCost * $taxType->rate;
         }
         $totalBookingCostTaxed = $totalBookingCost + $totalImposedTaxAmount;
         // Format the number with correct currency
         $totalBookingCostExcludedTaxedFormatted = new SRCurrency($totalBookingCost, $currencyId);
         // Format the number with correct currency
         $totalBookingCostIncludedTaxFormatted = new SRCurrency($totalBookingCostTaxed, $currencyId);
         // Format tariff break down
         $tariffBreakDownFormatted = array();
         foreach ($tariffBreakDown as $day => $priceOfDay) {
             $tariffBreakDownFormatted[$day] = new SRCurrency($priceOfDay, $currencyId);
         }
         $response = array('total_price_formatted' => $totalBookingCostIncludedTaxFormatted, 'total_price_tax_incl_formatted' => $totalBookingCostIncludedTaxFormatted, 'total_price_tax_excl_formatted' => $totalBookingCostExcludedTaxedFormatted, 'total_price' => $totalBookingCostTaxed, 'total_price_tax_incl' => $totalBookingCostTaxed, 'total_price_tax_excl' => $totalBookingCost, 'tariff_break_down' => $tariffBreakDownFormatted, 'is_applied_coupon' => $result['is_applied_coupon']);
         return $response;
     } else {
         return NULL;
     }
 }