<?php
define('THIS_SCRIPT', 'post_upload');
require 'global.php';
require_once INC_PATH.'FileHandler.class.php';
require_once INC_PATH.'image_misc.functions.php';
$lang = load_lang($lang, 'post_upload' );
$istoptable = 0;
head();

if (empty($uploadsettings)) {
	$uploadsettings = explode('|', $fsetting['uploadsetting']);
}
if ($uploadsettings[2] == '0') {	//	上传功能已关闭
	print $lang['Error.strings11'];
	exit;
}

if (empty($UserToday) AND empty($userinfo['usertoday'])) {
	$arrUserToday = array(0,0,0,0,0);
} elseif (!empty($UserToday)) {
	$arrUserToday = $UserToday;
} else {
	$arrUserToday = explode('|', $userinfo['usertoday']);
}


if (($t == 1) AND !empty($_FILES)){ // 提交上传文件
	
	//提交验证
	if( ChkPost() === false ){
		exit;
	}
	#移除空文件
	foreach ( $_FILES as $index => $currFile )if ($currFile['error'])unset($_FILES[$index]);
	$arrhiddenname = array();
	foreach ( $hiddenname as $index => $currFile ){
		if (empty($currFile))unset($hiddenname[$index]);
		else if (!empty($currFile))$arrhiddenname[]=$currFile;
	}
	if( $userid == 0 ){
		print $lang['Error.strings2'];
		exit;
	}
	if( $groupsetting[7] == 0 ){
		print $lang['Error.strings3'];
		exit;
	}
	//如果论坛需要支持较大的上传大，就必须设置。前提是要关闭PHP的安全模式
	if( !ini_get('safe_mode') ){
		ini_set('max_execution_time','999999');
	}
	if( count($_FILES) <= 0 ){
		print $lang['Error.strings7'];
		$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
		print str_replace('{$t}', 2, $Error_strings13);
		exit;
	}
	
	//Start 处理上传文件之前的常规检查
		$TodayUploaded = get_cookie('upNum');
		(is_array($_FILES)) AND ($OnceUPCount = count($_FILES));
		if (!is_numeric($OnceUPCount) OR $OnceUPCount < 0) {
			$OnceUPCount = 0;
		}
		if ($OnceUPCount > $groupsetting[40]) { // 一次只能上传 {$groupsetting[40]} 个文件！
			print str_replace('{$num}',$groupsetting[40],$lang['Error.strings4']);
			$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
			print str_replace('{$t}', 2, $Error_strings13);
			exit;
		} else {
			$InceptMaxFile = $groupsetting[40] - $OnceUPCount;
		}
		if ($TodayUploaded >= $groupsetting[50]) {	//	一天最多只能上传{$num}个文件！
			print str_replace('{$num}', $groupsetting[50], $lang['Error.strings4_1']);
			$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
			print str_replace('{$t}', 2, $Error_strings13);
		}
		if (!is_numeric($arrUserToday[2])) {
			$arrUserToday[2] = 0;
		}
		if ($arrUserToday[2] > $groupsetting[50]) { // 已超出了你在论坛每天上传的文件个数 {$groupsetting[50]} 个！
			print str_replace('{$num}',$groupsetting[50],$lang['Error.strings5']);
				$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
				print str_replace('{$t}', 2, $Error_strings13);
			exit;
		} else {
			if ($groupsetting[50] - $arrUserToday[2] < $InceptMaxFile) {
				$InceptMaxFile = $groupsetting[50] - $arrUserToday[2];
			}
		}

        #移除空的浏览
		foreach ($_FILES as $index => $currFile) {
			if (($currFile['size'] / 1024) > $groupsetting[44]) {	//	每个文件不能超过{$num}K！
				print str_replace('{$num}', $groupsetting[44], $lang['Error.strings4_2']);
				$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
				print str_replace('{$t}', 2, $Error_strings13);
				exit;
			}
			if ($currFile['error']) { // 上传文件时发生错误，错误代码是：{$currFile['error']}
				print $lang['Error.strings8'].$lang['Error.strings8_1'][$currFile['error']];
				$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
				print str_replace('{$t}', 2, $Error_strings13);
				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'];
				$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
				print str_replace('{$t}', 2, $Error_strings13);
				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);
			
			//关于文件后缀/文件扩展名的一劳永逸的防范说明：除了图片以外的所有文件，都将在其文件名的末尾，追加一个下划线"_"，用于提高安全性；追加下划线的代码在 savepost.php 的 uploadedFilesProc() 中实现
			//音乐文件也不加后缀(swf|wma|mp3)
			if (false !== strpos(',php,php3,php4,php5,cer,asa,phtml,asp,aspx,jsp,', ",{$lowerext},")) { // 文件类型{$fileExt}不正确!
				print str_replace('{$fileExt}',$currFileExt,$lang['Error.strings10']);
				$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
				print str_replace('{$t}', 2, $Error_strings13);
				exit;
			}
			//关于文件后缀/文件扩展名的一劳永逸的防范说明：除了图片以外的所有文件，都将在其文件名的末尾，追加一个下划线"_"，用于提高安全性
			if (false === strpos('|'.strtolower($board_settings[51]).'|', "|{$lowerext}|")) { // 文件类型{$fileExt}不正确!

				print str_replace('{$fileExt}',$currFileExt,$lang['Error.strings10']);
				$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
				print str_replace('{$t}', 2, $Error_strings13);
				exit;
			}
			$ftype = getFileType($lowerext);
			if ($ftype!=1) { // 文件类型{$fileExt}不正确!
				print str_replace('{$fileExt}',$currFileExt,$lang['Error.strings10']);
				$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
				print str_replace('{$t}', 2, $Error_strings13);
				exit;
			}

		}
	//End 处理上传文件之前的常规检查

	//Start 水印设置部分
		if ($canmakewatermark = canmakewatermark()) { // 检测系统是否支持在图片上加水印
			if ($uploadsettings[17] == 1) {
				$drawinfo = $uploadsettings[4].''; // 用文字作为水印
			} elseif ($uploadsettings[17] == 2) {
				$drawinfo = $uploadsettings[9].''; // 用图片作为水印
			} else {
				$drawinfo = '';
			}
			if ($drawinfo === '0') {
				$drawinfo = '';
				$uploadsettings[17] = 0;
			}
		}
		if ($uploadsettings[17] == 0) {
			$canmakewatermark = false;
		}
	//End 水印设置部分

	require_once INC_PATH.'upload.functions.php';
	$updirsettings = initUploadDirectories(array('init_space_updestdir'=>false));

	$UploadedFiles = array();
	$hid   = 1;
	$index = 0;
	$uploaded_tmpfiles = ''; // 成功上传到临时目录的文件名列表，以“:”分隔
	$colon = '';
	$uploadedcount = 0; // 成功上传的文件的计数
	$subuploaddir = basename($updirsettings['updestdir']);

	foreach ($_FILES AS $currFile) {

		$currFileExt = strtolower(str_replace('.', '', strrchr($currFile['name'], '.')));
		if ($currFileExt === false) {
			list(,$currFileExt) = explode('/',$currFile['type']);
			if( strpos($currFileExt,'-') !== false ){
				$currFileExt = str_replace('-','',strstr($currFileExt,'-'));
			}
		}
		list($msec, $sec) = explode(' ', microtime());
		$filenamewithoutextension = $sec.($msec*1000000);
		$newfilename = $filenamewithoutextension.'.'.$currFileExt;
		$destFile = str_replace($updirsettings['uptopdir'].'/', '', $updirsettings['updestdir'].'/'.$newfilename);
		$tmpfile = $updirsettings['uptmpdir'].'/__dv_tmp_uploadedfile__'.$newfilename;
		if (move_uploaded_file($currFile['tmp_name'], $tmpfile)) {
			@FileHandler::chmod($tmpfile, 0755);
			$ftype = getFileType($currFileExt);
			if ($ftype == 1) {
				if (true === $canmakewatermark) { // 由于安全模式的限制，应首先生成文字水印，然后再转移到临时目录
					@imageWaterMark($tmpfile, $uploadsettings[13], $drawinfo, $uploadsettings[5], $uploadsettings[6], $uploadsettings[10], $uploadsettings[7]);
				}
			}
			$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'];
			$hidname= "hidname{$hid}";
			$UploadedFiles[$index]['LocalName'] = $currFile['name'];
			$UploadedFiles[$index]['LocalUrl'] = $arrhiddenname[$index];
			
			$UploadedFiles[$index]['UpUrl'] = "[upload={$currFileExt}]{$destFile}[/upload]";
			$hid++;
			$index++;
		} else {
			print $lang['Error.strings12'];
			$Error_strings13=str_replace('{$boardid}', $boardid, $lang['Error.strings13']);
			print str_replace('{$t}', 2, $Error_strings13);

		}
	}
}

