<?php
include_once '../slex.php';
xCore::start();

// --- 防盗链 ---
// --- 此防盗链不适用于卷端 ---
$referers = parse_url($_SERVER['HTTP_REFERER']);
if(strpos($_SERVER['HTTP_REFERER'],':')!==false) $_SERVER['HTTP_REFERER'] = substr($_SERVER['HTTP_REFERER'], 0, strpos($_SERVER['HTTP_REFERER'],':'));
if($referers['host'] == $_SERVER['HTTP_HOST']) {
	$vol = new xVolume(1);
	xGbl::$mysql->exec('DELETE FROM `'.TB_PREFIX.'volume_token` WHERE `date` < "'.(time()-25200).'";');
	$tokenRes = xGbl::$mysql->exec('SELECT * FROM `'.TB_PREFIX.'volume_token` WHERE `token` = "'.xGbl::$mysql->escape($_GET['token']).'" AND `vid` = "'.xGbl::$mysql->escape($_GET['id']).'";');
	if($token = $tokenRes->fetch_assoc()) {
		// --- 判断扩展名 ---
		$nameExtDot = strrpos($token['filename'], '.');
		$nameExt = ($nameExtDot!==false) ? strtolower(substr($token['filename'], $nameExtDot+1)) : '';
		if(in_array($nameExt, $_APP['preview'])) {
			$vfileRes = xGbl::$mysql->exec('SELECT * FROM `'.TB_PREFIX.'volume_vfiles` WHERE `id` = '.$token['vid'].';');
			$vfile = $vfileRes->fetch_assoc();
			$vfileRes->free();
			// --- 开启文件 ---
			$fs = filesize($vfile['path']);
			$fh = fopen($vfile['path'],'r');
			if($nameExt == 'txt') {
				$text = fread($fh,($fs<=102400)?$fs:102400);
				$encode = mb_detect_encoding($text, array('GBK', 'UTF-8'));
				if($encode != 'UTF-8') $text = iconv($encode,'UTF-8',$text);
				echo $_GET['cb'].'('.json_encode(array(
					'result' => '1',
					'text' => ($_GET['encode']=='1') ? htmlspecialchars($text) : $text
				)).')';
			} else if(in_array($nameExt, array('jpg','gif','jpeg','png'))) {
				while(!feof($fh)) {
					echo fread($fh,32768);
					ob_flush();
					flush();
				}
			} else if(in_array($nameExt, array('mp4','mp3','flv','f4v'))) {
				@set_time_limit(0);
				header('Content-Length: '.$vfile['size']);
				switch($nameExt) {
					case 'mp3':
						header('Content-type: audio/x-mpeg');
						break;
					case 'mp4':
						header('Content-type: video/mp4');
						break;
				}
				while(!feof($fh)) {
					echo fread($fh,32768);
					ob_flush();
					flush();
				}
			}
			fclose($fh);
		} else {
			echo $_GET['cb'].'('.json_encode(array(
				'result' => '0',
				'msg' => 'Open file fail.'
			)).')';
		}
	} else {
		echo $_GET['cb'].'('.json_encode(array(
			'result' => '0',
			'msg' => 'Token fail.'
		)).')';
	}
	$tokenRes->free();
} else {
	echo $_GET['cb'].'('.json_encode(array(
		'result' => '0',
		'msg' => 'Access fail.'
	)).')';
}

