Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/vikbooking/admin/controller.php
+++ b/vikbooking/admin/controller.php
@@ -8169,6 +8169,9 @@
$porphanscal = $porphanscal == 'prevnext' ? 'prevnext' : 'next';
$config->set('orphanscalculation', $porphanscal);
+ // booking details link expiration days
+ $config->set('exp_book_revoke_access_days', max(0, VikRequest::getInt('exp_book_revoke_access_days', 7, 'request')));
+
$psrcrtpl = VikRequest::getString('srcrtpl', 'compact', 'request');
$config->set('searchrestmpl', $psrcrtpl);
@@ -8694,6 +8697,25 @@
$config->set('split_stay_ratio', ($glob_split_stay && $split_stay_ratio > 0 ? $split_stay_ratio : 0));
/**
+ * Guest media files above the web-root.
+ *
+ * @since 1.18.21 (J) - 1.8.21 (WP)
+ */
+ $mediaAboveRoot = VikRequest::getBool('media_above_root', false, 'request');
+ $config->set('media_above_root', (int) $mediaAboveRoot);
+ if ($mediaAboveRoot) {
+ // attempt to move files above the web-root
+ $webrootFilesMoved = (new VBOModelMediafiles(true))->moveAllFilesAboveWebRoot();
+ } else {
+ // attempt to move files under the web-root
+ $webrootFilesMoved = (new VBOModelMediafiles(true))->moveAllFilesUnderWebRoot();
+ }
+ if ($webrootFilesMoved !== null) {
+ // display successful or erroneous message
+ $app->enqueueMessage(($webrootFilesMoved ? 'Guest media files moved successfully' : 'Could not move guest media files'), ($webrootFilesMoved ? 'success': 'error'));
+ }
+
+ /**
* Re-build Web App manifest file to let the event trigger.
*
* @since 1.16.5 (J) - 1.6.5 (WP)
@@ -9124,64 +9146,121 @@
return $retval;
}
- public function downloadinvoices() {
- $ids = VikRequest::getVar('cid', array(0));
- if (@count($ids) > 0) {
- $dbo = JFactory::getDBO();
- $q = "SELECT * FROM `#__vikbooking_invoices` WHERE `id` IN (".implode(', ', $ids).");";
- $dbo->setQuery($q);
- $dbo->execute();
- if ($dbo->getNumRows() > 0) {
- $invoices = $dbo->loadAssocList();
- if (!(count($invoices) > 1)) {
- //Single Invoice Download
- if (file_exists(VBO_SITE_PATH.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'invoices'.DIRECTORY_SEPARATOR.'generated'.DIRECTORY_SEPARATOR.$invoices[0]['file_name'])) {
- header("Content-type:application/pdf");
- header("Content-Disposition:attachment;filename=".$invoices[0]['file_name']);
- readfile(VBO_SITE_PATH.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'invoices'.DIRECTORY_SEPARATOR.'generated'.DIRECTORY_SEPARATOR.$invoices[0]['file_name']);
- exit;
- }
- } else {
- //Multiple Invoices Download
- $to_zip = array();
- foreach ($invoices as $k => $invoice) {
- $to_zip[$k]['name'] = $invoice['file_name'];
- $to_zip[$k]['path'] = VBO_SITE_PATH.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'invoices'.DIRECTORY_SEPARATOR.'generated'.DIRECTORY_SEPARATOR.$invoice['file_name'];
- }
- if (class_exists('ZipArchive')) {
- $zip_path = VBO_SITE_PATH.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'invoices'.DIRECTORY_SEPARATOR.'generated'.DIRECTORY_SEPARATOR.date('Y-m-d').'-invoices.zip';
- $zip = new ZipArchive;
- $zip->open($zip_path, ZipArchive::CREATE);
- foreach ($to_zip as $k => $zipv) {
- $zip->addFile($zipv['path'], $zipv['name']);
- }
- $zip->close();
- header("Content-type:application/zip");
- header("Content-Disposition:attachment;filename=".date('Y-m-d').'-invoices.zip');
- header("Content-Length:".filesize($zip_path));
- readfile($zip_path);
- unlink($zip_path);
- exit;
- } else {
- //Class ZipArchive does not exist
- VikError::raiseWarning('', 'Class ZipArchive does not exist on your server. Download the files one by one.');
- }
- }
- }
+ public function downloadinvoices()
+ {
+ if (!JSession::checkToken() && !JSession::checkToken('get')) {
+ VBOHttpDocument::getInstance()->close(403, JText::translate('JINVALID_TOKEN'));
}
- $mainframe = JFactory::getApplication();
- $mainframe->redirect("index.php?option=com_vikbooking&task=invoices");
- }
- public function resendinvoices() {
- $ids = VikRequest::getVar('cid', array(0));
- $mainframe = JFactory::getApplication();
- if (!(count($ids) > 0)) {
- $mainframe->redirect("index.php?option=com_vikbooking&task=invoices");
+ if (!JFactory::getUser()->authorise('core.vbo.management', 'com_vikbooking')) {
+ VBOHttpDocument::getInstance()->close(403, JText::translate('JERROR_ALERTNOAUTHOR'));
+ }
+
+ $app = JFactory::getApplication();
+ $dbo = JFactory::getDbo();
+
+ $ids = array_map('intval', (array) VikRequest::getVar('cid', []));
+ if (!$ids) {
+ $app->enqueueMessage('Missing invoice ID(s).', 'error');
+ $app->redirect("index.php?option=com_vikbooking&task=invoices");
+ $app->close();
+ }
+
+ $q = "SELECT * FROM `#__vikbooking_invoices` WHERE `id` IN (" . implode(', ', $ids) . ");";
+ $dbo->setQuery($q);
+ $invoices = $dbo->loadAssocList();
+
+ // map invoice records
+ $invoices = array_map(function($invoiceRecord) {
+ // compute invoice path from file name
+ $invoiceRecord['_path'] = (new VBOModelMediafiles)->buildInvoicePath($invoiceRecord['file_name']);
+
+ // return the associative record array
+ return $invoiceRecord;
+ }, $invoices);
+
+ // filter out non-existing invoices
+ $invoices = array_values(array_filter($invoices, function($invoiceRecord) {
+ return is_file($invoiceRecord['_path']);
+ }));
+
+ if (!$invoices) {
+ $app->enqueueMessage('No invoices found.', 'error');
+ $app->redirect("index.php?option=com_vikbooking&task=invoices");
+ $app->close();
+ }
+
+ if (count($invoices) === 1) {
+ // single invoice download
+ header('Content-type: application/pdf');
+ header(
+ 'Content-Disposition: attachment; filename="' . addslashes($invoices[0]['file_name']) . '"; ' .
+ "filename*=UTF-8''" . rawurlencode($invoices[0]['file_name'])
+ );
+ header('X-Content-Type-Options: nosniff');
+ header('Content-Transfer-Encoding: binary');
+ header('Cache-Control: private, no-store, max-age=0');
+ header('Pragma: no-cache');
+
+ readfile($invoices[0]['_path']);
exit;
}
- $dbo = JFactory::getDBO();
- $invoices = array();
+
+ // multiple invoices download
+ if (!class_exists('ZipArchive')) {
+ $app->enqueueMessage('Class ZipArchive does not exist on your server. Download the files one by one.', 'error');
+ $app->redirect("index.php?option=com_vikbooking&task=invoices");
+ $app->close();
+ }
+
+ $to_zip = [];
+ foreach ($invoices as $k => $invoice) {
+ $to_zip[$k]['name'] = $invoice['file_name'];
+ $to_zip[$k]['path'] = $invoice['_path'];
+ }
+
+ $zip_name = date('Y-m-d') . '-invoices.zip';
+ $zip_path = VBO_SITE_PATH.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'invoices'.DIRECTORY_SEPARATOR.'generated'.DIRECTORY_SEPARATOR.$zip_name;
+
+ $zip = new ZipArchive;
+ $zip->open($zip_path, ZipArchive::CREATE);
+ foreach ($to_zip as $k => $zipv) {
+ $zip->addFile($zipv['path'], $zipv['name']);
+ }
+ $zip->close();
+
+ header("Content-type: application/zip");
+ header(
+ 'Content-Disposition: attachment; filename="' . addslashes($zip_name) . '"; ' .
+ "filename*=UTF-8''" . rawurlencode($zip_name)
+ );
+ header("Content-Length:" . filesize($zip_path));
+
+ readfile($zip_path);
+ unlink($zip_path);
+ exit;
+ }
+
+ public function resendinvoices()
+ {
+ if (!JSession::checkToken() && !JSession::checkToken('get')) {
+ VBOHttpDocument::getInstance()->close(403, JText::translate('JINVALID_TOKEN'));
+ }
+
+ if (!JFactory::getUser()->authorise('core.vbo.management', 'com_vikbooking')) {
+ VBOHttpDocument::getInstance()->close(403, JText::translate('JERROR_ALERTNOAUTHOR'));
+ }
+
+ $app = JFactory::getApplication();
+ $dbo = JFactory::getDbo();
+
+ $ids = array_map('intval', (array) VikRequest::getVar('cid', []));
+ if (!$ids) {
+ $app->enqueueMessage('Missing invoice ID(s).', 'error');
+ $app->redirect("index.php?option=com_vikbooking&task=invoices");
+ $app->close();
+ }
+
$q = "SELECT `i`.*,`o`.`custmail`,`c`.`email` AS `customer_email`, CONCAT_WS(' ',`c`.`first_name`,`c`.`last_name`) AS `customer_name`,`c`.`country` AS `customer_country`,`nat`.`country_name` ".
"FROM `#__vikbooking_invoices` AS `i` " .
"LEFT JOIN `#__vikbooking_orders` `o` ON `o`.`id`=`i`.`idorder` " .
@@ -9189,15 +9268,14 @@
"LEFT JOIN `#__vikbooking_countries` `nat` ON `nat`.`country_3_code`=`c`.`country` " .
"WHERE `i`.`id` IN (".implode(', ', $ids).") AND (`i`.`idorder` < 0 OR (`o`.`status`='confirmed' AND `o`.`total` > 0)) ORDER BY `o`.`id` ASC;";
$dbo->setQuery($q);
- $dbo->execute();
- if ($dbo->getNumRows() > 0) {
- $invoices = $dbo->loadAssocList();
- }
- if (!(count($invoices) > 0)) {
- VikError::raiseWarning('', JText::translate('VBOGENINVERRNOBOOKINGS'));
- $mainframe->redirect("index.php?option=com_vikbooking&task=invoices");
- exit;
+ $invoices = $dbo->loadAssocList();
+
+ if (!$invoices) {
+ $app->enqueueMessage(JText::translate('VBOGENINVERRNOBOOKINGS'), 'error');
+ $app->redirect("index.php?option=com_vikbooking&task=invoices");
+ $app->close();
}
+
$tot_generated = 0;
$tot_sent = 0;
foreach ($invoices as $bkey => $invoice) {
@@ -9208,8 +9286,9 @@
$tot_sent++;
}
}
- $mainframe->enqueueMessage(JText::sprintf('VBOTOTINVOICESGEND', $tot_generated, $tot_sent));
- $mainframe->redirect("index.php?option=com_vikbooking&task=invoices");
+
+ $app->enqueueMessage(JText::sprintf('VBOTOTINVOICESGEND', $tot_generated, $tot_sent));
+ $app->redirect("index.php?option=com_vikbooking&task=invoices");
}
public function removeinvoices()
@@ -9218,42 +9297,43 @@
VBOHttpDocument::getInstance()->close(403, JText::translate('JERROR_ALERTNOAUTHOR'));
}
+ $app = JFactory::getApplication();
+ $dbo = JFactory::getDbo();
+
$ids = VikRequest::getVar('cid', array());
$tot_removed = 0;
- $dbo = JFactory::getDbo();
foreach ($ids as $d) {
- $q = "SELECT * FROM `#__vikbooking_invoices` WHERE `id`=".(int)$d.";";
+ $q = "SELECT * FROM `#__vikbooking_invoices` WHERE `id`=" . (int) $d . ";";
$dbo->setQuery($q);
$cur_invoice = $dbo->loadAssoc();
if ($cur_invoice) {
+ // delete invoice file
$invoice_fpath = VBO_SITE_PATH.DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'invoices'.DIRECTORY_SEPARATOR.'generated'.DIRECTORY_SEPARATOR.$cur_invoice['file_name'];
- if (is_file($invoice_fpath)) {
- unlink($invoice_fpath);
- }
- if (VBOPlatformDetection::isWordPress()) {
- /**
- * @wponly - trigger files mirroring for deletion
- */
- VikBookingLoader::import('update.manager');
- VikBookingUpdateManager::triggerDeletionBackup($invoice_fpath);
- }
- $q = "DELETE FROM `#__vikbooking_invoices` WHERE `id`=".(int)$d.";";
+ (new VBOModelMediafiles)->deleteMediaFile($invoice_fpath);
+
+ // delete invoice record
+ $q = "DELETE FROM `#__vikbooking_invoices` WHERE `id`=" . (int) $d . ";";
$dbo->setQuery($q);
$dbo->execute();
+
+ // increase counter
$tot_removed++;
}
}
- $mainframe = JFactory::getApplication();
- $mainframe->enqueueMessage(JText::sprintf('VBOTOTINVOICESRMVD', $tot_removed));
- $mainframe->redirect("index.php?option=com_vikbooking&task=invoices");
+ $app->enqueueMessage(JText::sprintf('VBOTOTINVOICESRMVD', $tot_removed));
+ $app->redirect("index.php?option=com_vikbooking&task=invoices");
}
public function geninvoices()
{
- $dbo = JFactory::getDbo();
+ if (!JSession::checkToken()) {
+ VBOHttpDocument::getInstance()->close(403, JText::translate('JINVALID_TOKEN'));
+ }
+
$app = JFactory::getApplication();
+ $dbo = JFactory::getDbo();
$ids = VikRequest::getVar('cid', array());
@@ -11465,6 +11545,10 @@
public function createcheckindoc()
{
+ if (!JSession::checkToken()) {
+ VBOHttpDocument::getInstance()->close(403, JText::translate('JINVALID_TOKEN'));
+ }
+
if (!JFactory::getUser()->authorise('core.vbo.bookings', 'com_vikbooking')) {
VBOHttpDocument::getInstance()->close(403, JText::translate('JERROR_ALERTNOAUTHOR'));
}
@@ -11472,7 +11556,7 @@
$cid = VikRequest::getVar('cid', array(0));
$id = $cid[0];
- $dbo = JFactory::getDBO();
+ $dbo = JFactory::getDbo();
$mainframe = JFactory::getApplication();
$vbo_tn = VikBooking::getTranslator();
$lang = JFactory::getLanguage();
@@ -11503,36 +11587,38 @@
$vbo_tn::$force_tolang = $row['lang'];
}
}
- $customer = array();
$q = "SELECT `c`.*,`co`.`idorder`,`co`.`signature`,`co`.`pax_data`,`co`.`comments`,`co`.`checkindoc` FROM `#__vikbooking_customers` AS `c` LEFT JOIN `#__vikbooking_customers_orders` `co` ON `c`.`id`=`co`.`idcustomer` WHERE `co`.`idorder`=".$row['id'].";";
$dbo->setQuery($q);
- $dbo->execute();
- if ($dbo->getNumRows() > 0) {
- $customer = $dbo->loadAssoc();
- if (!empty($customer['country'])) {
- if (file_exists(VBO_ADMIN_PATH.DIRECTORY_SEPARATOR.'resources'.DIRECTORY_SEPARATOR.'countries'.DIRECTORY_SEPARATOR.$customer['country'].'.png')) {
- $customer['country_img'] = '<img src="'.VBO_ADMIN_URI.'resources/countries/'.$customer['country'].'.png'.'" title="'.htmlspecialchars($customer['country']).'" class="vbo-country-flag vbo-country-flag-left"/>';
- }
- }
- }
- if (!(count($customer) > 0)) {
+ $customer = $dbo->loadAssoc();
+ if (!$customer) {
VikError::raiseWarning('', JText::translate('VBOCHECKINERRNOCUSTOMER'));
$mainframe->redirect('index.php?option=com_vikbooking&task=newcustomer&checkin=1&bid='.$row['id'].($ptmpl == 'component' ? '&tmpl=component' : ''));
exit;
}
- $customer['pax_data'] = !empty($customer['pax_data']) ? json_decode($customer['pax_data'], true) : array();
+ if (!empty($customer['country'])) {
+ if (file_exists(VBO_ADMIN_PATH.DIRECTORY_SEPARATOR.'resources'.DIRECTORY_SEPARATOR.'countries'.DIRECTORY_SEPARATOR.$customer['country'].'.png')) {
+ $customer['country_img'] = '<img src="'.VBO_ADMIN_URI.'resources/countries/'.$customer['country'].'.png'.'" title="'.htmlspecialchars($customer['country']).'" class="vbo-country-flag vbo-country-flag-left"/>';
+ }
+ }
+ $customer['pax_data'] = !empty($customer['pax_data']) ? (array) json_decode($customer['pax_data'], true) : array();
//check if the signature has been submitted
- $signature_data = '';
$cont_type = '';
+ $signature_data = '';
if (!empty($psignature)) {
- //check whether the format is accepted
- if (strpos($psignature, 'image/png') !== false || strpos($psignature, 'image/jpeg') !== false || strpos($psignature, 'image/svg') !== false) {
- $parts = explode(';base64,', $psignature);
- $cont_type_parts = explode('image/', $parts[0]);
- $cont_type = $cont_type_parts[1];
- if (!empty($parts[1])) {
- $signature_data = base64_decode($parts[1]);
- }
+ /**
+ * Implemented safe filtering of base64-encoded signature image
+ * to obtain content and file extension.
+ *
+ * @since 1.15.1 (J) - 1.5.4 (WP)
+ */
+ if (preg_match("/^data:image/(png|jpe?g|svg);base64,([A-Za-z0-9/=+]+)$/", $psignature, $safe_match)) {
+ /**
+ * Validate and sanitize signature image data for the accepted PNG, JPG, SVG formats.
+ *
+ * @since 1.18.21 (J) - 1.8.21 (WP)
+ */
+ $cont_type = (string) $safe_match[1];
+ $signature_data = VikBooking::sanitizeImageBytes((string) base64_decode($safe_match[2]), $cont_type);
}
}
if (!empty($signature_data)) {
@@ -11553,27 +11639,23 @@
$new_width = floor(($ppad_width / 2));
$creativik = new vikResizer();
$creativik->proportionalImage($filepath, $filepath, $new_width, $new_width);
- } else {
+ } elseif (VBOPlatformDetection::isWordPress()) {
/**
* @wponly - trigger files mirroring
*/
VikBookingLoader::import('update.manager');
VikBookingUpdateManager::triggerUploadBackup($filepath);
- //
}
- //
} else {
VikError::raiseWarning('', JText::translate('VBOERRSTORESIGNFILE'));
}
}
//
//generate PDF for check-in document by parsing the apposite template file
- $booking_rooms = array();
$q = "SELECT `or`.*,`r`.`name` AS `room_name`,`r`.`fromadult`,`r`.`toadult` FROM `#__vikbooking_ordersrooms` AS `or` LEFT JOIN `#__vikbooking_rooms` `r` ON `r`.`id`=`or`.`idroom` WHERE `or`.`idorder`=".(int)$row['id'].";";
$dbo->setQuery($q);
- $dbo->execute();
- if ($dbo->getNumRows() > 0) {
- $booking_rooms = $dbo->loadAssocList();
+ $booking_rooms = $dbo->loadAssocList();
+ if ($booking_rooms) {
if (!empty($row['lang'])) {
$vbo_tn->translateContents($booking_rooms, '#__vikbooking_rooms', array('id' => 'idroom', 'room_name' => 'name'), array(), $row['lang']);
}
@@ -11637,18 +11719,21 @@
$dbo->setQuery($q);
$dbo->execute();
$mainframe->enqueueMessage(JText::translate('VBOGENCHECKINDOCSUCCESS'));
+
/**
- * @wponly - trigger files mirroring
+ * Handle generated guest media file.
+ *
+ * @since 1.18.21 (J) - 1.8.21 (WP)
*/
- VikBookingLoader::import('update.manager');
- VikBookingUpdateManager::triggerUploadBackup($pathpdf);
- //
+ (new VBOModelMediafiles)->moveMediaFile($pathpdf);
+ }
+
+ if (VBOPlatformDetection::isWordPress()) {
+ // task is executed via ajax for the Modal forms listener. We cannot redirect to tmpl=component
+ $mainframe->redirect('index.php?option=com_vikbooking&task=bookingcheckin&cid[]='.$row['id']);
+ } else {
+ $mainframe->redirect('index.php?option=com_vikbooking&task=bookingcheckin&cid[]='.$row['id'].($ptmpl == 'component' ? '&tmpl=component' : ''));
}
- //
- /**
- * @wponly - this task is executed via Ajax for the Modal forms listener. We cannot redirect to tmpl=component
- */
- $mainframe->redirect('index.php?option=com_vikbooking&task=bookingcheckin&cid[]='.$row['id']);
exit;
}
@@ -11805,7 +11890,7 @@
}
//'checked' status comments
- $q = "UPDATE `#__vikbooking_customers_orders` SET `comments`=".$dbo->quote($pcomments)." WHERE `id`=".$custorder['id'].";";
+ $q = "UPDATE `#__vikbooking_customers_orders` SET `comments`=".$dbo->quote($pcomments)." WHERE `id`=" . (int) $custorder['id'] . ";";
$dbo->setQuery($q);
$dbo->execute();
--- a/vikbooking/admin/controllers/mediafiles.php
+++ b/vikbooking/admin/controllers/mediafiles.php
@@ -0,0 +1,135 @@
+<?php
+/**
+ * @package VikBooking
+ * @subpackage core
+ * @author E4J s.r.l.
+ * @copyright Copyright (C) 2026 E4J s.r.l. All Rights Reserved.
+ * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
+ * @link https://vikwp.com
+ */
+
+// No direct access
+defined('ABSPATH') or die('No script kiddies please!');
+
+/**
+ * VikBooking media-files controller (admin).
+ *
+ * @since 1.18.21 (J) - 1.8.21 (WP)
+ */
+class VikBookingControllerMediafiles extends JControllerAdmin
+{
+ /**
+ * Preparation for displaying or downloading a media file.
+ *
+ * @return void
+ */
+ protected function preflight()
+ {
+ $app = JFactory::getApplication();
+
+ if (!JSession::checkToken('get')) {
+ // missing CSRF-proof token
+ VBOHttpDocument::getInstance($app)->close(403, JText::translate('JINVALID_TOKEN'));
+ }
+
+ if (!JFactory::getUser()->authorise('core.vbo.bookings', 'com_vikbooking')) {
+ VBOHttpDocument::getInstance($app)->close(403, JText::translate('JERROR_ALERTNOAUTHOR'));
+ }
+
+ $mediaType = $app->input->getString('media_type', '');
+ $mediaName = $app->input->getString('media_name', '');
+
+ if (!$mediaType || !$mediaName) {
+ VBOHttpDocument::getInstance($app)->close(400, 'Missing media data.');
+ }
+
+ // clean any buffered output
+ while (ob_get_level()) {
+ ob_end_clean();
+ }
+ }
+
+ /**
+ * Task for displaying inline a guest media file.
+ *
+ * @return void
+ */
+ public function render()
+ {
+ // run preflight
+ $this->preflight();
+
+ $app = JFactory::getApplication();
+
+ // access model
+ $model = new VBOModelMediafiles;
+
+ try {
+ // recover file data
+ $fileData = $model->recoverFileData($app->input->getString('media_type', ''), $app->input->getString('media_name', ''));
+
+ // extract data from list
+ list($filePath, $fileMime, $fileSize, $fileName) = $fileData;
+ } catch (Exception $e) {
+ // propagate the error
+ VBOHttpDocument::getInstance($app)->close($e->getCode(), $e->getMessage());
+ }
+
+ // set necessary headers for rendering the file content (display inline)
+ header('Content-Type: ' . $fileMime);
+ header('Content-Length: ' . $fileSize);
+ header('Content-Disposition: inline; filename="' . rawurlencode($fileName) . '"');
+ if (strpos($fileMime, 'image/') === 0) {
+ header("Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox");
+ }
+ header('X-Content-Type-Options: nosniff');
+ header('Cache-Control: private, no-store, max-age=0');
+ header('Pragma: no-cache');
+
+ readfile($filePath);
+ exit;
+ }
+
+ /**
+ * Task for downloading a guest media file.
+ *
+ * @return void
+ */
+ public function download()
+ {
+ // run preflight
+ $this->preflight();
+
+ $app = JFactory::getApplication();
+
+ // access model
+ $model = new VBOModelMediafiles;
+
+ try {
+ // recover file data
+ $fileData = $model->recoverFileData($app->input->getString('media_type', ''), $app->input->getString('media_name', ''));
+
+ // extract data from list
+ list($filePath, $fileMime, $fileSize, $fileName) = $fileData;
+ } catch (Exception $e) {
+ // propagate the error
+ VBOHttpDocument::getInstance($app)->close($e->getCode(), $e->getMessage());
+ }
+
+ // set necessary headers for forcing the download of the file
+ header('Content-Description: File Transfer');
+ header('Content-Type: ' . $fileMime);
+ header('Content-Length: ' . $fileSize);
+ header(
+ 'Content-Disposition: attachment; filename="' . addslashes($fileName) . '"; ' .
+ "filename*=UTF-8''" . rawurlencode($fileName)
+ );
+ header('X-Content-Type-Options: nosniff');
+ header('Content-Transfer-Encoding: binary');
+ header('Cache-Control: private, no-store, max-age=0');
+ header('Pragma: no-cache');
+
+ readfile($filePath);
+ exit;
+ }
+}
--- a/vikbooking/admin/helpers/einvoicing/drivers/agenzia_entrate.php
+++ b/vikbooking/admin/helpers/einvoicing/drivers/agenzia_entrate.php
@@ -2831,9 +2831,9 @@
}
$pdfpath = VBO_SITE_PATH . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'invoices' . DIRECTORY_SEPARATOR . 'generated' . DIRECTORY_SEPARATOR . $pdfname;
- if (!empty($pdfname) && is_file($pdfpath)) {
- $pdfremoved = true;
- @unlink($pdfpath);
+ if (!empty($pdfname)) {
+ // delete invoice file
+ $pdfremoved = (bool) (new VBOModelMediafiles)->deleteMediaFile($pdfpath);
}
}
--- a/vikbooking/admin/helpers/einvoicing/drivers/mydata_aade.php
+++ b/vikbooking/admin/helpers/einvoicing/drivers/mydata_aade.php
@@ -3007,13 +3007,12 @@
return false;
}
- if (VBOPlatformDetection::isWordPress()) {
- /**
- * @wponly - trigger files mirroring
- */
- VikBookingLoader::import('update.manager');
- VikBookingUpdateManager::triggerUploadBackup($pathpdf);
- }
+ /**
+ * Handle generated guest media file.
+ *
+ * @since 1.18.21 (J) - 1.8.21 (WP)
+ */
+ (new VBOModelMediafiles)->moveMediaFile($pathpdf);
// set the PDF file name at last
$env_fee_data['transmission']['pdf'] = $pdffname;
@@ -3952,9 +3951,9 @@
}
$pdfpath = VBO_SITE_PATH . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'invoices' . DIRECTORY_SEPARATOR . 'generated' . DIRECTORY_SEPARATOR . $pdfname;
- if (!empty($pdfname) && is_file($pdfpath)) {
- $pdfremoved = true;
- @unlink($pdfpath);
+ if (!empty($pdfname)) {
+ // delete invoice file
+ $pdfremoved = (bool) (new VBOModelMediafiles)->deleteMediaFile($pdfpath);
}
}
--- a/vikbooking/admin/helpers/report/es_hospedajes.php
+++ b/vikbooking/admin/helpers/report/es_hospedajes.php
@@ -2750,6 +2750,9 @@
} catch (Exception $e) {
// propagate the error caught
throw new Exception(sprintf('[%s] error: %s', __METHOD__, $e->getMessage()), $e->getCode() ?: 500);
+ } finally {
+ // clean up the report temporary directory to ensure we leave no files on disk
+ JFolder::delete($this->report_tmp_path);
}
// when executed through a cron, store an event in the Notifications Center
@@ -2889,6 +2892,9 @@
} catch (Exception $e) {
// propagate the error caught
throw new Exception(sprintf('[%s] error: %s', __METHOD__, $e->getMessage()), $e->getCode() ?: 500);
+ } finally {
+ // clean up the report temporary directory to ensure we leave no files on disk
+ JFolder::delete($this->report_tmp_path);
}
// when executed through a cron, store an event in the Notifications Center
@@ -3181,6 +3187,9 @@
} catch (Exception $e) {
// propagate the error caught
throw new Exception(sprintf('[%s] error: %s', __METHOD__, $e->getMessage()), $e->getCode() ?: 500);
+ } finally {
+ // clean up the report temporary directory to ensure we leave no files on disk
+ JFolder::delete($this->report_tmp_path);
}
// when executed through a cron, store an event in the Notifications Center
@@ -3256,11 +3265,12 @@
// first off, clean up the report temporary directory to ensure we've got no other files
JFolder::delete($this->report_tmp_path);
- // build the temporary XML file name
- $xml_fname = uniqid('hospedajes_') . '.xml';
+ // build the temporary XML file name and destination path
+ $xml_fname = uniqid('hospedajes_') . bin2hex(random_bytes(4)) . '.xml';
+ $xml_destination = $this->report_tmp_path . DIRECTORY_SEPARATOR . $xml_fname;
// store the XML file internally
- $xml_stored = JFile::write($this->report_tmp_path . DIRECTORY_SEPARATOR . $xml_fname, $data['xml']);
+ $xml_stored = JFile::write($xml_destination, $data['xml']);
if (!$xml_stored) {
throw new Exception('Could not store the XML file internally for the data transmission.', 500);
@@ -3283,6 +3293,10 @@
throw new Exception('Could not read the zip archive containing the XML file into a base64-encoded string for the data transmission.', 500);
}
+ // get rid of the file(s) just read
+ unlink($xml_destination);
+ unlink($zip_destination);
+
// build SOAP message values
$codigo_arrendador = $settings['service_arrendador'] ?? '';
$application_name = $this->software_application_name;
--- a/vikbooking/admin/helpers/report/istat_vit_albergatori.php
+++ b/vikbooking/admin/helpers/report/istat_vit_albergatori.php
@@ -1988,7 +1988,7 @@
JFolder::delete($this->report_tmp_path);
// build the temporary TXT file name
- $txt_fname = uniqid('vitalbergatori_') . '.txt';
+ $txt_fname = uniqid('vitalbergatori_') . bin2hex(random_bytes(4)) . '.txt';
// build the TXT file destination
$txt_destination = $this->report_tmp_path . DIRECTORY_SEPARATOR . $txt_fname;
@@ -2003,6 +2003,9 @@
// read the file into a base64-encoded string
$base64_content = base64_encode(file_get_contents($txt_destination));
+ // get rid of the file just read
+ unlink($txt_destination);
+
return (string) $base64_content;
}
--- a/vikbooking/admin/helpers/src/backup/export/type/full.php
+++ b/vikbooking/admin/helpers/src/backup/export/type/full.php
@@ -197,6 +197,33 @@
];
}
+ /**
+ * Include directories above web-root for guest media files.
+ *
+ * @since 1.18.21 (J) - 1.8.21 (WP)
+ */
+ $guestMediaFilesModel = new VBOModelMediafiles;
+ $aboveWebRootPath = $guestMediaFilesModel->getAboveRootMediaPath();
+ foreach ($guestMediaFilesModel->getFileDirectories() as $mediaId => $mediaDir)
+ {
+ if (!$aboveWebRootPath || !isset($folders[$mediaId]))
+ {
+ // ignore directory
+ continue;
+ }
+
+ // clone under web-root instruction
+ $folderKey = sprintf('%s_awr', $mediaId);
+ $folder = $folders[$mediaId];
+
+ // overwrite folder source path
+ $folder['source'] = JPath::clean($aboveWebRootPath . '/' . $mediaId);
+
+ // set new folder in list
+ $folders[$folderKey] = $folder;
+ }
+
+ // return the associative list of folders to export
return $folders;
}
@@ -219,6 +246,8 @@
'licensekey',
'licenseval',
'licensehash',
+ 'media_above_root',
+ 'media_above_root_path',
],
'vikchannelmanager' => [
'version',
@@ -246,26 +275,34 @@
$q->where($dbo->qn('param') . ' NOT IN (' . implode(',', array_map([$dbo, 'q'], $exclude)) . ')');
}
+ // iterate all settings
$dbo->setQuery($q);
- $dbo->execute();
-
- if ($dbo->getNumRows())
+ foreach ($dbo->loadObjectList() as $row)
{
- // iterate all settings
- foreach ($dbo->loadObjectList() as $row)
- {
- // clear update
- $update->clear('set')->clear('where');
- // define value to set
- $update->set($dbo->qn('setting') . ' = ' . $dbo->q($row->setting));
- // define parameter to update
- $update->where($dbo->qn('param') . ' = ' . $dbo->q($row->param));
+ // clear update
+ $update->clear('set')->clear('where');
+ // define value to set
+ $update->set($dbo->qn('setting') . ' = ' . $dbo->q($row->setting));
+ // define parameter to update
+ $update->where($dbo->qn('param') . ' = ' . $dbo->q($row->param));
- $sql[] = (string) $update;
- }
+ $sql[] = (string) $update;
}
}
+ /**
+ * Always disable guest media files above web-root during import.
+ * When the setting will be re-enabled, guest media files will be
+ * eventually moved to the newly computed above web-root path.
+ *
+ * @since 1.18.21 (J) - 1.8.21 (WP)
+ */
+ $sql[] = (string) $dbo->getQuery(true)
+ ->update($dbo->qn('#__vikbooking_config'))
+ ->set($dbo->qn('setting') . ' = 0')
+ ->where($dbo->qn('param') . ' = ' . $dbo->q('media_above_root'));
+
+ // return the list of queries to execute
return $sql;
}
}
--- a/vikbooking/admin/helpers/src/backup/export/type/management.php
+++ b/vikbooking/admin/helpers/src/backup/export/type/management.php
@@ -98,6 +98,9 @@
unset($folders['checkins']);
unset($folders['invoices']);
unset($folders['idscans']);
+ unset($folders['checkins_awr']);
+ unset($folders['invoices_awr']);
+ unset($folders['idscans_awr']);
unset($folders['customerdocs']);
unset($folders['visualeditor']);
--- a/vikbooking/admin/helpers/src/backup/manager.php
+++ b/vikbooking/admin/helpers/src/backup/manager.php
@@ -27,7 +27,7 @@
*
* @see This should MATCH the E4jConnect constants for the Trial.
*/
- const MINIMUM_REQUIRED_VERSION_JOOMLA = '1.18.6';
+ const MINIMUM_REQUIRED_VERSION_JOOMLA = '1.18.21';
/**
* Indicates the minimum required version while creating a
@@ -38,7 +38,7 @@
*
* @see This should MATCH the E4jConnect constants for the Trial.
*/
- const MINIMUM_REQUIRED_VERSION_WORDPRESS = '1.8.6';
+ const MINIMUM_REQUIRED_VERSION_WORDPRESS = '1.8.21';
/**
* An associative array containing the supported export types, where the
--- a/vikbooking/admin/helpers/src/dooraccess/factory.php
+++ b/vikbooking/admin/helpers/src/dooraccess/factory.php
@@ -723,6 +723,89 @@
}
/**
+ * Tells whether the given booking will go through passcode generation.
+ * The method will NOT check if device passcodes were already generated.
+ * Useful to identify a booking that is not yet eligible for passcode generation.
+ *
+ * @param VBOBookingRegistry $registry The booking registry.
+ *
+ * @return array List of eligible generation type enums, if any.
+ *
+ * @since 1.18.21 (J) - 1.8.21 (WP)
+ */
+ public function willBookingHavePasscodes(VBOBookingRegistry $registry)
+ {
+ if (!$registry->isConfirmed()) {
+ // only confirmed bookings will get passcodes
+ return [];
+ }
+
+ // get the unique list of booked listing ids and subunits
+ $bookedListingSubunits = $registry->getBookedListingSubunits();
+
+ // check if the booking has pre-check-in values
+ $hasPreCheckIn = $registry->hasPreCheckedIn();
+
+ // pool of eligible generation type enumerations
+ $eligibleGenTypes = [];
+
+ // scan the eligible integrations for generating passcodes upon pre-checkin completed
+ // or before the check-in time (not at the time of booking)
+ foreach ($this->loadGeneratingIntegrations(['precheckin', 'checkin']) as $record) {
+ // get the integration provider
+ $integration = $this->getIntegrationProvider($record['provider_alias']);
+ if (!$integration) {
+ // unknown integration provider
+ continue;
+ }
+
+ // inject profile record within the integration provider
+ $integration->setProfileRecord($record);
+
+ // iterate all provider integration devices
+ foreach ($integration->getDevices() as $device) {
+ // get the listing-subunit pairs compatible with the current device
+ $deviceListingUnits = $device->intersectListingUnits($bookedListingSubunits);
+
+ if (!$deviceListingUnits) {
+ // ignore device
+ continue;
+ }
+
+ // ensure this booking was never processed before
+ if ($integration->getBookingAccessProcessed($registry->getID())) {
+ // skip this booking as it was already processed
+ continue;
+ }
+
+ if (($record['gentype'] ?? '') === 'precheckin' && !$hasPreCheckIn) {
+ // this device will get a passcode generated once pre-check-in will be completed
+ $eligibleGenTypes[] = 'precheckin';
+ continue;
+ }
+
+ if (($record['gentype'] ?? '') === 'checkin') {
+ // obtain generation period values
+ list($genNumber, $genOperator) = $integration->getGenerationPeriodValues();
+
+ // obtain expected generation deadline timestamp
+ $deadlineTs = $genNumber > 0 ? strtotime(sprintf('-%d %s', $genNumber, ($genOperator === 'D' ? 'days' : 'hours')), $registry->getProperty('checkin', 0)) : $registry->getProperty('checkin', 0);
+ // give the timestamp a grace period until the end of the targeted hour
+ $deadlineTs = strtotime(date('Y-m-d H:59:59', $deadlineTs));
+
+ if ($deadlineTs >= time()) {
+ // this device will get a passcode when it's time to generate it, according to settings
+ $eligibleGenTypes[] = 'checkin';
+ continue;
+ }
+ }
+ }
+ }
+
+ return $eligibleGenTypes;
+ }
+
+ /**
* Attempts to return a list of associative arrays that include the active passcode string
* value and the device information based on what was generated for a specific booking.
*
@@ -833,6 +916,15 @@
$devicePasscodesSignatures[$passcodeSignature] = ($devicePasscodesSignatures[$passcodeSignature] ?? 0) + 1;
}
+ /**
+ * Trigger event to allow third-party plugins to manipulate the pool of devices and passcodes data found.
+ * Useful to adjust device information, instructions or passcodes format.
+ *
+ * @since 1.18.21 (J) - 1.8.21 (WP)
+ */
+ VBOFactory::getPlatform()->getDispatcher()->trigger('onAfterGetBookingDevicePasscodes', [&$devicePasscodesPool, $registry]);
+
+ // return the list of devices and passcodes data found, if any
return $devicePasscodesPool;
}
--- a/vikbooking/admin/helpers/src/model/mediafiles.php
+++ b/vikbooking/admin/helpers/src/model/mediafiles.php
@@ -0,0 +1,744 @@
+<?php
+/**
+ * @package VikBooking
+ * @subpackage core
+ * @author E4J s.r.l.
+ * @copyright Copyright (C) 2026 E4J s.r.l. All Rights Reserved.
+ * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
+ * @link https://vikwp.com
+ */
+
+// No direct access
+defined('ABSPATH') or die('No script kiddies please!');
+
+/**
+ * VikBooking Media files model.
+ *
+ * @since 1.18.21 (J) - 1.8.21 (WP)
+ */
+final class VBOModelMediafiles
+{
+ /** Whether guests related media files should live above the web-root directory. */
+ private bool $aboveRoot = false;
+
+ /**
+ * Binds the above web-root setting.
+ *
+ * @param bool $forceAbove True for by-passing the configuration setting.
+ */
+ public function __construct(bool $forceAbove = false)
+ {
+ $this->aboveRoot = $forceAbove || VBOFactory::getConfig()->getBool('media_above_root', false);
+
+ if (VBOPlatformDetection::isWordPress()) {
+ VikBookingLoader::import('update.manager');
+ }
+ }
+
+ /**
+ * Returns an associative list of media files that could live above the web-root directory.
+ * The associative list can refer to the actual paths on disk, or to the backup/mirroring paths.
+ *
+ * @param bool $uploadPaths True for the list of actual paths on disk, false for mirroring paths.
+ *
+ * @return array
+ */
+ public function getFileDirectories(bool $uploadPaths = true)
+ {
+ // associative list of directories whose files could live above the web-root
+ $dirPaths = [
+ // upload dir path for the customers check-in documents
+ 'checkins' => VBO_SITE_PATH . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'checkins' . DIRECTORY_SEPARATOR . 'generated',
+ // upload dir path for the invoices in PDF format
+ 'invoices' => VBO_SITE_PATH . DIRECTORY_SEPARATOR . 'helpers' . DIRECTORY_SEPARATOR . 'invoices' . DIRECTORY_SEPARATOR . 'generated',
+ // upload dir path for the scans of the ID/Documents of the customers
+ 'idscans' => VBO_ADMIN_PATH . DIRECTORY_SEPARATOR . 'resources' . DIRECTORY_SEPARATOR . 'idscans',
+ ];
+
+ if ($uploadPaths) {
+ // return the associatve list where files would live on disk
+ return $dirPaths;
+ }
+
+ // media files backup/mirroring directories
+
+ if (VBOPlatformDetection::isWordPress()) {
+ // get the array information of the configured upload directory
+ $cmsUploadDir = wp_upload_dir();
+ if (!$cmsUploadDir || empty($cmsUploadDir['basedir'])) {
+ // fallback onto default paths
+ return $dirPaths;
+ }
+
+ return [
+ // upload dir path for the the customers check-in documents
+ 'checkins' => $cmsUploadDir['basedir'] . DIRECTORY_SEPARATOR . 'vikbooking' . DIRECTORY_SEPARATOR . 'checkins',
+ // upload dir path for the invoices in PDF format
+ 'invoices' => $cmsUploadDir['basedir'] . DIRECTORY_SEPARATOR . 'vikbooking' . DIRECTORY_SEPARATOR . 'invoices',
+ // upload dir path for the scans of the ID/Documents of the customers
+ 'idscans' => $cmsUploadDir['basedir'] . DIRECTORY_SEPARATOR . 'vikbooking' . DIRECTORY_SEPARATOR . 'idscans',
+ ];
+ }
+
+ // fallback onto default paths
+ return $dirPaths;
+ }
+
+ /**
+ * Returns an associative list of media files base URIs.
+ *
+ * @return array
+ */
+ public function getFileBaseUrls()
+ {
+ return [
+ 'checkins' => VBO_SITE_URI . 'helpers/checkins/generated/',
+ 'invoices' => VBO_SITE_URI . 'helpers/invoices/generated/',
+ 'idscans' => VBO_ADMIN_URI . 'resources/idscans/',
+ ];
+ }
+
+ /**
+ * Tells if a media type is supported.
+ *
+ * @param string $mediaType The media type to evaluate.
+ *
+ * @return bool
+ */
+ public function isMediaTypeSupported(string $mediaType)
+ {
+ $fileDirectories = $this->getFileDirectories();
+
+ return isset($fileDirectories[$mediaType]);
+ }
+
+ /**
+ * Returns the above web-root base directory path, if writeable.
+ * Attempts to read the highest top-level directory above the CMS base path.
+ *
+ * @return ?string Writeable directory path or null.
+ */
+ public function getAboveRootBasePath()
+ {
+ if (!$this->aboveRoot) {
+ return null;
+ }
+
+ // rely on user-provided above-root path, which may not be
+ // a parent directory of the web-root or CMS installation base path
+ $customPath = VBOFactory::getConfig()->getString('media_above_root_path', '');
+ if ($customPath && is_dir($customPath) && is_writable($customPath)) {
+ return $customPath;
+ }
+
+ // get CMS base installation path (same value for web requests and CLI/cron, so the result is deterministic)
+ $cmsBasePath = VBOFactory::getPlatform()->getUri()->getAbsolutePath();
+
+ // keep climbing ancestors from CMS base installation path for as long as they are writeable
+ $writable = [];
+ while (true) {
+ // climb ancestor directory
+ $cmsBasePath .= DIRECTORY_SEPARATOR . '..';
+
+ // open_basedir may forbid reading ancestors above the allowed paths, and that's the
+ // expected stop condition - suppress the warning that may be emitted
+ $ancestorPath = @realpath($cmsBasePath);
+ if (!$ancestorPath || !is_dir($ancestorPath) || !is_writable($ancestorPath)) {
+ // break the loop
+ break;
+ }
+
+ // collect existing and writeable ancestor path
+ $writable[] = $ancestorPath;
+
+ if (dirname($ancestorPath) === $ancestorPath) {
+ // filesystem root directory hit, prevent loops
+ break;
+ }
+ }
+
+ // never use the filesystem root directory
+ if ($writable && dirname(end($writable)) === end($writable)) {
+ array_pop($writable);
+ }
+
+ // highest writeable path above the CMS base path, if any
+ $candidate = $writable ? end($writable) : null;
+
+ if (!$candidate) {
+ return null;
+ }
+
+ // when the web-root is known (web requests), refuse a path that is the web-root or lives inside it
+ $rawDocumentRoot = $_SERVER['DOCUMENT_ROOT'] ?? '';
+ $documentRoot = $rawDocumentRoot ? realpath($rawDocumentRoot) : false;
+
+ if ($documentRoot && strpos($candidate . DIRECTORY_SEPARATOR, rtrim($documentRoot, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR) === 0) {
+ // the path is not above the web-root
+ return null;
+ }
+
+ return $candidate;
+ }
+
+ /**
+ * Writes a deny-all .htaccess and an empty index.html onto the given directory, if missing.
+ * The .htaccess is honoured by Apache and LiteSpeed, the index.html prevents directory listings.
+ *
+ * @param string $dirPath The directory to protect.
+ *
+ * @return void
+ */
+ private function protectDirectory(string $dirPath)
+ {
+ $htaccess = $dirPath . DIRECTORY_SEPARATOR . '.htaccess';
+ if (!is_file($htaccess)) {
+ @file_put_contents(
+ $htaccess,
+ "<IfModule mod_authz_core.c>ntRequire all deniedn</IfModule>n<IfModule !mod_authz_core.c>ntOrder deny,allowntDeny from alln</IfModule>n"
+ );
+ }
+
+ $index = $dirPath . DIRECTORY_SEPARATOR . 'index.html';
+ if (!is_file($index)) {
+ @file_put_contents($index, '<html><body bgcolor="#ffffff"></body></html>');
+ }
+ }
+
+ /**
+ * Returns the above web-root media files directory path, if available.
+ *
+ * @param bool $installDirs True to create the required sub-directories.
+ *
+ * @return ?string Writeable media files directory path or null.
+ */
+ public function getAboveRootMediaPath(bool $installDirs = false)
+ {
+ $path = $this->getAboveRootBasePath();
+
+ if (!$path) {
+ return null;
+ }
+
+ $mediaPath = $path . DIRECTORY_SEPARATOR . VBO_ABOVE_ROOT_DIRNAME;
+
+ $justCreated = false;
+
+ if (!is_dir($mediaPath)) {
+ if (!JFolder::create($mediaPath)) {
+ // could not create the directory
+ return null;
+ }
+ $justCreated = true;
+ }
+
+ if (!is_writable($mediaPath)) {
+ // directory is not writeable
+ return null;
+ }
+
+ if ($installDirs || $justCreated) {
+ // defense in depth, in case the directory is reachable through the web server after all
+ $this->protectDirectory($mediaPath);
+ }
+
+ if ($installDirs) {
+ foreach ($this->getFileDirectories() as $mediaType => $mediaUnderRootPath) {
+ // create required sub-directory above the web-root path
+ $dirPath = $mediaPath . DIRECTORY_SEPARATOR . $mediaType;
+ if (!is_dir($dirPath) && !JFolder::create($dirPath)) {
+ // abort on error
+ return null;
+ }
+ }
+ }
+
+ return $mediaPath;
+ }
+
+ /**
+ * Given a path to a media file, attempts to convert it into the above-root path.
+ *
+ * @param string $filePath The initial file path under the web-root directory.
+ *
+ * @return ?string Converted file path above the web-root, or null.
+ */
+ public function convertPath(string $filePath)
+ {
+ // ensure the above-root path is available
+ $mediaPath = $this->getAboveRootMediaPath();
+
+ if (!$mediaPath) {
+ return null;
+ }
+
+ foreach ($this->getFileDirectories() as $mediaType => $mediaUnderRootPath) {
+ // identify if file path contains known guests related data to be moved above the web-root path
+ if (strpos($filePath, $mediaUnderRootPath) !== false) {
+ // match found, build converted file path
+ $convertedPath = $mediaPath . DIRECTORY_SEPARATOR . $mediaType . DIRECTORY_SEPARATOR . basename($filePath);
+ return is_file($convertedPath) ? $convertedPath : null;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Given a path to a media file, attempts to build the URI to render the file above the web-root.
+ *
+ * @param string $filePath The initial file path under the web-root directory.
+ * @param string $client Either "auto", "administrator" or "site" for routing the URI.
+ * @param string $action Either "render" or "download".
+ *
+ * @return ?string URI to render the file from the above the web-root directory, or null.
+ */
+ public function getUriFromPath(string $filePath, string $client = 'auto', string $action = 'download')
+ {
+ // make sure the file is available above the web-root
+ $convertedPath = $this->convertPath($filePath);
+
+ if (!$convertedPath) {
+ return null;
+ }
+
+ $foundMediaName = basename($convertedPath);
+ $foundMediaType = basename(dirname($convertedPath));
+
+ if (!$this->isMediaTypeSupported($foundMediaType)) {
+ return null;
+ }
+
+ $client = in_array($client, ['auto', 'administrator', 'site']) ? $client : 'auto';
+
+ if ($client === 'auto') {
+ $client = JFactory::getApplication()->isClient('site') ? 'site' : 'administrator';
+ }
+
+ $action = in_array($action, ['render', 'download']) ? $action : 'download';
+
+ $uriPlatform = VBOFactory::getPlatform()->getUri();
+
+ if ($client === 'administrator') {
+ // build back-end URI (with CSRF token)
+ $fileUri = $uriPlatform->admin(sprintf('index.php?option=com_vikbooking&task=mediafiles.%s&media_type=%s&media_name=%s', $action, $foundMediaType, $foundMediaName));
+ $fileUri = $uriPlatform->addCSRF($fileUri);
+ } else {
+ // build front-end URI (with expiring transient token)
+ $transientModel = VBOMvcModel::getInstance('transienttoken');
+ $transientToken = $transientModel->generateToken();
+ $saved = $transientModel->save([
+ 'token' => $transientToken,
+ 'scope' => implode('-', [$foundMediaType, $foundMediaName]),
+ 'expiry' => $transientModel->buildExpiryDate(60),
+ ]);
+ if (!$saved) {
+ // could not store the transient token
+ return null;
+ }
+ $fileUri = $uriPlatform->route(sprintf(
+ 'index.php?option=com_vikbooking&view=tinyurl&task=mediafiles.%s&media_type=%s&media_name=%s&tk=%s',
+ $action,
+ $foundMediaType,
+ $foundMediaName,
+ $transientToken
+ ));
+ }
+
+ return $fileUri;
+ }
+
+ /**
+ * Recovers the path and details of a known and existing guest media file.
+ *
+ * @param string $type The media file type (known sub-directory).
+ * @param string $name The media file basename to look for.
+ *
+ * @return array File data list of path, mime, size and name.
+ *
+ * @throws Exception
+ */
+ public function recoverFileData(string $type, string $name)
+ {
+ // ensure the above-root path is available
+ $mediaPath = $this->getAboveRootMediaPath();
+
+ if (!$mediaPath) {
+ throw new Exception('Could not recover path.', 500);
+ }
+
+ // make sure the media type is supported
+ if (!$this->isMediaTypeSupported($type)) {
+ throw new Exception('Invalid media type.', 400);
+ }
+
+ if ($name === '' || preg_match('/[\x00-\x1F]/', $name)) {
+ // empty names or control characters (including null bytes) are never valid
+ throw new Exception('Not found.', 404);
+ }
+
+ // build file path
+ $baseDir = realpath($mediaPath . DIRECTORY_SEPARATOR . $type);
+ $filePath = realpath($mediaPath . DIRECTORY_SEPARATOR . $type . DIRECTORY_SEPARATOR . basename($name));
+
+ if (!$baseDir || !$filePath || !is_file($filePath) || !is_readable($filePath)) {
+ throw new Exception('Not found.', 404);
+ }
+
+ if (strpos($filePath, $baseDir . DIRECTORY_SEPARATOR) !== 0) {
+ // resolved path (i.e. a symlink) escapes the media type directory
+ throw new Exception('Not found.', 404);
+ }
+
+ // list of allowed extensions and related type
+ $allowed = [
+ 'pdf' => 'application/pdf',
+ 'jpg' => 'image/jpeg',
+ 'jpeg' => 'image/jpeg',
+ 'png' => 'image/png',
+ ];
+
+ // get file extension and mime type
+ $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
+ $mime = $allowed[$ext] ?? null;
+
+ if (!$mime) {
+ throw new Exception('Unsupported media type.', 415);
+ }
+
+ // read file size and basename
+ $fileSize = filesize($filePath);
+ $fileName = basename($filePath);
+
+ // return the information of the existing file above the web-root
+ return [
+ $filePath,
+ $mime,
+ $fileSize,
+ $fileName,
+ ];
+ }
+
+ /**
+ * Builds the URL for displaying a known media file.
+ *
+ * @param string $mediaId Supported media identifier.
+ * @param string $fileName The media file name to look for.
+ *
+ * @return string The URL for displaying inline the media file.
+ */
+ public function buildMediaUrl(string $mediaId, string $fileName)
+ {
+ // make sure the media ID is known and file name is not empty
+ if (!$this->isMediaTypeSupported($mediaId) || empty($fileName)) {
+ return '';
+ }
+
+ // build media file base URL and path
+ $baseUrl = $this->getFileBaseUrls()[$mediaId] ?? null;
+ $basePath = $this->getFileDirectories()[$mediaId] ?? null;
+ if (!$baseUrl || !$basePath) {
+ return '';
+ }
+
+ // build fallback (under web-root) URL and path
+ $fallbackUrl = $baseUrl . basename($fileName);
+ $fallbackPath = implode(DIRECTORY_SEPARATOR, [$basePath, basename($fileName)]);
+
+ // ensure the above-root path is available
+ $mediaPath = $this->getAboveRootMediaPath();
+
+ if (!$mediaPath) {
+ // use fallback URL
+ return $fallbackUrl;
+ }
+
+ try {
+ // recover file data
+ $fileData = $this->recoverFileData($mediaId, basename($fileName));
+
+ // extract data from list
+ list($filePath, $fileMime, $fileSize, $fileName) = $fileData;
+ } catch (Exception $e) {
+ // use fallback URL (which may lead to a 404 status code)
+ return $fallbackUrl;
+ }
+
+ // get media file render URL
+ $downloadUrl = $this->getUriFromPath($fallbackPath, 'auto', 'render');
+
+ return $downloadUrl ?: $fallbackUrl;
+ }
+
+ /**
+ * Builds the path for handling a known media file.
+ *
+ * @param string $mediaId Supported media identifier.
+ * @param string $fileName The media file name to look for.
+ *
+ * @return string The path for handling the media file.
+ */
+ public function buildMediaPath(string $mediaId, string $fileName)
+ {
+ // make sure the media ID is known and file name is not empty
+ if (!$this->isMediaTypeSupported($mediaId) || empty($fileName)) {
+ return '';
+ }
+
+ // build media file base path
+ $basePath = $this->getFileDirectories()[$mediaId] ?? null;
+ if (!$basePath) {
+ return '';
+ }
+
+ // build fallback (under web-root) path
+ $fallbackPath = implode(DIRECTORY_SEPARATOR, [$basePath, basename($fileName)]);
+
+ // ensure the above-root path is available
+ $mediaPath = $this->getAboveRootMediaPath();
+
+ if (!$mediaPath) {
+ // use fallback path
+ return $fallbackPath;
+ }
+
+ try {
+ // recover file data
+ $fileData = $this->recoverFileData($mediaId, basename($fileName));
+
+ // extract data from list
+ list($filePath, $fileMime, $fileSize, $fileName) = $fileData;
+ } catch (Exception $e) {
+ // use fallback path (which may lead to a 404 status code)
+ return $fallbackPath;
+ }
+
+ // return the validated file path above web-root
+ return $filePath;
+ }
+
+ /**
+ * Builds the URL for displaying an invoice.
+ *
+ * @param string $invoiceFileName The invoice record file name.
+ *
+ * @return string The URL for displaying inline the invoice.
+ */
+ public function buildInvoiceUrl(string $invoiceFileName)
+ {
+ return $this->buildMediaUrl('invoices', $invoiceFileName);
+ }
+
+ /**
+ * Builds the path for handling an invoice file.
+ *
+ * @param string $invoiceFileName The invoice record file name.
+ *
+ * @return string The path for handling the invoice.
+ */
+ public function buildInvoicePath(string $invoiceFileName)
+ {
+ return $this->buildMediaPath('invoices', $invoiceFileName);
+ }
+
+ /**
+ * Given a file path under the web-root directory, detects whether this
+ * should be moved onto the above web-root media files directory.
+ *
+ * @param string $filePath The file path to disk that may be moved above the web-root.
+ * @param bool $unlinkFile True for not keeping a copy of the moved file under the web-root.
+ *
+ * @return bool True if the media file needed to be moved, and if it was moved successfully.
+ */
+ public function moveMediaFile(string $filePath, bool $unlinkFile = true)
+ {
+ if (!is_file($filePath)) {
+ // do not proceed
+ return false;
+ }
+
+ // ensure the above-root path is available
+ $mediaPath = $this->getAboveRootMediaPath(true);
+
+ if (!$mediaPath) {
+ // fallback onto CMS related operations
+ if (VBOPlatformDetection::isWordPress()) {
+ // trigger (legacy) files mirroring
+ return (bool) VikBookingUpdateManager::triggerUploadBackup($filePath);
+ }
+
+ // do nothing otherwise
+ return false;
+ }
+
+ // initial file moving flag
+ $fileMoved = false;
+
+ foreach ($this->getFileDirectories() as $mediaType => $mediaUnderRootPath) {
+ // identify if file path contains known guests related data to be moved above the web-root path
+ if (strpos($filePath, $mediaUnderRootPath) !== false) {
+ // match found, move file above the web-root
+ $fileMoved = JFile::copy($filePath, $mediaPath . DIRECTORY_SEPARATOR . $mediaType . DIRECTORY_SEPARATOR . basename($filePath));
+ break;
+ }
+ }
+
+ if ($fileMoved && $unlinkFile) {
+ // delete disk copy
+ unlink($filePath);
+ }
+
+ return (bool) $fileMoved;
+ }
+
+ /**
+ * Attempts to moves all guest media files above the web-root directory.
+ *
+ * @return ?bool True on success, false on error, null if operation did nothing.
+ */
+ public function moveAllFilesAboveWebRoot()
+ {
+ // ensure the above-root path is available
+ $aboveRootPath = $this->getAboveRootMediaPath(true);
+
+ if (!$aboveRootPath) {
+ // this is an error
+ return false;
+ }
+
+ $filesInvolved = 0;
+
+ foreach ($this->getFileDirectories() as $mediaType => $mediaPath) {
+ // read all media files under the current directory (under the web-root)
+ $files = JFolder::files($mediaPath, '.(pdf|jpe?g|png)$', $recursive = false, $fullpath = true);
+ foreach ($files as $copyFile) {
+ $fileMoved = JFile::copy($copyFile, $aboveRootPath . DIRECTORY_SEPARATOR . $mediaType . DIRECTORY_SEPARATOR . basename($copyFile));
+ if ($fileMoved) {
+ // increase counter
+ $filesInvolved++;
+ // delete copied file from under the web-root directory
+ unlink($copyFile);
+ if (VBOPlatformDetection::isWordPress()) {
+ // trigger (legacy) files mirroring for deletion
+ VikBookingUpdateManager::triggerDeletionBackup($copyFile);
+ }
+ }
+ }
+ }
+
+ // return true only if some files were moved
+ return