<?php

/*
	[SupeSite/X-Space] (C)2001-2006 Comsenz Inc.
	上傳處理

	$RCSfile: batch.upload.php,v $
	$Revision: 1.43 $
	$Date: 2006/10/23 06:36:53 $
*/

include_once('./include/main.inc.php');
include_once(S_ROOT.'./include/common.inc.php');

@header('Content-Type: text/html; charset='.$_SCONFIG['charset']);

getcookie(1);
$uid = $_SGLOBAL['supe_uid'];
if(empty($uid)) exit;

$showtext = $hash = '';
$action = postget('action');
$noinsert = intval(postget('noinsert'));
$aid = 0;

if($action == 'delete' || $action == 'edit') {
	
	//debug 刪除編輯
	$aid = intval(postget('aid'));
	$uc = postget('uc');
	if(empty($aid) || empty($uc)) exit;
	$ucarr = explode('|', authcode($uc, 'DECODE'));
	if(empty($ucarr[0]) || empty($ucarr[1])) exit;
	$uid = intval($ucarr[0]);
	if(empty($uid)) exit;
	
	$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('attachments')." WHERE aid='$aid' AND uid='$uid'");
	if(!$value = $_SGLOBAL['db']->fetch_array($query)) exit;
	$hash = $value['hash'];

	if($action == 'delete') {
		@unlink(A_DIR.'/'.$value['filepath']);
		@unlink(A_DIR.'/'.$value['thumbpath']);
		deletetable('attachments', array('aid'=>$aid));
		$_SGLOBAL['db']->query("UPDATE ".tname('userspacefields')." SET attachsize=attachsize-$value[size] WHERE uid=$uid");
		$aid = 0;
		showresult('指定的文件刪除成功\了', 'ok');
	} else {
		showresult('');
	}

} elseif (!empty($_POST)) {
	
	//編輯標題
	if(!empty($_GET['editaid']) && $editaid = intval($_GET['editaid'])) {
		$editsubject = cutstr(trim(shtmlspecialchars($_POST['editsubject'])), 50);
		updatetable('attachments', array('subject'=>$editsubject), array('aid'=>$editaid));

		print <<<END
		<script language="javascript">
		var div = parent.document.getElementById("div_upload_" + $editaid);
		var pf = parent.document.getElementById("phpframe");
		pf.src = "about:blank";
		div.innerHTML = "$editsubject";
		</script>
END;
		exit;
	}
	
	//上傳文件
	//上傳模式
	$mode = intval(postget('mode'));
	if($mode>2) exit;

	$hash = trim($_POST['hash']);
	if(strlen($hash) != 16) showresult('系統錯誤，無法完成此次上傳，請聯繫管理員');
	
	//個數
	$filecount = 1;
	if($mode == 2) $filecount = count($_FILES['batchfile']['tmp_name']) - 1;
	$query = $_SGLOBAL['db']->query('SELECT COUNT(*) FROM '.tname('attachments').' WHERE hash=\''.$hash.'\'');
	$count = $_SGLOBAL['db']->result($query, 0);
	$allowmax = intval($_POST['uploadallowmax']);
	if($allowmax > 0 && $count + $filecount > $allowmax) showresult('允許\上傳文件數目已經達到最大值，請先刪除已上傳的文件');

	//類型
	$allowtypearr = getallowtype(trim($_POST['uploadallowtype']));
	
	//空間
	$query = $_SGLOBAL['db']->query('SELECT attachsize FROM '.tname('userspacefields').' WHERE uid=\''.$uid.'\'');
	$attachsize = $_SGLOBAL['db']->result($query, 0);
	
	include_once(S_ROOT.'./function/upload.func.php');
	
	if(empty($mode)) {
		
		//本地上傳
		//檢查
		$filearr = $_FILES['localfile'];
		if(empty($filearr['size']) || empty($filearr['tmp_name'])) showresult('獲取上傳文件大小失敗，請選擇其他文件上傳');
		$fileext = fileext($filearr['name']);
		if(!empty($allowtypearr)) {
			if(empty($allowtypearr[$fileext])) showresult('本操作不允許\上傳此類型的資源，請返回檢查');
			if($filearr['size'] > $allowtypearr[$fileext]['maxsize']) showresult('上傳的文件大小超過允許\的範圍，請返回檢查');
		}
		if(!empty($_SGLOBAL['group']['attachsize']) && ($attachsize + $filearr['size'] > $_SGLOBAL['group']['attachsize'])) showresult('您目前擁有的上傳空間已滿，已經沒有權限繼續上傳附件');
		
		//縮略圖
		if(!empty($_POST['uploadthumb0']) && !empty($_SGLOBAL['thumbarr'][$_POST['uploadthumb0']])) {
			$thumbarr = $_SGLOBAL['thumbarr'][$_POST['uploadthumb0']];
		} else {
			$thumbarr = array($_POST['thumbwidth'], $_POST['thumbheight']);
		}
		
		//上傳
		$newfilearr = savelocalfile($filearr, $thumbarr);
		if(empty($newfilearr['file'])) showresult('上傳文件失敗，請您稍後嘗試重新上傳');

		//數據庫
		if(empty($_POST['uploadsubject0'])) $_POST['uploadsubject0'] = cutstr(filemain($filearr['name']), 50);
		$insertsqlarr = array(
			'uid' => $uid,
			'dateline' => $_SGLOBAL['timestamp'],
			'filename' => saddslashes($filearr['name']),
			'subject' => trim(shtmlspecialchars($_POST['uploadsubject0'])),
			'attachtype' => $fileext,
			'isimage' => (in_array($fileext, array('jpg','jpeg','gif','png'))?1:0),
			'size' => $filearr['size'],
			'filepath' => $newfilearr['file'],
			'thumbpath' => $newfilearr['thumb'],
			'hash' => $hash
		);
		inserttable('attachments', $insertsqlarr);
		$_SGLOBAL['db']->query('UPDATE '.tname('userspacefields').' SET attachsize=attachsize+'.$filearr['size'].' WHERE uid='.$uid);		

		showresult('指定的文件已經成功\上傳', 'ok');
			
	} elseif ($mode == 1) {
		//遠程上傳
		//檢查類型
		$remoteurl = trim($_POST['remotefile']);
		$fileext = fileext($remoteurl);
		if(!empty($allowtypearr)) {
			if(empty($allowtypearr[$fileext])) showresult('本操作不允許\上傳此類型的資源，請返回檢查');
		}

		//縮略圖
		if(!empty($_POST['uploadthumb1']) && !empty($_SGLOBAL['thumbarr'][$_POST['uploadthumb1']])) {
			$thumbarr = $_SGLOBAL['thumbarr'][$_POST['uploadthumb1']];
		} else {
			$thumbarr = array($_POST['thumbwidth'], $_POST['thumbheight']);
		}
		
		//遠程上傳
		$filearr = saveremotefile($remoteurl, $thumbarr);
		
		//檢查大小
		if(empty($filearr['file'])) showresult('無法獲取遠程文件，請重新嘗試');
		if(!empty($allowtypearr)) {
			if($filearr['size'] > $allowtypearr[$fileext]['maxsize']) {
				@unlink(A_DIR.'/'.$filearr['file']);
				if(!empty($filearr['thumb'])) @unlink(A_DIR.'/'.$filearr['thumb']);
				showresult('上傳的文件大小超過允許\的範圍，請返回檢查');
			}
		}
		if(!empty($_SGLOBAL['group']['attachsize']) && ($attachsize + $filearr['size'] > $_SGLOBAL['group']['attachsize'])) {
			@unlink(A_DIR.'/'.$filearr['file']);
			if(!empty($filearr['thumb'])) @unlink(A_DIR.'/'.$filearr['thumb']);
			showresult('您目前擁有的上傳空間已滿，已經沒有權限繼續上傳附件');
		}

		//數據庫
		if(empty($_POST['uploadsubject1'])) $_POST['uploadsubject1'] = cutstr(filemain($filearr['name']), 50);
		$insertsqlarr = array(
			'uid' => $uid,
			'dateline' => $_SGLOBAL['timestamp'],
			'filename' => saddslashes($filearr['name']),
			'subject' => trim(shtmlspecialchars($_POST['uploadsubject1'])),
			'attachtype' => $filearr['type'],
			'isimage' => (in_array($fileext, array('jpg','jpeg','gif','png'))?1:0),
			'size' => $filearr['size'],
			'filepath' => $filearr['file'],
			'thumbpath' => $filearr['thumb'],
			'hash' => $hash
		);
		inserttable('attachments', $insertsqlarr);
		$_SGLOBAL['db']->query('UPDATE '.tname('userspacefields').' SET attachsize=attachsize+'.$filearr['size'].' WHERE uid='.$uid);		

		showresult('指定的文件已經成功\上傳', 'ok');
		
	} elseif ($mode == 2) {
		//批量上傳
		$okcount = 0;
		for($i=0; $i<$filecount; $i++) {
			$filearr = array(
				'name' => $_FILES['batchfile']['name'][$i],
				'tmp_name' => $_FILES['batchfile']['tmp_name'][$i],
				'size' => $_FILES['batchfile']['size'][$i]
			);
			if(empty($filearr['size']) || empty($filearr['tmp_name'])) continue;
			$fileext = fileext($filearr['name']);
			if(!empty($allowtypearr)) {
				if(empty($allowtypearr[$fileext])) continue;
				if($filearr['size'] > $allowtypearr[$fileext]['maxsize']) continue;
			}
			if(!empty($_SGLOBAL['group']['attachsize']) && ($attachsize + $filearr['size'] > $_SGLOBAL['group']['attachsize'])) continue;
			
			//縮略圖
			if(!empty($_POST['thumb'][$i]) && !empty($_SGLOBAL['thumbarr'][$_POST['thumb'][$i]])) {
				$thumbarr = $_SGLOBAL['thumbarr'][$_POST['thumb'][$i]];
			} else {
				$thumbarr = array($_POST['thumbwidth'], $_POST['thumbheight']);
			}
			
			//上傳
			$newfilearr = savelocalfile($filearr, $thumbarr);
			
			if(empty($newfilearr['file'])) continue;

			//數據庫
			$insertsqlarr = array(
				'uid' => $uid,
				'dateline' => $_SGLOBAL['timestamp'],
				'filename' => saddslashes($filearr['name']),
				'subject' => trim(shtmlspecialchars($_POST['picname'][$i])),
				'attachtype' => $fileext,
				'isimage' => (in_array($fileext, array('jpg','jpeg','gif','png'))?1:0),
				'size' => $filearr['size'],
				'filepath' => $newfilearr['file'],
				'thumbpath' => $newfilearr['thumb'],
				'hash' => $hash
			);
			inserttable('attachments', $insertsqlarr);
			
			$attachsize = $attachsize + $filearr['size'];
			$okcount++;
		}
		
		if($okcount) {
			$_SGLOBAL['db']->query('UPDATE '.tname('userspacefields').' SET attachsize='.$attachsize.' WHERE uid='.$uid);
		} else {
			showresult('上傳文件失敗，請您稍後嘗試重新上傳');
		}
		if($okcount < $filecount) {
			showresult(($filecount-$okcount).'個文件不符合上傳要求無法上傳，其餘文件上傳成功\', 'ok');
		} else {
			showresult('指定的文件已經成功\上傳', 'ok');
		}
	}
}

//函數
function showresult($message, $type='error') {
	
	global $hash, $noinsert, $aid;

	$attacharr = selecttable('attachments', array(), array('hash'=>$hash), 'ORDER BY dateline');
	$listtext = getuploadinserthtml($attacharr, $noinsert, $aid);

	$listtext = addcslashes($listtext, '"');
	$message = addcslashes($message, '"');
	
	if(empty($message)) {
		$typestr = 'msg.style.display = "none";
					msgok.style.display = "none";';
	} else {
		if($type == 'ok') {
			$typestr = 'msg.style.display = "none";
						msgok.style.display = "";
						msgok.innerHTML = "'.$message.'";
						subject0.value = "";
						subject1.value = "";
						localfile.outerHTML = localfile.outerHTML;
						remotefile.value = "http://";
						';
		} else {
			$typestr = 'msg.style.display = "";
						msgok.style.display = "none";
						msg.innerHTML =  "'.$message.'";
						';
		}
	}

	print <<<END
	<script language="javascript">
	<!--

	var list = parent.document.getElementById("divshowupload");
	var msg = parent.document.getElementById("divshowuploadmsg");
	var msgok = parent.document.getElementById("divshowuploadmsgok");
	var subject0 = parent.document.getElementById("uploadsubject0");
	var subject1 = parent.document.getElementById("uploadsubject1");
	var localfile = parent.document.getElementById("localfile");
	var remotefile = parent.document.getElementById("remotefile");
	var pf = parent.document.getElementById("phpframe");
	localfile.value = "";
	pf.src = "about:blank";
	list.innerHTML = "$listtext";
	$typestr
	//-->
	</script>
END;
	exit;
}

function getallowtype($sqltype='') {
	global $_SGLOBAL;

	$sqltype = strtolower($sqltype);
	$types = array();
	if(empty($sqltype)) {
		$sqltypewhere = '';
		$query = $_SGLOBAL['db']->query('SELECT * FROM '.tname('attachmenttypes'));
	} else {
		$sqltypearr = explode(',', $sqltype);
		$defaulttype = array('fileext' => '','maxsize' => '9999999999');
		foreach ($sqltypearr as $value) {
			$types[$value] = $defaulttype;
		}
		$query = $_SGLOBAL['db']->query('SELECT * FROM '.tname('attachmenttypes').' WHERE fileext IN ('.simplode($sqltypearr).')');
	}
	while ($type = $_SGLOBAL['db']->fetch_array($query)) {
		$types[$type['fileext']] = $type;
	}
	return $types;
}

?>