<?php

require_once('../initialize/initialize.php');

//#### Liitetään luokkakirjastot
require_once(CLASS_CORE_PATH.'dummy.class.php');
require_once(CLASS_CORE_PATH.'session.class.php');
require_once(CLASS_CORE_PATH.'errorhandler.class.php');
require_once(CLASS_CORE_PATH.'usermanager.class.php');
require_once(CLASS_CORE_PATH.'rowtreeparser.class.php');
require_once(CLASS_CORE_PATH.'query.class.php');
require_once(CLASS_CORE_PATH.'rowlist.class.php');
require_once(CLASS_CORE_PATH.'filelist.class.php');
require_once(CLASS_CORE_PATH.'videolist.class.php');
require_once(CLASS_CORE_PATH.'tempfile.class.php');
require_once(CLASS_CORE_PATH.'stack.class.php');
require_once(CLASS_CORE_PATH.'errorhandler.class.php');
require_once(CLASS_CORE_PATH.'setting.class.php');
require_once(CLASS_CORE_PATH.'urlparser.class.php');

require_once(CLASS_CORE_PATH.'debug.class.php');

require_once(CLASS_APP_PATH.'resource_user.class.php');
require_once(CLASS_APP_PATH.'resource_product.class.php');
require_once(CLASS_APP_PATH.'resource_point.class.php');


function get_http_mdate($lFile) {

	return gmdate("D, d M Y H:i:s", mktime(substr($lFile->row->mod_time, 11, 2), substr($lFile->row->mod_time, 14, 2),
		substr($lFile->row->mod_time, 17, 2), substr($lFile->row->mod_time, 5, 2), substr($lFile->row->mod_time, 8, 2),
		substr($lFile->row->mod_time, 0, 4)))." GMT";
}


function check_modified_header($lFile) {

	$headers = apache_request_headers();
	$gmtime  = get_http_mdate($lFile);

	// Tarkastetaan onko asiakkaan tiedosto ajantasalla
	if (isset($headers['If-Modified-Since']) && ($headers['If-Modified-Since'] == $gmtime)) {
		$expires = 60 * 60 * 24 * 30;
		header("Cache-Control: public, max-age={$expires}");
		header('Last-Modified: '.$gmtime, true, 304);
		exit();
	} else {
		$expires = 60 * 60 * 24 * 30;
		$exp_gmt = gmdate("D, d M Y H:i:s", time() + $expires )." GMT";
		header("Cache-Control: public, max-age={$expires}");
		header("Expires: {$exp_gmt}");
		header('Last-Modified: '.$gmtime, true, 200);
		return;
	}
}


//#### Start session
session_name(SESSION_NAME);
session_start();


$session      = new Session;
$userManager  = new UserManager;
$errorHandler = new ErrorHandler;
$urlparser    = new urlparser();

// #######################################

$tDir     = new rowTreeParser('sys_doc_dir');
$aRequest = $urlparser->getArray();
$request  = new Dummy;

/* Tehdään oikeanmallinen request-olio */
foreach ($aRequest as $key=>$value){
	$request->$key = $value;
}

/* Request talteen, jotta jos virhe syntyy kirjautumisessa niin tiedetään mitä yritettiin tehdä */
if (strpos($request->action,'login')  === false &&
	strpos($request->action,'error')  === false)
	$session->setVar('currentRequest',$request);


/* Haetaan normaalia tiedostoa */
if ($request->fid){
	$lFile = new fileList();
	$lFile->first('id = '.$request->fid);

	$mode = 'file';
}

/* Haetaan videotiedostoa */
elseif ($request->vid){
	$lFile = new VideoList;
	$lFile->first('id = '.$request->vid);

	$mode = 'video';
}
else
	$errorHandler->throwError('default','Ei riittäviä tietoja toiminnon suorittamiseen.','error');



if ($lFile->fetch()){

	/* Luodaan käyttäjä, jotta voidaan tarkastaa oikeudet kansioon */
	$user = new Dummy;
	$user = $userManager->login($session->getVar('user'));

	if (!$user) {
		echo "Error: no logged user";
	}


	/* Cachetetaan oikeustarkastuksia */
	if ($mode == 'file')
		$aDirCache = $session->getVar('action/binary/file#aDirCache');
	else
		$aDirCache = $session->getVar('action/binary/video#aDirCache');


	if ($aDirCache[$lFile->row->dir_id]) {
		$path = $aDirCache[$lFile->row->dir_id];
	}
	else {
		$tDir->setStartNode($lFile->row->dir_id);
		$path = $tDir->parsePath();
		$aDirCache[$lFile->row->dir_id] = $path;

		if ($mode == 'file')
			$session->setVar('action/binary/file#aDirCache', $aDirCache);
		else
			$session->setVar('action/binary/video#aDirCache', $aDirCache);
	}

	// Rakennetaan oikea tarkastuspolku
	if ($mode == 'file')
		$checkPath = 'sitedoc/view'.$path;
	else
		$checkPath = 'sitevideo/view'.$path;


	/* Tarkastetaan oikeudet tiedoston kansioon */
	if ($userManager->check($checkPath)) {

		if ($request->action == 'binary/file'){
			$size = $lFile->getFileSize();
			$mime = $lFile->row->type;
			$fileName = $lFile->getNameAscii();
			
			// Korjataan piste- ja välilyöntivirheet tiedostonimestä
			$fileName = preg_replace('/ /', '_', $fileName);
			$dotcount = substr_count($fileName,'.');
			
			if ($dotcount > 1){
				$fileName = preg_replace('/\./', '_', $fileName, $dotcount - 1);
			}
			
			check_modified_header($lFile);
			header("Content-Type: ".$mime);

			if (strpos($mime,'x-shockwave-flash') !== false )
				header("Content-Disposition: inline; filename=".$fileName);
			elseif (strpos($mime,'application/pdf') !== false && $request->force != 'download')
				header("Content-Disposition: inline; filename=".$fileName);
			elseif (substr($mime, 0, 5) != 'image' || strpos($mime,'pdf') !== false || $request->force == 'download')
				header("Content-Disposition: attachment; filename=".$fileName);

			if ($size)
				header("Content-Length: ".$size);

			print_r($lFile->getData());
		}
		elseif ($request->action == 'binary/image/thumbnailer'){

			/* Thumbnailin oletus koko */
			$width  = $request->width;;
			$height = $request->height;

			if ($width == '' && $height == '')
				$width = 100;


			if($request->clip == 'clip' && (intval($request->pos) || $request->pos == 'auto')){
				$content = $lFile->getThumb($width, $height, $request->clip, $request->pos);
			}
			elseif($request->clip == 'clip'){
				$content = $lFile->getThumb($width, $height, $request->clip);
			}
			else{
				$content = $lFile->getThumb($width, $height);
			}

			$size = strlen($content);
			$mime = $lFile->row->type;
			$fileName = $lFile->getNameAscii();

			check_modified_header($lFile);
			header("Content-Length: " . $size);
			header("Content-Type: " . $mime);

			print_r($content);
		}
	}
	else{
		$errorHandler->throwError('no_access','Sinulla ei oikeutta ladata valittua tiedostoa','error');
	}
}
else{
	$errorHandler->throwError('default','Hakemaasi tiedostoa ei löydy.','error');
}
// #######################################
$session->__destruct();

?>