<?php
/**
 * Library module
 * 
 * Download file script used for workgroup user. 
 * Can also be used from other modules and plugins
 * 
 * @package linea21\core\library
 * @author $Author$ - Simon Georget <simon@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

include_once('../config/define.php');
session_start();

//////////// Check Droits utilisateur ////////////
if (!$l21auth->isAuthenticated()) ReloadIndex('public');
if (is_numeric(strpos($_REQUEST['file'], 'plugins/l21_')) && !$l21auth->isSuperAdmin()) ReloadIndex('public');
////////////

// we log the action
logfile(LOG_MAINFILE, array('File download', $_REQUEST['file'], $l21auth->GetSessionElement('login'), $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING'], get_referer(), $_SERVER['HTTP_COOKIE'], i2c_realip()));

$file = str_replace('//', '/', SITE_PATH . '/' . $_REQUEST['file']);

$allowed_folders = array(SITE_PATH . 'plugins/', SITE_PATH . 'library/userfiles/');
$allowed = array();

// we check if download is allowed from given folder
foreach($allowed_folders as $folder) {
	
	if(Stringy\Stringy::create($file, CHARSET)->startsWith($folder)) {
		array_push($allowed, 1);
	} else {
		array_push($allowed, 0);
	}

}
// if folder is not allowed, we exit
if(!in_array(1, $allowed)) die('no way!');


if (file_exists($file)) {
  // default type
  $m = 'application/octet-stream';
  if(function_exists('finfo_file')) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $m = finfo_file($finfo, $file);
    $m = mime_content_type($file);
    finfo_close($finfo);
  } else {
    if(function_exists('mime_content_type')) $m = mime_content_type($file);
  }

  header('Content-Description: File Transfer');
  header('Content-Type: '.$m);
  header('Content-Disposition: attachment; filename='.basename($file));
  header('Content-Transfer-Encoding: binary');
  header('Expires: 0');
  header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  header('Pragma: public');
  header('Content-Length: ' . filesize($file));
  ob_clean();
  flush();
  readfile($file);
  exit;
}
?>