<?php

define('DS', DIRECTORY_SEPARATOR);
define('APP_PATH_ROOT', dirname(__FILE__));
define('APP_PATH_LIB', APP_PATH_ROOT . '/se-lib');
define('APP_PATH_WWW', APP_PATH_ROOT);
define('APP_PATH_CONFIG', APP_PATH_ROOT . DS . 'config');

session_start();

date_default_timezone_set('Europe/Warsaw');// PHP 5 >= 5.1.0 required by date functions

error_reporting(1);
ini_set('error_reporting', 1);
ini_set('display_startup_errors','1'); 
//display_startup_errors(0);

#TEST $_SESSION['DEBUG'] = 3;// TODO: TEST
if (!isset($_SESSION['DEBUG'])) $_SESSION['DEBUG'] = 0;// set default value


if (file_exists(APP_PATH_ROOT . "/config/.config_{$_SERVER['SERVER_NAME']}.php")) {
	require APP_PATH_ROOT . "/config/.config_{$_SERVER['SERVER_NAME']}.php";
}

if (file_exists(APP_PATH_ROOT . "/.config.php")) include APP_PATH_ROOT . "/.config.php";


require_once APP_PATH_ROOT . "/superedit-SEF.php";
SEF('DEBUG_S');

require_once APP_PATH_LIB . '/' . 'Lib.php';
Lib::loadClass('V');
Lib::loadClass('DB');
Lib::loadClass('User');
Lib::loadClass('S');
Lib::loadClass('Http');
Lib::loadClass('HttpException');

if (!User::logged()) {
	Http::sendHeaderByCode(401);
	exit;
}

/* example:
    [zasobID] => 636
    [id] => 2773
    [file] => 2014-07-11_wizytowki_michal_zaleski_wzor_bn2.bcard/Screen Shot 2014-07-11 at 15.58.15.png
*/

$zasobID = V::get('zasobID', 0, $_GET, 'int');
$recordID = V::get('id', 0, $_GET, 'int');
$fileName = V::get('file', '', $_GET);

if (!$zasobID || !$recordID || empty($fileName)) {
	Http::sendHeaderByCode(406);
	exit;
}
if (false !== strpos($fileName, '../')) {
	Http::sendHeaderByCode(403);
	die('..');
}

$userAcl = User::getAcl();
$tblAcl = $userAcl->getTableAcl($zasobID);

if (!$tblAcl->isInitialized()) {
	Http::sendHeaderByCode(404);
	die("Brak konfiguracji dla ".$tblAcl->getName()."!");
}

Lib::loadClass('TableAjax');
if (!class_exists('TableAjax')) {
	Http::sendHeaderByCode(404);
	die('Error: cls not exists TableAjax');
}

$tblObj = new TableAjax($tblAcl);
try {
	$tblObj->sendFileContent($recordID, $fileName);
}
catch (HttpException $e) {
	Http::sendHeaderByCode($e->getCode());
	header('Content-Type: text/html; charset=utf-8');
	echo $e->getMessage();
}
catch (Exception $e) {
	header('Content-Type: text/html; charset=utf-8');
	echo 'Error ' . $e->getCode() . ':' . $e->getMessage();
}
