<?php

class tokenget_sxExe extends xIExecutor {

	public function main() {
		$file = new xFile((int)$_POST['id']);
		if($file->isValid()) {
			// --- 判断是否有下载权限 ---
			define('FILE_ISSHARE',		$share = xShare::access($file, false) ? true : false);
			if(FILE_ISSHARE || (!xUser::$cur->isGuest() && (xUser::$cur->id == $file->owner))) {
				$vfile = new xVFile((int)$file->vfid);
				if($vfile->serv0 == '1') {
					$or = xGbl::$mysql->exec('SELECT `token` FROM `'.TB_PREFIX.'volume_token` WHERE `filename` = "'.xGbl::$mysql->escape($file->name).'" AND `vid` = '.$vfile->id.' AND `date` > '.(time()-3600).';');
					if($o = $or->fetch_assoc()) {
						$token = $o['token'];
					} else {
						$token = date('d').xStrUtils::randomString(30, 'abcdefghijklmnopqrstuvwxyz0123456789');
						while(!xGbl::$mysql->exec('INSERT INTO `'.TB_PREFIX.'volume_token` (`token` ,`vid` ,`date` ,`filename`) VALUES ("'.$token.'", '.$vfile->id.', '.time().', "'.xGbl::$mysql->escape($file->name).'");')) {
							$token = date('d').xStrUtils::randomString(30, 'abcdefghijklmnopqrstuvwxyz0123456789');
						}
						// --- 只有下载才算下载 ---
						if($_POST['do'] == 'downurl') xGbl::$mysql->exec('UPDATE `'.TB_FILES.'` SET `downloads` = `downloads` + 1 WHERE `id` = '.$file->id.';');
					}
					$or->free();
					$url = ($_POST['do'] == 'downurl') ? 'download.php?id='.$vfile->id.'&token='.$token : 'preview.php?id='.$vfile->id.'&token='.$token;
					echo json_encode(array(
						'result' => '1',
						'url' => '/volume/' . $url
					));
				} else {
					// --- 暂未实现 ---
				}
			} else {
				echo json_encode(array(
					'result' => '0',
					'msg' => '您无权下载/预览'
				));
			}
		} else {
			echo json_encode(array(
				'result' => '0',
				'msg' => '文件不存在'
			));
		}
	}

	public function onError($result) {

	}
}

