<?php

define('THIS_SCRIPT', 'spaceupload');
require_once 'space_global.php';
require_once INC_PATH.'FileHandler.class.php';
require_once INC_PATH.'image_misc.functions.php';
$lang = load_lang($lang, 'spaceupload' );
$lang = load_lang($lang, 'space.error' );

$_strMode = strtolower($_GET['mode']);
if ($_strMode === 'saveupload') {
	if (false === ChkPost()) {	//	拒绝从外部提交
		exit;
	}

	if ($userid <= 0) {	//	您还未登录！
		spaceHeader(array('stats'=>$lang['HeaderTitle1'],'isSystem'=>false,'topEnable'=>false,'navEnable'=>false));
		spaceshowmsg($lang['spaceError.MustLogin'], 0, '', false);
		exit;
	}

	if (1 == $spaceSystemUpSetting[0]) {
		if (0 == $groupsetting[7]) {	//	您没有在本论坛上传文件的权限！
			spaceHeader(array('stats'=>$lang['HeaderTitle1'],'isSystem'=>false,'topEnable'=>false,'navEnable'=>false));
			spaceshowmsg($lang['error.str0'], 0, '', false);
			exit;
		}
	} else {
		if (0 == $spaceSystemUpSetting[1]) {	//	您没有在此空间上传文件的权限！
			spaceHeader(array('stats'=>$lang['HeaderTitle1'],'isSystem'=>false,'topEnable'=>false,'navEnable'=>false));
			spaceshowmsg($lang['error.str1'], 0, '', false);
			exit;
		}
	}

	$_intMaxSize = intval($spaceSystemUpSetting[1]);
	if ($_intMaxSize <= 0) {
		$_intMaxSize = intval($groupsetting[44]);
	}
	if( $spaceUserInfo['spacesize'] == 0 ) {	//	当前space允许上传的空间已满，请与管理员联系。
		spaceHeader(array('stats'=>$lang['HeaderTitle1'],'isSystem'=>false,'topEnable'=>false,'navEnable'=>false));
		spaceshowmsg($lang['error.str2'],0,'',false);
		exit;
	} elseif ($spaceUserInfo['spacesize'] > 0) {
		if ($spaceUserInfo['spacesize'] < $_intMaxSize) {
			$_intMaxSize = $spaceUserInfo['spacesize'];
		}
	}
		
	//检查上传文件
	foreach ($_FILES as $index => $currFile) {
		if ($currFile['error']) { // 上传文件时发生错误，错误代码是：{$currFile['error']}
			print $lang['Error.strings8'].$lang['Error.strings8_1'][$currFile['error']];
			exit;
		}		
		$_FILES[$index]['tmp_name'] = $currFile['tmp_name'] = str_replace('\\\\', '\\', $currFile['tmp_name']);
		if (false === is_uploaded_file(str_replace('\\\\', '\\', $currFile['tmp_name']))) { // 请使用POST方式上传文件！
			print $lang['Error.strings9'];
			exit;
		}
		$currFileExt = str_replace('.','',strrchr($currFile['name'],'.'));
		if ($currFileExt === false) {
			list(,$currFileExt) = explode('/',$currFile['type']);
			if (strpos($currFileExt,'-') !== false) {
				$currFileExt = str_replace('-','',strstr($currFileExt,'-'));
			}
		}
		$lowerext = strtolower($currFileExt);
		//关于文件后缀/文件扩展名的一劳永逸的防范说明：除了图片以外的所有文件，都将在其文件名的末尾，追加一个下划线"_"，用于提高安全性；追加下划线的代码在 spacemanage.php 和 spacepostings.php 中的 uploadedFilesProc() 中实现
		if (false !== strpos(',php,php3,php4,php5,cer,asa,phtml,asp,aspx,jsp,', ",{$lowerext},")) { // 文件类型{$fileExt}不正确!
			print str_replace('{$fileExt}',$currFileExt,$lang['Error.strings10']);
			exit;
		}
		//关于文件后缀/文件扩展名的一劳永逸的防范说明：除了图片以外的所有文件，都将在其文件名的末尾，追加一个下划线"_"，用于提高安全性
		if (false === strpos('|'.strtolower($spaceSystemSetting[16]).'|', "|{$lowerext}|")) { // 文件类型{$fileExt}不正确!
			print str_replace('{$fileExt}',$currFileExt,$lang['Error.strings10']);
			exit;
		}
	}
	

	//Start 水印设置部分
		if ($canmakewatermark = canmakewatermark()) { // 检测系统是否支持在图片上加水印
			if (1 == $spaceSystemUpSetting[17]) {
				$drawinfo = $spaceSystemUpSetting[4].''; // 用文字作为水印
			} elseif (2 == $spaceSystemUpSetting[17]) {
				$drawinfo = $spaceSystemUpSetting[9].''; // 用图片作为水印
			} else {
				$drawinfo = '';
			}
			if ($drawinfo === '0') {
				$drawinfo = '';
				$spaceSystemUpSetting[17] = 0;
			}
		}
		if (0 == $spaceSystemUpSetting[17]) {
			$canmakewatermark = false;
		}
	//End 水印设置部分
	//开始执行上传
	require_once INC_PATH.'upload.functions.php';
	$initedupparams = initUploadDirectories(array('init_updestdir'=>false));
	$UploadedFiles = array();
	$index = 0;
	$uploaded_tmpfiles = ''; // 成功上传到临时目录的文件名列表，以“:”分隔
	$colon = '';
	$uploadedcount = 0; // 成功上传的文件的计数
	$subuploaddir = basename($initedupparams['spacedestdir']);
	print <<<EOT
		<link rel="stylesheet" type="text/css" href="{$fsetting['css']}" />
		<style type="text/css">body { margin: 0px; }</style>
EOT;
	foreach ($_FILES AS $currFile) {
		$currpathinfo = FileHandler::pathinfo($currFile['name']);
		$currFileExt = strtolower($currpathinfo['extension']);
		if (empty($currFileExt)) {
			list(, $currFileExt) = explode('/', $currFileExt['type']);
			if (false !== strpos($currFileExt, '-')) {
				$currFileExt = str_replace('-', '', strstr($currFileExt, '-'));
			}
		}
		list($msec, $sec) = explode(' ', microtime());
		$filenamewithoutextension = $sec.($msec*1000000);
		$newfilename = $filenamewithoutextension.'.'.$currFileExt;
		$destFile = str_replace($initedupparams['spaceuptopdir'].'/', '', $initedupparams['spacedestdir'].'/'.$newfilename);
		$tmpfile = $initedupparams['uptmpdir'].'/__dv_tmp_uploaded_file__'.$newfilename;
		if (true === move_uploaded_file($currFile['tmp_name'], $tmpfile)) {
			@FileHandler::chmod($tmpfile, 0755);
			$ftype = getFileType($currFileExt);
			if ($ftype == 1) {
				if (true === $canmakewatermark) { // 由于安全模式的限制，应首先生成文字水印，然后再转移到临时目录
					@imageWaterMark($tmpfile, $spaceSystemUpSetting[13], $drawinfo, $spaceSystemUpSetting[5], $spaceSystemUpSetting[6]);
				}
			}
			$uploaded_tmpfiles .= "{$colon}{$newfilename}";
			$colon = ':';
			$uploadedcount++;
			$UploadedFiles[$index]['uploaded_tmpfile'] = basename($tmpfile); // 出于安全考虑，仅存储文件名，不包括完整路径
			$UploadedFiles[$index]['destfile'] = $destFile;
			$UploadedFiles[$index]['subuploaddir'] = $subuploaddir;
			$UploadedFiles[$index]['ftype'] = $ftype;
			$UploadedFiles[$index]['name'] = $filenamewithoutextension;
			$UploadedFiles[$index]['ext'] = $currFileExt;
			$UploadedFiles[$index]['size'] = $currFile['size'];
			$index++;
		} else {
			print $lang['Error.strings11'];
		}
	}
}
require printout('spaceupload');