# 提交附件上传文件
if (($t == 3) AND !empty($_FILES)){ 
	foreach ($_FILES as $index => $currFile) {
	if (!empty($index)){ unset ($_FILES[$index]);break;}
	}

	if (count($_FILES) > 0)
	{
		$upcount=count($_FILES);
	}

	//提交验证
	if( ChkPost() === false ){
		exit;
	}

	if( $userid == 0 ){
		echo '<SCRIPT LANGUAGE="JavaScript">alert("'.$lang["Error.strings2"].'");</SCRIPT>';
		exit;
	}
	if( $groupsetting[7] == 0 ){
		//您没有在本论坛上传文件的权限
		echo '<SCRIPT LANGUAGE="JavaScript">alert("'.$lang["Error.strings3"].'");</SCRIPT>';
		exit;
	}
	//如果论坛需要支持较大的上传大，就必须设置。前提是要关闭PHP的安全模式
	if( !ini_get('safe_mode') ){
		ini_set('max_execution_time','999999');
	}
	
	if( count($_FILES) <= 0 ){
		//没有发现上传文件
		echo '<SCRIPT LANGUAGE="JavaScript">alert("'.$lang["Error.strings7"].'");</SCRIPT>';
		exit;
	}			
	
	//Start 处理上传文件之前的常规检查
		$TodayUploaded = get_cookie('upNum');
		(is_array($_FILES)) AND ($OnceUPCount = count($_FILES));
		if (!is_numeric($OnceUPCount) OR $OnceUPCount < 0) {
			$OnceUPCount = 0;
		}
		if ($OnceUPCount > $groupsetting[40]) { // 一次只能上传 {$groupsetting[40]} 个文件！

			$err=str_replace('{$num}',$groupsetting[40],$lang['Error.strings4']);
			echo "<SCRIPT LANGUAGE=\"JavaScript\">alert('".$err."');</SCRIPT>";
			exit;
		} else {
			$InceptMaxFile = $groupsetting[40] - $OnceUPCount;
		}
		if ($TodayUploaded >= $groupsetting[50]) {	//	一天最多只能上传{$num}个文件！
		   echo "<SCRIPT LANGUAGE=\"JavaScript\">alert('".str_replace('{$num}', $groupsetting[50], $lang['Error.strings4_1'])."');</SCRIPT>";

			exit;
		}
		if (!is_numeric($arrUserToday[2])) {
			$arrUserToday[2] = 0;
		}
		if ($arrUserToday[2] > $groupsetting[50]) { // 已超出了你在论坛每天上传的文件个数 {$groupsetting[50]} 个！
		   echo "<SCRIPT LANGUAGE=\"JavaScript\">alert('".str_replace('{$num}',$groupsetting[50],$lang['Error.strings5'])."');</SCRIPT>";
			exit;
		} else {
			if ($groupsetting[50] - $arrUserToday[2] < $InceptMaxFile) {
				$InceptMaxFile = $groupsetting[50] - $arrUserToday[2];
			}
		}

		foreach ($_FILES as $index => $currFile) {
			if (($currFile['size'] / 1024) > $groupsetting[44]) {	//	每个文件不能超过{$num}K！
				echo "<SCRIPT LANGUAGE=\"JavaScript\">alert('".str_replace('{$num}', $groupsetting[44], $lang['Error.strings4_2'])."');</SCRIPT>";			
				exit;
			}
			if ($currFile['error']) { // 上传文件时发生错误，错误代码是：{$currFile['error']}
				echo "<SCRIPT LANGUAGE=\"JavaScript\">alert('".$lang['Error.strings8'].$lang['Error.strings8_1'][$currFile['error']]."');</SCRIPT>";						
				exit;
			}
			$_FILES[$index]['tmp_name'] = $currFile['tmp_name'] = str_replace('\\\\', '\\', $currFile['tmp_name']);
			if (false === is_uploaded_file(str_replace('\\\\', '\\', $currFile['tmp_name']))) { // 请使用POST方式上传文件！
				echo "<SCRIPT LANGUAGE=\"JavaScript\">alert('".$lang['Error.strings9']."');</SCRIPT>";			
				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);

			//关于文件后缀/文件扩展名的一劳永逸的防范说明：除了图片以外的所有文件，都将在其文件名的末尾，追加一个下划线"_"，用于提高安全性；追加下划线的代码在 savepost.php 的 uploadedFilesProc() 中实现
			//音乐文件也不加后缀(swf|wma|mp3)
			if (false !== strpos(',php,php3,php4,php5,cer,asa,phtml,asp,aspx,jsp,', ",{$lowerext},")) { // 文件类型{$fileExt}不正确!
				echo "<SCRIPT LANGUAGE=\"JavaScript\">alert('".str_replace('{$fileExt}',$currFileExt,$lang['Error.strings10'])."');</SCRIPT>";			
				exit;
			}
			//关于文件后缀/文件扩展名的一劳永逸的防范说明：除了图片以外的所有文件，都将在其文件名的末尾，追加一个下划线"_"，用于提高安全性
			if (false === strpos('|'.strtolower($board_settings[51]).'|', "|{$lowerext}|")) { // 文件类型{$fileExt}不正确!
				echo "<SCRIPT LANGUAGE=\"JavaScript\">alert('".str_replace('{$fileExt}',$currFileExt,$lang['Error.strings10'])."');</SCRIPT>";			
				exit;
			}
			$ftype = getFileType($lowerext);
			if ($ftype==1)  { // 文件类型{$fileExt}不正确!
				echo "<SCRIPT LANGUAGE=\"JavaScript\">alert('".str_replace('{$fileExt}',$currFileExt,$lang['Error.strings10'])."');</SCRIPT>";			
				exit;
			}
		}
	//End 处理上传文件之前的常规检查

	require_once INC_PATH.'upload.functions.php';
	$updirsettings = initUploadDirectories(array('init_space_updestdir'=>false));

	$UploadedFiles = array();
	$hid   = 1;
	$index = 0;
	$uploaded_tmpfiles = ''; // 成功上传到临时目录的文件名列表，以“:”分隔
	$colon = '';
	$uploadedcount = 0; // 成功上传的文件的计数
	$subuploaddir = basename($updirsettings['updestdir']);

	foreach ($_FILES AS $currFile) {
		$currFileExt = strtolower(str_replace('.', '', strrchr($currFile['name'], '.')));
		if ($currFileExt === false) {
			list(,$currFileExt) = explode('/',$currFile['type']);
			if( strpos($currFileExt,'-') !== false ){
				$currFileExt = str_replace('-','',strstr($currFileExt,'-'));
			}
		}
		$ftype = getFileType($currFileExt);

		list($msec, $sec) = explode(' ', microtime());
		$filenamewithoutextension = $sec.($msec*1000000);
		$newfilename = $filenamewithoutextension.'.'.$currFileExt;
		$destFile = str_replace($updirsettings['uptopdir'].'/', '', $updirsettings['updestdir'].'/'.$newfilename);
		$tmpfile = $updirsettings['uptmpdir'].'/__dv_tmp_uploadedfile__'.$newfilename;
		if (move_uploaded_file($currFile['tmp_name'], $tmpfile)) {
			@FileHandler::chmod($tmpfile, 0755);

			$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'];
			$hidname= "hidname{$hid}";
			$UploadedFiles[$index]['LocalName'] = $currFile['name'];
			$UploadedFiles[$index]['LocalUrl'] = $$hidname;
			$UploadedFiles[$index]['UpUrl'] = "[upload={$currFileExt}]{$destFile}[/upload]";
			$hid++;
			$index++;
		} else {
			//无法转移上传文件到临时目录
			echo "<SCRIPT LANGUAGE=\"JavaScript\">alert('".$lang['Error.strings12']."');</SCRIPT>";			

		}
	}
}


require printout('post_upload');

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

?>