<?php
// BEGIN PHP File wrapper.php - DO NOT MODIFY - It is just a copy of wrapper.html sample.
$websitekey=basename(dirname(__FILE__));
if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load master if not already loaded
include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';

$encoding = '';
$hashp=GETPOST('hashp','aZ09');
$modulepart=GETPOST('modulepart','aZ09');
$entity=GETPOST('entity','int')?GETPOST('entity','int'):$conf->entity;
$original_file=GETPOST("file","alpha");

// If we have a hash public (hashp), we guess the original_file.
if (! empty($hashp))
{
	include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
	$ecmfile=new EcmFiles($db);
	$result = $ecmfile->fetch(0, '', '', '', $hashp);
	if ($result > 0)
	{
		$tmp = explode('/', $ecmfile->filepath, 2);		// $ecmfile->filepath is relative to document directory
		// filepath can be 'users/X' or 'X/propale/PR11111'
		if (is_numeric($tmp[0])) // If first tmp is numeric, it is subdir of company for multicompany, we take next part.
		{
			$tmp = explode('/', $tmp[1], 2);
		}
		$moduleparttocheck = $tmp[0];	// moduleparttocheck is first part of path

		if ($modulepart)	// Not required, so often not defined, for link using public hashp parameter.
		{
			if ($moduleparttocheck == $modulepart)
			{
				// We remove first level of directory
				$original_file = (($tmp[1]?$tmp[1].'/':'').$ecmfile->filename);		// this is relative to module dir
				//var_dump($original_file); exit;
			}
			else
			{
				print 'Bad link. File is from another module part.';
			}
		}
		else
		{
			$modulepart = $moduleparttocheck;
			$original_file = (($tmp[1]?$tmp[1].'/':'').$ecmfile->filename);		// this is relative to module dir
		}
	}
	else
	{
		print "ErrorFileNotFoundWithSharedLink";
		exit;
	}
}

// Define attachment (attachment=true to force choice popup 'open'/'save as')
$attachment = true;
if (preg_match('/\.(html|htm)$/i',$original_file)) $attachment = false;
if (isset($_GET["attachment"])) $attachment = GETPOST("attachment",'none')?true:false;
if (! empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS_WEBSITE)) $attachment=false;

// Define mime type
$type = 'application/octet-stream';
if (GETPOST('type','none')) $type=GETPOST('type','alpha');
else $type=dol_mimetype($original_file);

// Security: Delete string ../ into $original_file
$original_file=str_replace("../","/", $original_file);

// Cache or not
if (GETPOST("cache",'none') || image_format_supported($original_file) >= 0)
{
    // Important: Following code is to avoid page request by browser and PHP CPU at
    // each Dolibarr page access.
    header('Cache-Control: max-age=3600, public, must-revalidate');
    header('Pragma: cache');       // This is to avoid having Pragma: no-cache
}

// Find the subdirectory name as the reference
$refname=basename(dirname($original_file)."/");

if ($_GET["modulepart"] == "mycompany" && preg_match('/^\/?logos\//', $original_file)) 
{
	readfile(dol_osencode($conf->mycompany->dir_output."/".$original_file));
}
else 
{
	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
	$check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $refname);
	$accessallowed              = $check_access['accessallowed'];
	$sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
	$fullpath_original_file     = $check_access['original_file'];               // $fullpath_original_file is now a full path name
	if (! empty($_GET["hashp"]))
	{
		$accessallowed = 1;					// When using hashp, link is public so we force $accessallowed
		$sqlprotectagainstexternals = '';
	}
	
	// Security:
	// Limit access if permissions are wrong
	if (! $accessallowed)
	{
		print 'Access forbidden';
		exit;
	}

	clearstatcache();

	$filename = basename($fullpath_original_file);

	// Output file on browser
	dol_syslog("wrapper.php download $fullpath_original_file filename=$filename content-type=$type");
	$fullpath_original_file_osencoded=dol_osencode($fullpath_original_file);	// New file name encoded in OS encoding charset

	// This test if file exists should be useless. We keep it to find bug more easily
	if (! file_exists($fullpath_original_file_osencoded))
	{
		print "ErrorFileDoesNotExists: ".$original_file;
		exit;
	}

	// Permissions are ok and file found, so we return it
	//top_httphead($type);
	header('Content-Type: '.$type);
	header('Content-Description: File Transfer');
	if ($encoding)   header('Content-Encoding: '.$encoding);
	// Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open)
	if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"');
	else header('Content-Disposition: inline; filename="'.$filename.'"');
	header('Content-Length: ' . dol_filesize($fullpath_original_file));

	readfile($fullpath_original_file_osencoded);
}
if (is_object($db)) $db->close();
// END PHP ?>