//判断文件类型:0=其它,1=图片,2=FLASH,3=音乐,4=电影
function getFileType($FileExt){
	if( strpos('|gif|jpg|jpeg|png|bmp|tif|iff|',"|{$FileExt}|") !== false ){
		return 1;
	} elseif( strpos('|swf|swi|',"|{$FileExt}|") !== false ){
		return 2;
	} elseif( strpos('|mid|wav|mp3|rmi|cda|',"|{$FileExt}|") !== false ){
		return 3;
	} elseif( strpos('|avi|mpg|mpeg|ra|ram|wov|asf|',"|{$FileExt}|") !== false ){
		return 4;
	} else{
		return 0;
	}
}//end function getFileType

function initUploadDirectory()
{
	global $fsetting, $spaceSystemUpSetting;
	$space_uptopdir = trim($spaceSystemUpSetting[19]);
	if (empty($space_uptopdir) OR (false === ($space_uptopdir = realpath($space_uptopdir)))) {
		$space_uptopdir = realpath('uploadfile');
	}
	if (empty($space_uptopdir)) {	//	找不到My Space的上传目录。
		spaceHeader(array('stats'=>$lang['HeaderTitle1'],'isSystem'=>false,'topEnable'=>false,'navEnable'=>false));
		spaceshowmsg($lang['error.str3'], 0, '', false);
		exit;
	}
//Start 存储临时上传文件的目录
	$forum_uptopdir = realpath(ROOT_PATH.$fsetting['forumuploadname']);
	if (false === $forum_uptopdir) {
		$forum_uptopdir = realpath('./uploadfile');
	}
	$tempdir = $forum_uptopdir.'/tempimage';
	if (!FileHandler::is_dir($tempdir)) {	//	临时上传目录不存在，请通过FTP创建它——uploadfile/tempimage，并将其属性设为0777。
		spaceHeader(array('stats'=>$lang['HeaderTitle1'],'isSystem'=>false,'topEnable'=>false,'navEnable'=>false));
		spaceshowmsg($lang['error.str5'], 0, '', false);
		exit;
	}
//End 存储临时上传文件的目录
	$strdate = date('Y-m');
//Start 上传文件所在目录
	$destdir = $space_uptopdir.'/'.$strdate;
	if (!FileHandler::is_dir($destdir)) {
		@chmod($destdir, 0777);
		if (!FileHandler::mkdir($destdir, 0777)) {
			spaceHeader(array('stats'=>$lang['HeaderTitle1'],'isSystem'=>false,'topEnable'=>false,'navEnable'=>false));
			spaceshowmsg(str_replace('{$Tpl_dir}', $destdir, $lang['error.str4']), 0, '', false);
			exit;
		}
	}
//End 上传文件所在目录
//Start 预览图片所在的根目录
	$previewtopdir = $space_uptopdir.'/previewimage';
	if (!FileHandler::is_dir($previewtopdir)) {
		if (!FileHandler::mkdir($previewtopdir, 0777)) {
			spaceHeader(array('stats'=>$lang['HeaderTitle1'],'isSystem'=>false,'topEnable'=>false,'navEnable'=>false));
			spaceshowmsg(str_replace('{$Tpl_dir}', $previewtopdir, $lang['error.str4']), 0, '', false);
			exit;
		}
	}
//End 预览图片所在的根目录
//Start 按月份存储的预览图片的目录
	$previewdir = $space_uptopdir.'/previewimage/'.$strdate;
	if (!FileHandler::is_dir($previewdir)) {
		if (!FileHandler::mkdir($previewdir, 0777)) {
			spaceHeader(array('stats'=>$lang['HeaderTitle1'],'isSystem'=>false,'topEnable'=>false,'navEnable'=>false));
			spaceshowmsg(str_replace('{$Tpl_dir}', $previewdir, $lang['error.str4']), 0, '', false);
			exit;
		}
	}
//End 按月份存储的预览图片的目录
	return array('upload_top_dir'=>$space_uptopdir, 'preview_top_dir'=>$previewtopdir, 'dest_dir'=>$destdir, 'temp_dir'=>$tempdir, 'strdate'=>$strdate);
}//end function initUploadDirectory

?>