<?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.'debug.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)));
}

function check_modified_header($lFile) {

   $headers=apache_request_headers();
   $if_modified_since=preg_replace('/;.*$/', '', $headers['If-Modified-Since']);
   if(!$if_modified_since) {
	   
       return;
   }
   $gmtime=get_http_mdate($lFile);

   if ($if_modified_since > $gmtime) {
       header("HTTP/1.1 304 Not Modified");
       exit;
   }
}


//#### Start session
session_name(SESSION_NAME);
session_start();
session_register("_SESSION_VARIABLE");



$session = new Session;
$userManager = new UserManager;

$tDir = new rowTreeParser('sys_doc_dir');
$lFile = new fileList();

// Käyttäjä
$user = new Dummy;
$user = $userManager->login($session->getVar('user'));

if (!$user) {
	
	//tehdään login
	
	if ($request) {}
	
	
} 


$aDirCache = $session->getVar('action/binary/file#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;
	$session->setVar('action/binary/file#aDirCache', $aDirCache);
}

if ($userManager->check('sitedoc/view'.$path)) {

	$size = $lFile->getFileSize();

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

	check_modified_header($lFile);
	header("Content-Length: " . $size);
	header("Content-Type: " . $mime);
	// HTTP/1.1
	header("Last-Modified: ".get_http_mdate($lFile)." GMT");
	//header("Cache-Control: no-store, no-cache, must-revalidate");
	//header("Cache-Control: post-check=0, pre-check=0", false);
	// HTTP/1.0
	header("Pragma: no-cache");


	
	//$lFile->echoData();
	
	
} else {
	
	echo 'No permission';
	
}



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


$session->__destruct();


?>
