<?php
define('THIS_SCRIPT', 'spacemanage');
require 'space_global.php';
require_once INC_PATH.'DV_Encoding.class.php';
require_once INC_PATH.'BoardCache.class.php';
require_once INC_PATH.'space.functions.php';
require_once INC_PATH.'FileHandler.class.php';
require_once INC_PATH.'image_misc.functions.php';
$lang = load_lang($lang,'space.error');
$lang = load_lang($lang,'spacemanage');

if( $spaceUserID <= 0 OR $isSpaceOwner === false ){
	spaceHeader(array('stats'=>$lang['HeaderTitle1'],'isSystem'=>true,'topEnable'=>true,'navEnable'=>true));
	spaceShowMsg($lang['spaceError.str12'],0,'',true);
	exit;
}

$action = strtolower($action);
$_stats = $lang['HeaderTitle1'];
$_isSystem = true;
$_blnspaceConfigUpdated = false;
$_objCache = false;
session_start();
if (empty($_SESSION['spaceManage'])) {
	if ($action === 'login') {
	//Start Page_ChkLogin
		$_stats = $lang['tpl.str1'];
		$_isSystem = false;
		if( ChkPost() === false ){
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>true,'navEnable'=>true));
			spaceShowMsg($lang['spaceError.str0'],0,'',true);
			exit;
		}
		if( $fsetting['logingetcode'] == 1 AND ($userinfo['getcode'] == '' OR $userinfo['getcode'] != $getcode) ){
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>true,'navEnable'=>true));
			spaceShowMsg($lang['spaceError.str5']);
			exit;
		}
		$password = trim($password);
		if( $password === '' ){
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>true,'navEnable'=>true));
			spaceShowMsg($lang['spaceError.str9']);
			exit;
		} else{
			$password = dv_md5($password);
		}
		$_strRedirectUrl = trim($f);
		if( $_strRedirectUrl === '' ){
			$_strRedirectUrl = 'spacemanage.php';
		}
		$_strDbPassword = $db->scalar("SELECT password FROM {$dv}space_user WHERE userid='{$userid}'");
		if( $_strDbPassword === false ){
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>true,'navEnable'=>true));
			spaceShowMsg($lang['spaceError.str2']);
			exit;
		}
		if( $_strDbPassword != $password ){
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>true,'navEnable'=>true));
			spaceShowMsg($lang['spaceError.str13']);
			exit;
		}
		$_SESSION['spaceManage'] = $userid;
		setcookie(session_name(),session_id());
		header("Location:{$_strRedirectUrl}");
		exit;
	//End Page_ChkLogin
	} else {
	//Start Page_Login
		$_stats = $lang['tpl.str2'];
		$_isSystem = false;
		if( $f != '' ){
			$_strRedirectUrl = trim($f);
		} elseif( $_SERVER['QUERY_STRING'] != '' ){
			$_strRedirectUrl = "spacemanage.php?{$_SERVER['QUERY_STRING']}";
		} else{
			$_strRedirectUrl = 'spacemanage.php';
		}
		spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>true,'navEnable'=>true));
		require printout('spacemanage.login');
		spaceFooter();
	//End Page_Login
	}
} else {
	$s = strtolower($_GET['s']);
	$t = strtolower($_GET['t']);
	$m = strtolower($_GET['m']);
	$action = strtolower($_GET['action']);
	if ($s === '1') {
		if( empty($t) ){
			$t = 1;
			$_sTypeID = 0;
		} else{
			$_sTypeID = $t - 1;
		}
		$_tStr = $lang['tpl.navlink'][$t];
		$_stats .= ' - '.$_tStr;
		if (!isset($m) OR $m <= 0) {
			$m = 3;
		}
		if( $m === '1' ){	//	发表文章、收藏、链接、音乐、交易、相册
			if( $action === 'savepost' ){
				spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
				Post_Save(true);
				exit;
			} else{
			}
		} elseif( $m === '2' ){
			if( $action === 'save' ){
				spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
				Page_UserInput_Cat_Save();
				exit;
			} elseif( $action === 'del' ){
				spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
				Page_UserInput_Cat_Del();
				exit;
			} else{
			}
		} elseif( $m === '3' ){
			if( $action === 'del' ){
				spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
				Page_UserInput_mTopic_Del();
				exit;
			} else{
			}
		} else{
		}
	} elseif( $s === '2' ){
		$_tStr = $lang['HeaderTitle2'];
		$_stats .= ' - '.$_tStr;
		if( $action === 'del' ){
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
			Page_UserInput_mPost_Del();
				exit;
		} else{
		}
	} elseif( $s === '3' ){
		$_tStr = $lang['HeaderTitle3'];
		$_stats .= ' - '.$_tStr;
		if( $action === 'del' ){
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
			Page_UserFile_Del();
			exit;
		}
	} elseif( $s === '4' ){
		$_tStr = $lang['HeaderTitle4'];
		$_stats .= ' - '.$_tStr;
		if( $action === 'saveskin' ){
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
			Page_SaveSkins();
			exit;
		}
	} elseif( $s === '5' ){
		$_intIndex = ( ( $t >= 1 AND $t <= 4 ) ? $t : 1 );
		$_tStr = $lang['HeaderTitle5_1'][$_intIndex];
		$_stats .= ' - '.$lang['HeaderTitle5'].' - '.$_tStr;
		if( $t === '1' ){
			if( $action === 'save' ){
				spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
				Page_UserSetting_Info_Save();
				exit;
			}
		} elseif( $t === '2' ){
			if( $action === 'save' ){
				spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
				Page_UserSetting_Pass_Save();
				exit;
			}
		} elseif( $t === '3' ){
			if( $action === 'save' ){
				spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
				Page_UserSetting_Set_Save();
				exit;
			}
		} elseif( $t === '4' ){
			if( $action === 'save' ){
				spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
				Page_UserSetting_Key_Save();
				exit;
			} elseif( $action === 'del' ){
				spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
				Page_UserSetting_Key_Del();
				exit;
			}
		} else{
			if( $action === 'save' ){
				spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
				Page_UserSetting_Info_Save();
				exit;
			}
		}
	} elseif( $s === '6' ){//数据更新
		if( $t === '1' ) $_tStr = $lang['HeaderTitle6_1'];
		$_stats .= ' - '.$lang['HeaderTitle6'].' - '.$_tStr;
		spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
		Update_UserCatToXml();
		exit;
	} elseif( $s === '7' ){//数据统计
		$_tStr = $lang['HeaderTitle7'];
		$_stats .= ' - '.$lang['HeaderTitle7'].' - '.$_tStr;
		if( $t === '1' ){//更新用户笔名
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
			Update_UserNickName();
			exit;
		} elseif( $t === '2' ){
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
			Update_UserCatData();
			exit;
		} elseif( $t === '3' ){
			spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
			Update_UserspaceData();
			exit;
		}
	} elseif ('8' === $s) {	//	申请今日之星
	}

	$_isSystem = false;
	$_topEnable = true;
	$_navEnable = false;
	spaceHeader(array('stats'=>$_stats,'isSystem'=>$_isSystem,'topEnable'=>$_topEnable,'navEnable'=>$_navEnable));
	require printout('spacemanage');
	spaceFooter();
}

function &getspaceKeyWord($argkeyid){
	global $dv,$db;
	if( !is_numeric($argkeyid) ) return false;
	return $db->getResultSet("SELECT keyid,userid,keyword,nkeyword,linkurl,linktitle,newwindows FROM {$dv}space_keyword WHERE keyid='{$argkeyid}' AND userid='{$GLOBALS['userid']}'");
}

function getspaceKeyWord2($arguserid){
	global $dv,$db;
	$returnval = false;
	if (!is_numeric($arguserid) OR $arguserid <= 0) {
		return $returnval;
	}
	$returnval =& $db->getResultSet("SELECT keyid,userid,keyword,nkeyword,linkurl,linktitle,newwindows FROM {$dv}space_keyword WHERE userid='{$arguserid}' ORDER BY keyid");
	return $returnval;
}

function &getspaceSysCat(){
	global $dv,$db;
	return $db->getResultSet("SELECT scatid,scattitle,scatnote,ucatnum,topicnum,postnum,todaynum,stype,lastuptime FROM {$dv}space_syscat WHERE stype=0 ORDER BY scatid");
}

function &getspacePost($_argUserID,$_argSTypeID,$_argKeyWord=''){
	global $dv,$db,$spaceSystemSetting;
	$_argKeyWord = trim($_argKeyWord);
	$_strWhereStmt = '';
	if( $_argKeyWord !== '' ){
		$_strWhereStmt = " AND (title LIKE '%{$_argKeyWord}%' OR content LIKE '%{$_argKeyWord}%') ";
	}
	$_intPage = intval($GLOBALS['page']);
	if( $_intPage < 1 ) $_intPage = 1;
	if ($spaceSystemSetting[7] < 1) {
		$spaceSystemSetting[7] = 20;
	}
	$_arrReturnVal = array('RecordCount'=>0,'PageCount'=>0,'AbsolutePage'=>$_intPage,'PageSize'=>$spaceSystemSetting[7],'ResultSet'=>false);
	$_strWhereStmt = " ";
	if( ( $_arrReturnVal['RecordCount'] = $db->scalar("SELECT COUNT(1) FROM {$dv}space_post WHERE userid='{$_argUserID}' AND stype='{$_argSTypeID}' AND parentid=0 {$_strWhereStmt}",array('debug'=>false)) ) > 0 ){
		$_arrReturnVal['PageCount'] = ceil( (float)$_arrReturnVal['RecordCount'] / (float)$_arrReturnVal['PageSize'] );
		if( $_arrReturnVal['AbsolutePage'] > $_arrReturnVal['PageCount'] ){
			$_arrReturnVal['AbsolutePage'] = $_arrReturnVal['PageCount'];
		}
		if( $_arrReturnVal['AbsolutePage'] < 1 ){
			$_arrReturnVal['AbsolutePage'] = 1;
		}
		$_arrReturnVal['ResultSet'] =& $db->getResultSet("SELECT rootid,catid,scatid,userid,username,title,content,jointime,stype,postid FROM {$dv}space_post WHERE userid='{$_argUserID}' AND stype='{$_argSTypeID}' AND parentid=0 {$_strWhereStmt} ORDER BY postid DESC",array('absolutePage'=>$_arrReturnVal['AbsolutePage'],'pageSize'=>$_arrReturnVal['PageSize']));
	}
	return $_arrReturnVal;
}

function &getspacePost2($_argUserID,$_argKeyWord=''){
	global $dv,$db,$spaceSystemSetting;
	$_argKeyWord = trim($_argKeyWord);
	$_strWhereStmt = '';
	if( $_argKeyWord !== '' ){
		$_strWhereStmt = " AND (title LIKE '%{$_argKeyWord}%' OR content LIKE '%{$_argKeyWord}%') ";
	}
	$_intPage = intval($GLOBALS['page']);
	if( $_intPage < 1 ) $_intPage = 1;
	if ($spaceSystemSetting[7] < 1) {
		$spaceSystemSetting[7] = 20;
	}
	$_arrReturnVal = array('RecordCount'=>0,'PageCount'=>0,'AbsolutePage'=>$_intPage,'PageSize'=>$spaceSystemSetting[7],'ResultSet'=>false);
	$_strWhereStmt = " ";
	if( ( $_arrReturnVal['RecordCount'] = $db->scalar("SELECT COUNT(1) FROM {$dv}space_post WHERE userid='{$_argUserID}' AND parentid<>0 {$_strWhereStmt}",array('debug'=>false)) ) > 0 ){
		$_arrReturnVal['PageCount'] = ceil( (float)$_arrReturnVal['RecordCount'] / (float)$_arrReturnVal['PageSize'] );
		if( $_arrReturnVal['AbsolutePage'] > $_arrReturnVal['PageCount'] ){
			$_arrReturnVal['AbsolutePage'] = $_arrReturnVal['PageCount'];
		}
		if( $_arrReturnVal['AbsolutePage'] < 1 ){
			$_arrReturnVal['AbsolutePage'] = 1;
		}
		$_arrReturnVal['ResultSet'] =& $db->getResultSet("SELECT rootid,catid,scatid,userid,username,title,content,jointime,stype,postid FROM {$dv}space_post WHERE userid='{$_argUserID}' AND parentid<>0 {$_strWhereStmt} ORDER BY postid DESC",array('absolutePage'=>$_arrReturnVal['AbsolutePage'],'pageSize'=>$_arrReturnVal['PageSize']));
	}
	return $_arrReturnVal;
}

function &getspacePostByTopicID($_argTopicID){
	global $dv,$db;
	if( !is_numeric($_argTopicID) ) return false;
	return $db->getResultSet("SELECT postid,spaceuserid,catid,scatid,parentid,rootid,userid,username,title,content,jointime,ip,stype,isupfile,islock FROM {$dv}space_post WHERE rootid='{$_argTopicID}'",array('pageSize'=>1));
}

function &getspaceUserCat(){
	global $dv,$db;
	return $db->getResultSet("SELECT ucatid,userid,ucattitle,ucatnote,opentime,utype,topicnum,postnum,todaynum,isview,lastuptime FROM {$dv}space_usercat WHERE userid='{$GLOBALS['userid']}'");
}

function &getspaceUserCat2($_argUCatID){
	global $dv,$db;
	return $db->getResultSet("SELECT ucatid,userid,ucattitle,ucatnote,opentime,utype,topicnum,postnum,todaynum,isview,lastuptime FROM {$dv}space_usercat WHERE userid='{$GLOBALS['userid']}' AND ucatid='{$_argUCatID}'");
}

function &getspaceUserCat3($_argUCatID,$_argUType,$_argUserID){
	global $dv,$db;
	$_result = false;
	if( $_query = $db->query("SELECT ucatid,userid,ucattitle,ucatnote,opentime,utype,topicnum,postnum,todaynum,isview,lastuptime FROM {$dv}space_usercat WHERE ucatid='{$_argUCatID}' AND utype='{$_argUType}' AND userid='{$_argUserID}'") ){
		$_result =& $db->fetch_array($_query);
	}
	return $_result;
}

function &getspaceUserCat4($_argUserID,$_argUType){
	global $dv,$db;
	return $db->getResultSet("SELECT ucatid,userid,ucattitle,ucatnote,opentime,utype,topicnum,postnum,todaynum,isview,lastuptime FROM {$dv}space_usercat WHERE userid='{$_argUserID}' AND utype='{$_argUType}' ORDER BY ucatid");
}

function &getspaceUpFile($_argUserID,$_argKeyWord=''){
	global $dv,$db,$spaceSystemSetting,$s,$t,$m;
	$_argKeyWord = trim($_argKeyWord);
	$_strWhereStmt = '';
	if( $_argKeyWord !== '' ){
		$_strWhereStmt = " AND (title LIKE '%{$_argKeyWord}%' OR content LIKE '%{$_argKeyWord}%') ";
	}
	switch($m){
		case '2'://图片
			$_strWhereStmt .= " AND filetype=1 ";
			break;
		case '3'://压缩
			$_strWhereStmt .= " AND filetype=5 ";
			break;
		case '4'://文档
			$_strWhereStmt .= " AND filetype=6 ";
			break;
		case '5'://媒体
			$_strWhereStmt .= " AND filetype IN(2,3,4) ";
			break;
	}
	if ($spaceSystemSetting[7] < 1) {
		$spaceSystemSetting[7] = 20;
	}
	$_intPage = intval($GLOBALS['page']);
	if( $_intPage < 1 ) $_intPage = 1;
	$_arrReturnVal = array('RecordCount'=>0,'PageCount'=>0,'AbsolutePage'=>$_intPage,'PageSize'=>$spaceSystemSetting[7],'ResultSet'=>false);
	$_strWhereStmt = " ";
	if( ( $_arrReturnVal['RecordCount'] = $db->scalar("SELECT COUNT(1) FROM {$dv}space_upfile WHERE userid='{$_argUserID}' {$_strWhereStmt}",array('debug'=>false)) ) > 0 ){
		$_arrReturnVal['PageCount'] = ceil( (float)$_arrReturnVal['RecordCount'] / (float)$_arrReturnVal['PageSize'] );
		if( $_arrReturnVal['AbsolutePage'] > $_arrReturnVal['PageCount'] ){
			$_arrReturnVal['AbsolutePage'] = $_arrReturnVal['PageCount'];
		}
		if( $_arrReturnVal['AbsolutePage'] < 1 ){
			$_arrReturnVal['AbsolutePage'] = 1;
		}
		$_arrReturnVal['ResultSet'] =& $db->getResultSet("SELECT id,spaceuserid,username,catid,stype,topicid,postid,istopic,title,filename,filetype,filesize,filenote,downnum,viewnum,dateandtime,previewimage,islock,sfilename FROM {$dv}space_upfile WHERE userid='{$_argUserID}' {$_strWhereStmt} ORDER BY dateandtime DESC",array('absolutePage'=>$_arrReturnVal['AbsolutePage'],'pageSize'=>$_arrReturnVal['PageSize']));
	}
	return $_arrReturnVal;
}

function &getspaceSkin(){
	global $dv,$db,$s,$t,$m;
	$_intPage = intval($GLOBALS['page']);
	if( $_intPage < 1 ) $_intPage = 1;
	$_arrReturnVal = array('RecordCount'=>0,'PageCount'=>0,'AbsolutePage'=>$_intPage,'PageSize'=>9,'ResultSet'=>false);
	$_strWhereStmt = " ";
	if( ( $_arrReturnVal['RecordCount'] = $db->scalar("SELECT COUNT(1) FROM {$dv}space_skins",array('debug'=>false)) ) > 0 ){
		$_arrReturnVal['PageCount'] = ceil( (float)$_arrReturnVal['RecordCount'] / (float)$_arrReturnVal['PageSize'] );
		if( $_arrReturnVal['AbsolutePage'] > $_arrReturnVal['PageCount'] ){
			$_arrReturnVal['AbsolutePage'] = $_arrReturnVal['PageCount'];
		}
		if( $_arrReturnVal['AbsolutePage'] < 1 ){
			$_arrReturnVal['AbsolutePage'] = 1;
		}
		$_arrReturnVal['ResultSet'] =& $db->getResultSet("SELECT s_id,s_skinname,s_path,s_viewpic,s_info,s_builder FROM {$dv}space_skins");
	}
	return $_arrReturnVal;
}

function Page_UserInput_mTopic_Del(){
	global $lang,$s,$t,$_sTypeID,$m,$keyword,$_tpl_skinPath,$_tpl_spaceName,$_tpl_spaceUrl,$userid,$spaceUserID;
	global $dv,$db,$_objCache,$userid,$spaceUserInfo;
	$_arrTopicID = $GLOBALS['topicid'];
	$_iTopic = $GLOBALS['itopic'];
	if (empty($_arrTopicID) OR !is_array($_arrTopicID) OR !is_numeric($_iTopic)) {
		spaceShowMsg($lang['spaceError.str7']);
		return false;
	}
	if( checkIDList(implode(',',$_arrTopicID)) === false ){
		spaceShowMsg($lang['spaceError.str7'],0);
		return false;
	}
	if( $_iTopic != 0 AND $_iTopic != 1 ){
		spaceShowMsg($lang['spaceError.str7'],0);
		return false;
	}
	$_uCatID = intval($GLOBALS['ucatid']);
	if( empty($_uCatID) OR !is_numeric($_uCatID) ){
		$_uCatID = 0;
	}
	if( $_uCatID == -1 AND $_iTopic == 1 ){//检测目标栏目是否合法
		spaceShowMsg($lang['spaceError.str46'],0);
		return false;
	}
	if ($_uCatID > 0) {
		$_arrspaceUserCat =& getspaceUserCat2($_uCatID);
		if( $_arrspaceUserCat === false ){
			spaceShowMsg($lang['spaceError.str46'],0);
			return false;
		} else{
			$_sTypeID_a = $_arrspaceUserCat[0]['utype'];
		}
	}
	$_Num_T = $_Num_F = $_Num_L = $_Num_P = $_Num_M = 0;
	$_strDateNow = TIME_NOW;
	foreach( $_arrTopicID as $_currTopicID ){
		$_arrspaceTopicInfo = false;
		if( $_iTopic == 0 OR $_iTopic == 1 ){
			if( !is_numeric($userid) ) continue;
			if( $_query = $db->query("SELECT topicid,catid,scatid,userid,username,title,titlenote,posttime,child,hits,isview,islock,stype,lastposttime,isbest,s_key,weather,visituser,paymoney,paynumber,paytime,trackbacks FROM {$dv}space_topic WHERE userid='{$userid}' AND topicid='{$_currTopicID}'",array('pageSize'=>1,'debug'=>false)) ){
				$_arrspaceTopicInfo =& $db->fetch_array($_query);
			}
			if( $_arrspaceTopicInfo === false ) continue;
		}
		if( $_iTopic == 0 ){
			$_intTopicNum = 0;
			if( dateDiff('d',$_arrspaceTopicInfo['posttime'],$_strDateNow) == 0 ){
				$_intTopicNum = 1;
			}
			if( intval($_arrspaceTopicInfo['stype']) == 0 ){
				$_Num_T = 1;
			} elseif( intval($_arrspaceTopicInfo['stype']) == 1 ){
				$_Num_F = 1;
			} elseif( intval($_arrspaceTopicInfo['stype']) == 2 ){
				$_Num_L = 1;
			} elseif( intval($_arrspaceTopicInfo['stype']) == 4 ){
				$_Num_P = 1;
			} elseif (intval($_arrspaceTopicInfo['stype']) == 5) {
				$_Num_M = 1;
			}
			$_arrspacePost =& getspacePostByTopicID($_currTopicID);
			$_intPostNum = 0;
			$_intTPostNum = 0;
			if( !empty($_arrspacePost) AND is_array($_arrspacePost) ){
				foreach( $_arrspacePost as $_val ){
					$_intPostNum++;
					if( dateDiff('d',$_val['jointime'],$_strDateNow) == 0 ) {
						$_intTPostNum++;
					}
					if( $_val['isupfile'] == 1 ){//上传文件清理
						SysDeleteFile($_val['postid']);
					}
				}
			}
			$_intPostNum--;
			$_intTopicNum += $_intTPostNum;	
			
			$db->query("DELETE FROM {$dv}space_post WHERE rootid='{$_currTopicID}'");

			//更新系统数据
			$db->query("UPDATE {$dv}space_syscat SET topicnum=topicnum-1,postnum=postnum-'{$_intPostNum}',todaynum=todaynum-'{$_intTopicNum}' WHERE scatid IN ({$_arrspaceTopicInfo['scatid']},{$spaceUserInfo['syscatid']})");

			$db->query("UPDATE {$dv}space_system SET s_topicnum=s_topicnum-'{$_Num_T}',s_postnum=s_postnum-'{$_intPostNum}',s_photonum=s_photonum-'{$_Num_P}',s_medianum=s_medianum-'{$_Num_M}',s_favnum=s_favnum-'{$_Num_F}',s_todaynum=s_todaynum-'{$_intTopicNum}'");

			//更新用户总数据
			$db->query("UPDATE {$dv}space_user SET topicnum=topicnum-'{$_Num_T}',postnum=postnum-'{$_intPostNum}',favnum=favnum-'{$_Num_F}',photonum=photonum-'{$_Num_P}',medianum=medianum-'{$_Num_M}',todaynum=todaynum-'{$_intTopicNum}' WHERE userid='{$spaceUserID}'");

			//更新用户栏目数据
			$db->query("UPDATE {$dv}space_usercat SET topicnum=topicnum-1,postnum=postnum-'{$_intPostNum}',todaynum=todaynum-'{$_intTopicNum}' WHERE ucatid='{$_arrspaceTopicInfo['catid']}'");

			//删除主题并按日期更新主题缓存
			if ($db->query("DELETE FROM {$dv}space_topic WHERE topicid='{$_currTopicID}'")) {
				global $spaceUserInfo;
				updateDiaryTopic(array('Action' => 'delete', 'userid' => $_arrspaceTopicInfo['userid'], 'DiaryTopic' => &$spaceUserInfo['diary_topic'], 'PostTime' => $_arrspaceTopicInfo['posttime'], 'TopicID' => $_currTopicID));
			}

		} elseif( $_iTopic == 1 ){
			$_intTopicNum = 0;
			if( dateDiff('d',$_arrspaceTopicInfo['posttime'],$_strDateNow) == 0 ){
				$_intTopicNum = 1;
			}
			if( intval($_arrspaceTopicInfo['stype']) == 0 ){
				$_Num_T = 1;
			} elseif( intval($_arrspaceTopicInfo['stype']) == 1 ){
				$_Num_F = 1;
			} elseif( intval($_arrspaceTopicInfo['stype']) == 2 ){
				$_Num_L = 1;
			} elseif( intval($_arrspaceTopicInfo['stype']) == 4 ){
				$_Num_P = 1;
			} elseif( intval($_arrspaceTopicInfo['stype']) == 5 ){
				$_Num_M = 1;
			}
			$_arrspacePost =& getspacePostByTopicID($_currTopicID);
			$_intPostNum = 0;
			$_intTPostNum = 0;
			if( !empty($_arrspacePost) AND is_array($_arrspacePost) ){
				foreach( $_arrspacePost as $_val ){
					$_intPostNum++;
					if( dateDiff('d',$_val['jointime'],$_strDateNow) == 0 ) {
						$_intTPostNum++;
					}
					if( $_val['isupfile'] == 1 ){//上传文件移动
						$db->query("UPDATE {$dv}space_upfile SET catid='{$_uCatID}',stype='{$_sTypeID_a}' WHERE postid='{$_val['postid']}'");
					}
				}
			}
			$_intPostNum--;
			$_intTopicNum += $_intTPostNum;

			$db->query("UPDATE {$dv}space_post SET catid={$_uCatID},stype='{$_sTypeID_a}' WHERE rootid='{$_currTopicID}'");

		//更新用户栏目数据
			$db->query("UPDATE {$dv}space_usercat SET topicnum=topicnum-1,postnum=postnum-'{$_intPostNum}',todaynum=todaynum-'{$_intTopicNum}' WHERE ucatid='{$_arrspaceTopicInfo['catid']}'");
			$db->query("UPDATE {$dv}space_usercat SET topicnum=topicnum+1,postnum=postnum+'{$_intPostNum}',todaynum=todaynum+'{$_intTopicNum}' WHERE ucatid='{$_uCatID}'");

		//移动主题
			$db->query("UPDATE {$dv}space_topic SET catid='{$_uCatID}',stype='{$_sTypeID_a}' WHERE topicid='{$_currTopicID}'");
		}
		$_Num_T = $_Num_F = $_Num_L = $_Num_P = 0;
	}
	//更新系统缓存数据
	updatespaceConfigCache();
	//更新用户首页数据
	Update_TopicToXml();
	spaceShowMsg($lang['spaceError.str47'],1);
}

function updatespaceConfigCache(){
	global $db;
	static $_blnspaceConfigUpdated = false;
	static $_objCache = null;
	if( $_blnspaceConfigUpdated === false ){
		$_blnspaceConfigUpdated = true;
		if( empty($_objCache) ){
			$_objCache = new BoardCache($db);
		}
		$_objCache->createspaceConfig();
	}
}
function selected_templates_prev(){
	global $dv,$db;
	$_arrspaceConfig_UserCat =& getUserCatFromXmlData();
	$_arrspaceConfig_UserCat['selected_templates_prev'] = 'default.';
	saveUserCatToXmlData();
}

//更新用户栏目数据
function Update_UserCatToXml(){
	global $lang,$dv,$db;
	$_arrspaceConfig_UserCat =& getUserCatFromXmlData();
	$_arrspaceConfig_UserCat['result_set'] =& $db->getResultSet("SELECT ucatid, userid, ucattitle, ucatnote, opentime, utype, topicnum, postnum, todaynum, isview, lastuptime FROM {$dv}space_usercat WHERE userid='{$GLOBALS['userid']}' ORDER BY utype, ucatid");
	if( $_arrspaceConfig_UserCat['result_set'] === false ){
		$_arrspaceConfig_UserCat['result_set'] = array();
	}

	//更新首页主题数据
	Update_TopicToXml(false);
	//更新首页链接数据
	Update_LinkToXml(false);
	//更新首页图片数据
	Update_PhotoToXml(false);
	//更新首页评论数据
	Update_PostToXml(false);
	//更新关键字转换数据
	Update_KeyWordToXml(false);
	//更新音乐数据
	Update_MusicToXml(false);
	
	saveUserCatToXmlData();

	spaceShowMsg($lang['spaceError.str25'],1);
	return true;
}//end function Update_UserCatToXml

//更新首页主题数据
function Update_TopicToXml($mustupdatedb=true){
	global $dv,$db,$lang,$spaceUserCat,$spaceSetting,$spaceName,$_objEnc;
	if( !is_numeric($spaceSetting[6]) ){
		$spaceSetting[6] = 10;
	}
	$spaceconfig_usercat =& getUserCatFromXmlData();
	if ($spaceSetting[6] < 1) {
		$spaceSetting[6] = 20;
	}
	unset($spaceconfig_usercat['spacetopic']);
	if ($query = $db->query("SELECT /*!40001 SQL_CACHE */ topicid,catid,scatid,userid,username,title,titlenote,posttime,child,hits,isview,islock,stype,lastposttime,isbest,s_key,weather FROM {$dv}space_topic /*!32312 USE INDEX(newly_topic_by_user) */ WHERE userid='{$GLOBALS['spaceUserID']}' AND stype>=0 AND islock<3 ORDER BY topicid DESC",array('pageSize'=>$spaceSetting[6]))) {
		while ($topicinfo =& $db->fetch_array($query)) {
			$titlenote = trim($topicinfo['titlenote']);
			if ('' === $titlenote) {
				$titlenote = trim($db->scalar("SELECT content FROM {$dv}space_post WHERE parentid=0 AND rootid='{$topicinfo['topicid']}'"));
			}
			if ($titlenote !== '' ) {
				$_ubbcode = stripslashes(spaceUbbCode($titlenote, false));
				$titlenote =& getTitleNote($_ubbcode, 0, $spaceSetting[2]);
				$titlenote =& _imgaddjscode($titlenote);
				$db->query("UPDATE {$dv}space_topic SET titlenote='".$db->escape_string($titlenote)."' WHERE topicid='{$topicinfo['topicid']}'");
			}
			$topicinfo['titlenote'] = $titlenote;
			$spaceconfig_usercat['spacetopic'][] =& $topicinfo;
		}
		$db->free_result($query);
	}
	if (empty($spaceconfig_usercat['spacetopic'])) {
		$spaceconfig_usercat['spacetopic'] = array();
	}
	if (true === $mustupdatedb) {
		saveUserCatToXmlData();
	}
}//end function Update_TopicToXml

function Update_LinkToXml($_argUpdateDataBase=true){//更新首页链接数据
	global $dv,$db,$lang,$spaceUserCat,$spaceSetting,$spaceName,$_objEnc;
	$_arrspaceConfig_UserCat =& getUserCatFromXmlData();
	$_arrspaceConfig_UserCat['spacelink'] =& $db->getResultSet("SELECT topicid,catid,scatid,userid,username,title,titlenote,posttime,child,hits,isview,islock,stype,lastposttime,isbest,s_key,weather,title AS content FROM {$dv}space_topic WHERE userid='{$GLOBALS['spaceUserID']}' AND stype=2 AND islock<3 ORDER BY lastposttime DESC",array('pageSize'=>5));
	if( $_arrspaceConfig_UserCat['spacelink'] === false ){
		$_arrspaceConfig_UserCat['spacelink'] = array();
	} else{
		foreach( $_arrspaceConfig_UserCat['spacelink'] as $_index => $_val ){
			$_strContent = $_val['content'].'';
			if( $_strContent === '' ){
				$_strContent = $db->scalar("SELECT content FROM {$dv}space_post WHERE parentid=0 AND rootid='{$_val['topicid']}'");
			}
			$_arrspaceConfig_UserCat['spacelink'][$_index]['content'] = $_strContent;
		}
	}
	if( $_argUpdateDataBase === true ){
		saveUserCatToXmlData();
	}
}//end function Update_LinkToXml

function Update_PhotoToXml($_argUpdateDataBase=true){//更新首页图片数据
	global $dv,$db,$lang,$spaceUserCat,$spaceSetting,$spaceName,$_objEnc;
	$_arrspaceConfig_UserCat =& getUserCatFromXmlData();
	$_arrspaceConfig_UserCat['spacephoto'] =& $db->getResultSet("SELECT id,spaceuserid,username,catid,stype,topicid,postid,istopic,title,filename,filetype,filesize,filenote,downnum,viewnum,dateandtime,previewimage,islock FROM {$dv}space_upfile WHERE stype=4 AND istopic=0 AND islock<3 AND spaceuserid='{$GLOBALS['spaceUserID']}' ORDER BY dateandtime DESC",array('pageSize'=>5));
	if( $_arrspaceConfig_UserCat['spacephoto'] === false ){
		$_arrspaceConfig_UserCat['spacephoto'] = array();
	}
	if( $_argUpdateDataBase === true ){
		saveUserCatToXmlData();
	}
}

function Update_PostToXml($_argUpdateDataBase=true){//更新首页评论数据
	global $dv,$db,$lang,$spaceUserCat,$spaceSetting,$spaceName,$_objEnc;
	if( !is_numeric($spaceSetting[3]) ){
		$spaceSetting[3] = 10;
	}
	$_arrspaceConfig_UserCat =& getUserCatFromXmlData();
	$_arrspaceConfig_UserCat['spacepost'] =& $db->getResultSet("SELECT postid,catid,scatid,parentid,rootid,userid,username,title,SUBSTRING(content, 1, 50),jointime,ip,stype FROM {$dv}space_post WHERE spaceuserid='{$GLOBALS['spaceUserID']}' AND parentid>0 AND stype IN(0,3,4) ORDER BY jointime DESC",array('pageSize'=>$spaceSetting[3]));
	if( $_arrspaceConfig_UserCat['spacepost'] === false ){
		$_arrspaceConfig_UserCat['spacepost'] = array();
	}
	if( $_argUpdateDataBase === true ){
		saveUserCatToXmlData();
	}
}

function Update_KeyWordToXml($_argUpdateDataBase=true){//更新关键字转换数据
	global $dv,$db,$lang,$spaceUserCat,$spaceSetting,$spaceName,$_objEnc;
	if( !is_numeric($spaceSetting[3]) ){
		$spaceSetting[3] = 10;
	}
	$_arrspaceConfig_UserCat =& getUserCatFromXmlData();
	$_arrspaceConfig_UserCat['spacekeyword'] =& $db->getResultSet("SELECT postid,catid,scatid,parentid,rootid,userid,username,title,content,jointime,ip,stype FROM {$dv}space_post WHERE spaceuserid='{$GLOBALS['spaceUserID']}' AND parentid>0 AND stype IN(0,3,4) ORDER BY jointime DESC",array('pageSize'=>$spaceSetting[3]));
	if( $_arrspaceConfig_UserCat['spacekeyword'] === false ){
		$_arrspaceConfig_UserCat['spacekeyword'] = array();
	}
	if( $_argUpdateDataBase === true ){
		saveUserCatToXmlData();
	}
}
function Update_MusicToXml($_argUpdateDataBase = true)	//	更新音乐数据
{
	global $dv,$db,$lang,$spaceUserCat,$spaceSetting,$spaceName,$_objEnc;
	if( !is_numeric($spaceSetting[3]) ){
		$spaceSetting[3] = 10;
	}
	$_arrspaceConfig_UserCat =& getUserCatFromXmlData();
	$_arrspaceConfig_UserCat['spacemusic'] =& $db->getResultSet("SELECT postid,catid,scatid,parentid,rootid,userid,username,title,SUBSTRING(content, 1, 50),jointime,ip,stype FROM {$dv}space_post WHERE spaceuserid='{$GLOBALS['spaceUserID']}' AND parentid>0 AND stype='5' ORDER BY jointime DESC",array('pageSize'=>$spaceSetting[3]));
	if( $_arrspaceConfig_UserCat['spacemusic'] === false ){
		$_arrspaceConfig_UserCat['spacemusic'] = array();
	}
	if( $_argUpdateDataBase === true ){
		saveUserCatToXmlData();
	}
}//end function Update_MusicToXml

function Page_UserInput_Cat_Save(){//保存用户栏目设置
	global $dv,$db,$lang,$spaceUserCat,$spaceSetting,$spaceName,$_objEnc;
	$_uCatTitle = trim($GLOBALS['ucattitle']);
	if( $_uCatTitle === '' ){
		spaceShowMsg($lang['spaceError.str23'],0);
		return false;
	} else{
		$_uCatTitle = htmlspecialchars($_uCatTitle);
	}
	$_uCatID = trim($GLOBALS['ucatid']);
	if( !is_numeric($_uCatID) ){
		$_uCatID = 0;
	}
	$_uCatNote = trim($GLOBALS['ucatnote']);
	if( $_uCatNote !== '' ){
		$_uCatNote = htmlspecialchars($_uCatNote);
	}
	$_isView = trim($GLOBALS['isview']);
	if( !is_numeric($_isView) ){
		$_isView = 0;
	}
	$_sType = trim($GLOBALS['stype']);
	if( !is_numeric($_sType) ){
		$_sType = 0;
	}
	if( $_uCatID > 0 ){
		$db->query("UPDATE {$dv}space_usercat SET ucattitle='{$_uCatTitle}',ucatnote='{$_uCatNote}',isview='{$_isView}',utype='{$_sType}' WHERE ucatid='{$_uCatID}' AND userid='{$GLOBALS['userid']}'");
	} else{
		$db->query("INSERT INTO {$dv}space_usercat(ucattitle,ucatnote,isview,userid,utype) VALUES('{$_uCatTitle}','{$_uCatNote}','{$_isView}','{$GLOBALS['userid']}','{$_sType}')");
	}
	Update_UserCatToXml();
	spaceShowMsg($lang['spaceError.str22'],1);
	return false;
}

function Page_UserInput_Cat_Del(){
	global $dv,$db,$lang,$spaceUserCat,$spaceSetting,$spaceName,$_objEnc;
	$_intUCatID = $GLOBALS['ucatid'];
	if( !is_numeric($_intUCatID) ) $_intUCatID = 0;
	$db->query("DELETE FROM {$dv}space_usercat WHERE ucatid='{$_intUCatID}' AND userid='{$GLOBALS['userid']}'");
	spaceShowMsg($lang['spaceError.str24'],1);
}

function Post_Save($_argSaveNew=true){
	global $dv,$db,$lang,$_objEnc,$spaceSystemSetting,$spaceUserInfo;
	//检查POST的来源
	if( !ChkPost() ){
		spaceShowMsg($lang['spaceError.str0'],0);
		return false;
	}
	//检查验证码
	if( $spaceSystemSetting[4] == 1 AND CodeIsTrue() !== true ){
		spaceShowMsg($lang['spaceError.str5'],0);
		return false;
	}
	//初始化$_objEnc
	if( empty($_objEnc) ){
		$_objEnc =& DV_Encoding::GetEncoding($GLOBALS['charset']);
	}
	//检查标题
	$_P_Title = trim($GLOBALS['title']);
	if( $_P_Title === '' OR $_objEnc->StrLength($_P_Title) > 250 ){
		spaceShowMsg($lang['spaceError.str28'],0);
		return false;
	}
	//检查搜索关键字
	$_P_SearchKey = trim($GLOBALS['searchkey']);
	if( $_P_SearchKey === ''){
		spaceShowMsg($lang['spaceError.str29_1'],0);
		return false;
	}
	if($_objEnc->StrLength($_P_SearchKey) > 250 ){
		spaceShowMsg($lang['spaceError.str29'],0);
		return false;
	}
	//检查日期
	$_P_DDateTime = trim($GLOBALS['ddatetime']);
	if( $_P_DDateTime === '' OR !isDate($_P_DDateTime) ){
		spaceShowMsg($lang['spaceError.str29'],0);
		return false;
	}
	$_P_DDateTime = (dv_gmtimestamp(dateFormat($_P_DDateTime,'Y-m-d')) - getUserTimeZoneOffset()).gmdate(' H:i:s');
	//检查类别stype
	$_P_sType = trim($GLOBALS['stype']);
	if( $_P_sType < 0 OR $_P_sType > 5 ){
		spaceShowMsg($lang['spaceError.str30'],0);
		return false;
	}
	//检查话题scatid
	$_P_sCatID = trim($GLOBALS['scatid']);
	if( $_P_sCatID == -1 ){
		spaceShowMsg($lang['spaceError.str31'],0);
		return false;
	}
	//检查所属栏目catid
	$_P_Catid = trim($GLOBALS['catid']);
	if ('' === $_P_Catid OR -1 == $_P_Catid OR !is_numeric($_P_Catid) ){
		$_P_Catid = 0;
	} else {
		$_P_Catid = is_numeric($_P_Catid) ? $_P_Catid : 0;
	}

	$_P_Lock = trim($GLOBALS['lock']);
	$_P_Best = trim($GLOBALS['best']);
	//检查内容
	$_P_PostContent =& CheckAlipay();
	if( $_P_PostContent === '' ){
		$_P_PostContent = trim($GLOBALS['postcontent']);
	}
	if( $_P_PostContent === '' ){
		spaceShowMsg($lang['spaceError.str33'],0);
		return false;
	}
	$_P_PostContent = str_replace(array("\r","\n"),'',$_P_PostContent);
	$_P_PostContent =& spaceFormatCode($_P_PostContent);

	$_P_PostTitleNote = trim($_POST['posttitlenote']);
	if ($_P_PostTitleNote !== '') {
		$_ubbcode = stripslashes(spaceUbbCode($_P_PostTitleNote, false));
		$_P_PostTitleNote =& getTitleNote($_ubbcode, 0, $spaceSetting[2]);
		$_P_PostTitleNote =& _imgaddjscode($_P_PostTitleNote);
	} elseif ($_P_PostContent !== '') {
		$_ubbcode = stripslashes(spaceUbbCode($_P_PostContent, false));
		$_P_PostTitleNote =& getTitleNote($_ubbcode, 0, $spaceSetting[2]);
		$_P_PostTitleNote =& _imgaddjscode($_P_PostTitleNote);
	}
	$_PostID = trim($GLOBALS['postid']);
	$_RootID = trim($GLOBALS['rootid']);
	//检查天气weather
	$_P_Weather = trim($GLOBALS['weather']);
	if( $_P_Weather !== '' ){
		$_P_iWeather = explode('|',$_P_Weather);
		if( count($_P_iWeather) == 2 ){
			$_P_Weather = is_numeric($_P_iWeather[1]) ? $_P_iWeather[1] : 0 ;
		} else{
			$_P_Weather = 0;
		}
	} else{
		$_P_Weather = 0;
	}

	if ($upfileinfo = uploadedFilesProc($_P_PostContent)) {
		$_HaveUpFile = $upfileinfo[0];
		$_P_UpFileID = $upfileinfo[1];
	} else {
		$_HaveUpFile = 0;
		$_P_UpFileID = 0;
	}

	$_Num_T = $_Num_F = $_Num_L = $_Num_P = $_Num_M = 0;
	if( $_P_sType == 0 ){
		$_Num_T = 1;
	} elseif( $_P_sType == 1 ){
		$_Num_F = 1;
	} elseif( $_P_sType == 2 ){
		$_Num_L = 1;
	} elseif( $_P_sType == 4 ){
		$_Num_P = 1;
	} elseif( $_P_sType == 5 ){
		$_Num_M = 1;
	}

	if( $_argSaveNew === true ){
		$_blnDebug = false;
		$db->query("INSERT INTO {$dv}space_topic(CatID,sCatID,UserID,UserName,Title,TitleNote,PostTime,IsLock,sType,LastPostTime,IsBest,S_Key,Weather) VALUES('{$_P_Catid}','{$_P_sCatID}','{$GLOBALS['spaceUserID']}','{$GLOBALS['spaceUserName']}','{$_P_Title}','".$db->escape_string($_P_PostTitleNote)."','{$_P_DDateTime}','{$_P_Lock}','{$_P_sType}','{$_P_DDateTime}','{$_P_Best}','{$_P_SearchKey}','{$_P_Weather}')",array('debug'=>$_blnDebug));
		$_RootID = $db->scalar("SELECT MAX(topicid) FROM {$dv}space_topic");
		//按日期更新主题缓存
		global $spaceUserInfo;
		updateDiaryTopic(array('Action' => 'insert', 'userid' => $spaceUserInfo['userid'], 'DiaryTopic' => &$spaceUserInfo['diary_topic'], 'PostTime' => $_P_DDateTime, 'TopicID' => $_RootID));

		$db->query("INSERT INTO {$dv}space_post (CatID,sCatID,RootID,UserID,UserName,Title,Content,JoinTime,ip,sType,IsUpfile,spaceUserID,IsLock) VALUES ('{$_P_Catid}','{$_P_sCatID}','{$_RootID}','{$GLOBALS['spaceUserID']}','{$GLOBALS['spaceUserName']}','{$_P_Title}','{$_P_PostContent}','{$_P_DDateTime}','{$usertrueip}','{$_P_sType}','{$_HaveUpFile}','{$GLOBALS['spaceUserID']}','{$_P_Lock}')",array('debug'=>$_blnDebug));
		$_PostID = $db->scalar("SELECT MAX(postid) FROM {$dv}space_post");

		$_strDateNow = TIME_NOW;

		$db->query("UPDATE {$dv}space_user SET topicnum=topicnum+'{$_Num_T}',favnum=favnum+'{$_Num_F}',photonum=photonum+'{$_Num_P}',medianum=medianum+'{$_Num_M}',todaynum=todaynum+1,lastuptime='{$_strDateNow}' WHERE userid='{$GLOBALS['spaceUserID']}'",array('debug'=>$_blnDebug));

		$db->query("UPDATE {$dv}space_syscat SET topicnum=topicnum+'{$_Num_T}',todaynum=todaynum+1,lastuptime='{$_strDateNow}' WHERE scatid IN({$_P_sCatID},{$spaceUserInfo['syscatid']})",array('debug'=>$_blnDebug));

		$db->query("UPDATE {$dv}space_usercat SET topicnum=topicnum+1,todaynum=todaynum+1,lastuptime='{$_strDateNow}' WHERE ucatid='{$_P_Catid}'",array('debug'=>$_blnDebug));

		$db->query("UPDATE {$dv}space_system SET s_topicnum=s_topicnum+'{$_Num_T}',s_photonum=s_photonum+'{$_Num_P}',s_medianum=s_medianum+'{$_Num_M}',s_favnum=s_favnum+'{$_Num_F}',s_todaynum=s_todaynum+1,s_lastposttime='{$_strDateNow}'",array('debug'=>$_blnDebug));

		if ($_HaveUpFile == 1 AND $_P_UpFileID) {
			$db->query("UPDATE {$dv}space_upfile SET catid='{$_P_Catid}',stype='{$_P_sType}',topicid='{$_RootID}',postid='{$_PostID}',istopic=0,title='{$_P_Title}',filenote='{$_P_PostTitleNote}',islock='{$_P_Lock}' WHERE id IN({$_P_UpFileID})",array('debug'=>$_blnDebug));
		}

		Update_TopicToXml();
		$db->query("UPDATE {$dv}space_syscat SET lastuptime='{$_strDateNow}',todaynum=todaynum+1,topicnum=topicnum+'{$_Num_T}' WHERE scatid IN({$_P_Catid},{$spaceUserInfo['syscatid']})");
		$db->query("UPDATE {$dv}space_system SET s_todaynum=s_todaynum+1,s_favnum=s_favnum+'{$_Num_F}',s_photonum=s_photonum+'{$_Num_P}',s_medianum=s_medianum+'{$_Num_M}',s_topicnum=s_topicnum+'{$_Num_T}',s_lastposttime='{$_strDateNow}'");

		updatespaceConfigCache();

		spaceShowMsg($lang['spaceError.str35'],1);
		exit;
	}
}

function Page_UserInput_mPost_Del(){
	global $lang,$dv,$db,$spaceUserInfo,$spaceUserID;
	$_arrTopicID = $GLOBALS['topicid'];
	$_iTopic = trim($GLOBALS['itopic']);
	if( $_iTopic === '' OR empty($_arrTopicID) OR !is_array($_arrTopicID) ){
		spaceShowMsg($lang['spaceError.str7'],0);
		return false;
	}
	if( !is_numeric($_iTopic) ){
		spaceShowMsg($lang['spaceError.str7'],0);
		return false;
	}
	if( $_iTopic != 0 ){
		spaceShowMsg($lang['spaceError.str7'],0);
		return false;
	}
	$_strTopicIDList = implode(',',$_arrTopicID);
	if( !checkIDList($_strTopicIDList) ){
		spaceShowMsg($lang['spaceError.str7'],0);
		return false;
	}
	$_strDateNow = TIME_NOW;
	foreach( $_arrTopicID as $_currTopicID ){
		$_arrRS =& $db->getResultSet("SELECT postid,spaceuserid,catid,scatid,parentid,rootid,userid,username,title,content,jointime,ip,stype,isupfile,islock FROM {$dv}space_post WHERE postid='{$_currTopicID}'",array('pageSize'=>1));
		if( $_arrRS === false ) continue;
		$_arrspacePost =& $_arrRS[0];
		$_tPostNum = 0;
		if( dateDiff('d',$_arrspacePost['jointime'],$_strDateNow) == 0 ){
			$_tPostNum = 1;
		}
		//更新系统数据
		$db->query("UPDATE {$dv}space_syscat SET PostNum=PostNum-1,TodayNum=TodayNum-'{$_tPostNum}' WHERE scatid IN({$_arrspacePost['scatid']},{$spaceUserInfo['syscatid']})");
		$db->query("UPDATE {$dv}space_system SET S_PostNum=S_PostNum-1,S_TodayNum= _TodayNum-'{$_tPostNum}'");
		//更新用户总数据
		$db->query("UPDATE {$dv}space_user SET PostNum=PostNum-1,TodayNum=TodayNum-'{$_tPostNum}' WHERE userid='{$spaceUserID}'");
		//更新用户栏目数据
		$db->query("UPDATE {$dv}space_usercat SET PostNum=PostNum-1,TodayNum=TodayNum-'{$_tPostNum}' WHERE ucatid='{$_arrspacePost['catid']}'");
		//上传文件清理
		if( $_arrspacePost['isupfile'] == 1 ){
			SysDeleteFile($_arrspacePost['postid']);
		}
		//更新主题数据
		$db->query("UPDATE {$dv}space_topic SET Child=Child-1 WHERE TopicID='{$_arrspacePost['rootid']}'");
		$db->query("DELETE FROM {$dv}space_post WHERE postid='{$_currTopicID}'");
	}
	Update_TopicToXml();
	updatespaceConfigCache();
	spaceShowMsg($lang['spaceError.str47'],1);
	return true;
}

function Page_UserFile_Del(){
	global $spaceUserID,$dv,$db,$lang,$spaceSystemUpSetting;
	$_FilePath = $spaceSystemUpSetting[19];
	$_arrFileID = $GLOBALS['fileid'];
	$_iTopic = trim($GLOBALS['itopic']);
	if( $_iTopic === '' OR empty($_arrFileID) OR !is_array($_arrFileID) ){
		spaceShowMsg($lang['spaceError.str7']);
		exit;
	}
	if( !is_numeric($_iTopic)  OR $_iTopic != 0 ){
		spaceShowMsg($lang['spaceError.str7']);
		exit;
	}
	if( !checkIDList(implode(',',$_arrFileID)) ){
		spaceShowMsg($lang['spaceError.str7']);
		exit;
	}

	foreach( $_arrFileID as $_currFileID ){
		$_arrTmp1 =& $db->getResultSet("SELECT id,spaceuserid,userid,username,catid,stype,topicid,postid,istopic,title,filename,sfilename,filetype,filesize,filenote,downnum,viewnum,dateandtime,previewimage,islock FROM {$dv}space_upfile WHERE id='{$_currFileID}' AND spaceuserid='{$spaceUserID}'",array('pageSize'=>1));
		if( $_arrTmp1 === false ) continue;
		$_arrUpFile =& $_arrTmp1[0];
		//如关联帖子,则更新相应数据
		if( ( $_arrUpFile['istopic'] == 0 OR $_arrUpFile['istopic'] == 1 ) AND $_arrUpFile['postid'] > 0 ){
			$_arrTmp2 =& $db->getResultSet("SELECT postid,spaceuserid,catid,scatid,parentid,rootid,userid,username,title,content,jointime,ip,stype,isupfile,islock FROM {$dv}space_post WHERE postid='{$_arrUpFile['postid']}'",array('pageSize'=>1));
			if( $_arrTmp2 !== false ){
				$_arrspacePost =& $_arrTmp2[0];
				list(,$_strTmp1) = each(explode('.',$_arrUpFile['filename']));
				$_strPostContent = str_replace("[upload={$_strTmp1}]{$_arrUpFile['filename']}[/upload]",'',$_arrspacePost['content']);
				$db->query("UPDATE {$dv}space_post SET content='".$db->escape_string($_strPostContent)."',isupfile=0 WHERE postid='{$_arrUpFile['postid']}'");
			}
		}
		//删除附件
		if( file_exists($_arrUpFile['filename']) ){
			@FileHandler::unlink($_arrUpFile['filename']);
		}
		$_strPreviewImage = str_replace('..','',$_arrUpFile['previewimage']).'';
		if( $_strPreviewImage !== '' ){
			if( file_exists($_strPreviewImage) ){
				@unlink($_strPreviewImage);
			}
		}
		//删除附件表记录
		$db->query("DELETE FROM {$dv}space_upfile WHERE id='{$_arrUpFile['id']}'");
	}
	spaceShowMsg($lang['spaceError.str48'],1);
	exit;
}

function Page_SaveSkins(){	//	保存模板风格设置
	global $lang,$dv,$db;
	if( !ChkPost() ){
		spaceShowMsg($lang['spaceError.str0']);
		exit;
	}
	$_intSkinID = trim($GLOBALS['skinid']);
	if( !is_numeric($_intSkinID) ){
		spaceShowMsg($lang['spaceError.str2']);
		exit;
	}
	$_intSkinID = $db->scalar("SELECT s_id FROM {$dv}space_skins WHERE s_id='{$_intSkinID}'");
	if( !is_numeric($_intSkinID) OR $_intSkinID <= 0  ){
		spaceShowMsg($lang['spaceError.str2']);
		exit;
	}
	$db->query("UPDATE {$dv}space_user SET skinid='{$_intSkinID}' WHERE userid='{$GLOBALS['userid']}'");
	updatespaceConfigCache();
	spaceShowMsg($lang['spaceError.str27'],1);
	exit;
}

function Page_UserSetting_Info_Save()	//	个人资料修改
{
	global $lang,$dv,$db,$_objEnc;
	if( !ChkPost() ){
		spaceShowMsg($lang['spaceError.str0']);
		exit;
	}
	if( empty($_objEnc) ){
		$_objEnc =& DV_Encoding::GetEncoding($GLOBALS['charset']);
	}
	$_NickName = trim($GLOBALS['nickname']);
	$_intLength = $_objEnc->StrLength($_NickName);
	if( $_NickName === '' OR $_intLength > 50 OR $_intLength < 1 ){
		spaceShowMsg($lang['spaceError.str6']);
		exit;
	}
	$_NickName = htmlspecialchars($_NickName);
	if(checkText($_NickName) === false ){
		spaceShowMsg($lang['spaceError.str7']);
		exit;
	}

	$_spaceTitle = trim($GLOBALS['spacetitle']);
	$_intLength = $_objEnc->StrLength($_spaceTitle);
	if( $_spaceTitle === '' OR $_intLength > 150 OR $_intLength < 1 ){
		spaceShowMsg($lang['spaceError.str10']);
		exit;
	}

	$_spaceCTitle = trim($GLOBALS['spacectitle']);
	$_intLength = $_objEnc->StrLength($_spaceCTitle);
	if( $_spaceCTitle === '' OR $_intLength > 250 OR $_intLength < 1 ){
		spaceShowMsg($lang['spaceError.str10_1']);
		exit;
	}

	$_spaceNote = trim($GLOBALS['spacenote']);
	if( $_spaceNote !== '' AND checkText($_spaceNote) === false ){
		spaceShowMsg($lang['spaceError.str7']);
		exit;
	}

	$_spaceTitle = htmlspecialchars($_spaceTitle);
	$_spaceCTitle = htmlspecialchars($_spaceCTitle);
	$_spaceNote = htmlspecialchars($_spaceNote);

	$_arrTmp =& $db->getResultSet("SELECT userid,username,nickname,spacename,password,spacetitle,spacechildtitle,spacenote,joinspacetime,pageview,topicnum,favnum,photonum,postnum,todaynum,trackbacks,spacesize,xmldata,syscatid,spacesetting,lastuptime,skinid,stats,myphoto_path,myphoto_preview_path,myphoto_desc FROM {$dv}space_user WHERE userid='{$GLOBALS['spaceUserID']}'");
	if( $_arrTmp === false ){
		spaceShowMsg($lang['spaceError.str12']);
		return false;
	}
	$_arrspaceUser = $_arrTmp[0];

	$myphotostmt = '';
	//Start 相片上传部分
		if (!empty($_arrspaceUser['myphoto_path'])) {
			if (!empty($_FILES)) {	//	您已经上传过相片了。如需要重新上传，请先将原相片删除！
				spaceShowMsg($lang['spaceError.str52']);
				return false;
			} elseif ('1' === $_POST['del_myphoto']) {
				$myphotostmt = ",myphoto_path='', myphoto_preview_path='', myphoto_desc=''";
				$_myphoto_path = $_myphoto_path = '';
				global $fsetting, $spaceSystemUpSetting;
				if (!empty($_arrspaceUser['myphoto_path'])) {
					$_myphoto_path = $fsetting['forumuploadname'].'/'.$spaceSystemUpSetting[19].'/'.$_arrspaceUser['myphoto_path'];
				}
				if (!empty($_arrspaceUser['myphoto_preview_path'])) {
					$_myphoto_preview_path = $fsetting['forumuploadname'].'/'.$spaceSystemUpSetting[19].'/'.$_arrspaceUser['myphoto_preview_path'];
				}
				$arrunlink = array();
				if (!empty($_arrspaceUser['myphoto_path']) AND FileHandler::is_file($_myphoto_path)) {
					$arrunlink[] = $_myphoto_path;
				}
				if (!empty($_arrspaceUser['myphoto_preview_path']) AND FileHandler::is_file($_myphoto_preview_path)) {
					$arrunlink[] = $_myphoto_preview_path;
				}
				if (!empty($arrunlink)) {
					FileHandler::unlink($arrunlink);
				}
				$db->query("DELETE FROM {$dv}space_apply_today_star WHERE userid='{$_arrspaceUser['userid']}'");
			} else {
				$myphotostmt = ",myphoto_desc='{$_POST['myphoto_desc']}'";
			}
		} else if (!empty($_POST['myphoto_path'])) {
			$myphotopath = $myphoto_preview_path = $myphoto_desc = '';
			if (!empty($_FILES['myphoto_path'])) {
				$upfile =& $_FILES['myphoto_path'];
				if (!FileHandler::is_uploaded_file($upfile['tmp_name'])) {	//	请通过 POST 上传文件！
					spaceShowMsg($lang['spaceError.str53']);
					return false;
				}
				$currpathinfo = FileHandler::pathinfo($upfile['name']);
				$currfileext = strtolower($currpathinfo['extension']);
				if (empty($currfileext)) {
					list(, $currfileext) = explode('/', $currfileext['type']);
					if (false !== strpos($currfileext, '-')) {
						$currfileext = str_replace('-', '', strstr($currfileext, '-'));
					}
				}
				if (false === strpos(',gif,jpg,jpeg,png,bmp,', ",{$currfileext},")) {	//	图片格式不正确！
					spaceShowMsg($lang['spaceError.str53']);
					return false;
				}
				require_once INC_PATH.'upload.functions.php';
				$updirs = initUploadDirectories(array('init_updestdir'=>false));
				$uptmpdir = $updirs['uptmpdir'];
				list($msec, $sec) = explode(' ', microtime());
				$newname = $sec.($msec*1000000);
				$fullname = $newname.'.'.$currfileext;
				$tmpphoto = $uptmpdir.'/__dv_tmp_uploaded_file_spaceuser_photo__'.$fullname;
				FileHandler::find_writable_dir($uptopdir); // 设置可写目录
				if (move_uploaded_file($upfile['tmp_name'], $tmpphoto)) {
					@chmod($tmpphoto, 0755);
					$renamesrc[] = $tmpphoto;
					$renamedest[] = $updirs['spacedestdir'].'/user_photo_'.$fullname;
					global $spaceSystemUpSetting;
					if ($spaceSystemUpSetting[17] != 0 AND canmakethumbnail()) {
						$thumbnailphoto = $uptmpdir.'/__dv_tmp_space_preview_file_userphoto__'.$newname;
						if (!image_thumbnail($tmpphoto, $spaceSystemUpSetting[14], $spaceSystemUpSetting[15], $thumbnailphoto)) {
							spaceShowMsg($lang['spaceError.str57']);
							return false;
						}
						$previewphoto = $updirs['spacepreviewdestdir'].'/'.$newname.'.jpg';
						$renamesrc[] = $thumbnailphoto.'.jpg';
						$renamedest[] = $previewphoto;
					}
					if (!FileHandler::rename($renamesrc, $renamedest)) {
						foreach ($renamesrc AS $srcfile) {
							@FileHandler::unlink($srcfile);
						}//end foreach
						spaceShowMsg($lang['spaceError.str58']);
						return false;
					}
					@FileHandler::chmod($renamedest, 0755);
					$myphotopath = $db->escape_string(str_replace($updirs['spaceuptopdir'].'/', '', $renamedest[0]));
					$myphoto_preview_path = $db->escape_string(str_replace($updirs['spaceuptopdir'].'/', '', $renamedest[1]));
					$db->query("UPDATE {$dv}space_apply_today_star SET nickname='{$_NickName}', user_photo='{$myphotopath}', user_preview_photo='{$myphoto_preview_path}' WHERE userid='{$_arrspaceUser['userid']}'");
				}
			}
			$myphotostmt = ",myphoto_path='{$myphotopath}', myphoto_preview_path='{$myphoto_preview_path}', myphoto_desc='{$myphoto_desc}'";
		}
	//End相片上传部分

	if( strtolower($_arrspaceUser['nickname']) !== strtolower($_NickName) ){
	//更新主题表
		$db->query("UPDATE {$dv}space_topic SET username='{$_NickName}' WHERE userid='{$GLOBALS['spaceUserID']}'");
	//更新帖子表
		$db->query("UPDATE {$dv}space_post SET username='{$_NickName}' WHERE userid='{$GLOBALS['spaceUserID']}'");
	//更新上传表
		$db->query("UPDATE {$dv}space_upfile SET username='{$_NickName}' WHERE userid='{$GLOBALS['spaceUserID']}'");
	}
	$db->query("UPDATE {$dv}space_user SET nickname='{$_NickName}',spacetitle='{$_spaceTitle}',spacechildtitle='{$_spaceCTitle}',spacenote='{$_spaceNote}' {$myphotostmt} WHERE userid='{$GLOBALS['spaceUserID']}'");
	//更新用户首页数据
	Update_TopicToXml();
	updatespaceConfigCache();

	spaceShowMsg($lang['spaceError.str14'],1);
	return true;
}

function Page_UserSetting_Pass_Save(){
	global $lang,$dv,$db,$_objEnc;
	if( !ChkPost() ){
		spaceShowMsg($lang['spaceError.str0']);
		exit;
	}
	$_PassWord = trim($GLOBALS['password']);
	$_nPassWord = trim($GLOBALS['npass']);
	$_rnPassWord = trim($GLOBALS['rnpass']);
	if( $_PassWord === '' OR $_nPassWord === '' OR $_rnPassWord === ''  ){
		spaceShowMsg($lang['spaceError.str9']);
		exit;
	}
	if( $_nPassWord !== $_rnPassWord ){
		spaceShowMsg($lang['spaceError.str15']);
		exit;
	}
	$_nPassWord = dv_md5($_nPassWord);
	$_PassWord = dv_md5($_PassWord);
	$_strDBPassWord =& $db->scalar("SELECT password FROM {$dv}space_user WHERE userid='{$GLOBALS['userid']}'");
	if( $_strDBPassWord === false ){
		spaceShowMsg($lang['spaceError.str12']);
		return false;
	}
	if( $_strDBPassWord != $_PassWord ){
		spaceShowMsg($lang['spaceError.str13']);
		return false;
	}
	$db->query("UPDATE {$dv}space_user SET password='{$_nPassWord}' WHERE userid='{$GLOBALS['userid']}'");
	spaceShowMsg($lang['spaceError.str16'],1);
	return true;
}

function Page_UserSetting_Set_Save(){
	global $lang,$dv,$db,$_objEnc,$spaceUserInfo;
	$_SysCatID = trim($_POST['syscatid']);
	if( !is_numeric($_SysCatID) ){
		$_SysCatID = 1;
	}
	$_strComma = '';
	$_strspaceSetting = '';
	for( $i = 0 ; $i < 50 ; $i++ ){
		$_iSetting = trim($_POST["setting".$i]);
		if( $_iSetting === '' ){
			$_iSetting = 1;
		}
		if( $i < 12 ){
			if( !is_numeric($_iSetting) ){
				spaceShowMsg($lang['spaceError.str7']);
				exit;
			}
		}
		$_strspaceSetting .= "{$_strComma}{$_iSetting}";
		$_strComma = ',';
	}
	if( $_strspaceSetting !== '' ){
		$_strspaceSetting = Dv_FilterJS(htmlspecialchars($_strspaceSetting));
	}
	//当用户所选系统分类改变时相应更新分类用户数
	if( $spaceUserInfo['syscatid'] != $_SysCatID ){
		$db->query("UPDATE {$dv}space_syscat SET ucatnum=ucatnum-1 WHERE scatid='{$spaceUserInfo['syscatid']}'");
		$db->query("UPDATE {$dv}space_syscat SET ucatnum=ucatnum+1 WHERE scatid='{$_SysCatID}'");

		$db->query("UPDATE {$dv}space_syscat SET ucatnum=ucatnum-1 WHERE scatid='{$spaceUserInfo['syscatid']}'");
		$db->query("UPDATE {$dv}space_syscat SET ucatnum=ucatnum+1 WHERE scatid='{$_SysCatID}'");
		updatespaceConfigCache();
	}

	$db->query("UPDATE {$dv}space_user SET spacesetting='{$_strspaceSetting}',syscatid='{$_SysCatID}' WHERE userid='{$GLOBALS['spaceUserID']}'");
	spaceShowMsg($lang['spaceError.str17'],1);
	exit;
}

function Page_UserSetting_Key_Save(){
	global $lang,$dv,$db,$_objEnc,$spaceUserInfo;
	$_KeyID = trim($_POST['keyid']);
	if( !is_numeric($_KeyID) ){
		$_KeyID = 0;
	}
	$_KeyWord = str_replace('|', '', trim($_POST['keyword']));
	$_nKeyWord = str_replace('|', '' ,trim($_POST['nkeyword']));
	if ('' === $_KeyWord OR '' === $_nKeyWord) {
		spaceShowMsg($lang['spaceError.str18']);
		exit;
	}
	$_KeyWord = htmlspecialchars($_KeyWord);
	$_nKeyWord = htmlspecialchars($_nKeyWord);

	$_LinkUrl = trim($_POST['linkurl']);
	if( $_LinkUrl !== '' ){
		$_LinkUrl = htmlspecialchars($_LinkUrl);
	}

	$_LinkTitle = trim($_POST['linktitle']);
	if( $_LinkTitle !== '' ){
		$_LinkTitle = htmlspecialchars(Dv_FilterJS($_LinkTitle));
	}

	$_NewWindows = trim($_POST['newwindows']);
	if( !is_numeric($_NewWindows) ){
		$_NewWindows = 0;
	}

	if( $_KeyID > 0 ){
		$_intKeyID = $db->scalar("SELECT keyid FROM {$dv}space_keyword WHERE keyid<>'{$_KeyID}' AND userid='{$GLOBALS['userid']}' AND keyword='{$_KeyWord}'");
		if( $_intKeyID !== false ){
			spaceShowMsg($lang['spaceError.str20'],0);
			exit;
		}
		$db->query("Update {$dv}space_keyword SET keyword='{$_KeyWord}',nkeyword='{$_nKeyWord}',linkurl='{$_LinkUrl}',linktitle='{$_LinkTitle}',newwindows='{$_NewWindows}' WHERE keyid='{$_KeyID}' AND userid='{$GLOBALS['userid']}'");
	} else{
		$_intKeyID = $db->scalar("SELECT keyid FROM {$dv}space_keyword WHERE userid='{$GLOBALS['userid']}' AND keyword='{$_KeyWord}'");
		if( $_intKeyID !== false ){
			spaceShowMsg($lang['spaceError.str20'],0);
			exit;
		}
		$db->query("INSERT INTO {$dv}space_keyword(keyword,nkeyword,linkurl,linktitle,newwindows,userid) VALUES('{$_KeyWord}','{$_nKeyWord}','{$_LinkUrl}','{$_LinkTitle}','{$_NewWindows}','{$GLOBALS['userid']}')");
	}
	spaceShowMsg($lang['spaceError.str19'],1);
	exit;
}

function Page_UserSetting_Key_Del(){
	global $lang,$dv,$db,$_objEnc,$spaceUserInfo;
	$_KeyID = trim($GLOBALS['keyid']);
	if( !is_numeric($_KeyID) ){
		$_KeyID = 0;
	}
	$db->query("DELETE FROM {$dv}space_keyword WHERE keyid='{$_KeyID}' AND userid='{$GLOBALS['userid']}'");
	spaceShowMsg($lang['spaceError.str21'],1);
	exit;
}

function Update_UserNickName(){//更新用户笔名
	global $lang,$dv,$db;
	$db->query("UPDATE {$dv}space_topic SET username='{$GLOBALS['spaceUserName']}' WHERE userid='{$GLOBALS['spaceUserID']}'");
	$_strMsg = $lang['tpl.str4'];
	$db->query("UPDATE {$dv}space_upfile SET username='{$GLOBALS['spaceUserName']}' WHERE userid='{$GLOBALS['spaceUserID']}'");
	$_strMsg .= $lang['tpl.str5'];
	$db->query("UPDATE {$dv}space_post SET username='{$GLOBALS['spaceUserName']}' WHERE userid='{$GLOBALS['spaceUserID']}'");
	$_strMsg .= $lang['tpl.str6'];
	spaceShowMsg($_strMsg,1);
	exit;
}

function Update_UserCatData(){//更新栏目数据
	global $lang,$dv,$db,$spaceUserCat;
	$_arrspaceCat =& $spaceUserCat['result_set'];
	$_strMsg = '';
	if( !empty($spaceUserCat['result_set']) AND is_array($spaceUserCat['result_set']) ){
		foreach( $spaceUserCat['result_set'] as $_index => $_val ){
			$_uCatID = intval($_val['ucatid']);
			if( $_uCatID > 0 ){
				$_TopicNum = $db->scalar("SELECT COUNT(1) FROM {$dv}space_topic WHERE catid='{$_uCatID}'");
				$_PostNum = $db->scalar("SELECT COUNT(1) FROM {$dv}space_post WHERE parentid>0 AND catid='{$_uCatID}'");
				$time1 = strtotime('Y-m-d 00:00:00');
				$time2 = $time1 + (24 *3600) - 1;
				$_TodayNum = $db->scalar("SELECT COUNT(1) FROM {$dv}space_post WHERE catid='{$_uCatID}' AND jointime BETWEEN '{$time1}' AND '{$time2}'");
				$_LastUpTime = $db->scalar("SELECT jointime FROM {$dv}space_post WHERE catid='{$_uCatID}' ORDER BY jointime DESC");
				if( $_LastUpTime === false ){
					$_LastUpTime = TIME_NOW;
				}
				$_arrspaceCat[$_index]['topicnum'] = $_TopicNum;
				$_arrspaceCat[$_index]['postnum'] = $_PostNum;
				$_arrspaceCat[$_index]['todaynum'] = $_TodayNum;
				$_arrspaceCat[$_index]['lastuptime'] = $_LastUpTime;
				$db->query("UPDATE {$dv}space_usercat SET TopicNum='{$_TopicNum}',PostNum='{$_PostNum}',TodayNum='{$_TodayNum}',LastUpTime = '{$_LastUpTime}' WHERE ucatid='{$_uCatID}'");
				$_strMsg .= str_replace(array('{$Tpl_uCatTitle}','{$Tpl_TopicNum}','{$Tpl_PostNum}','{$Tpl_TodayNum}'),array($_val['ucattitle'],$_TopicNum,$_PostNum,$_TodayNum),$lang['tpl.str7']);
			}
		}
		$db->query("UPDATE {$dv}space_user SET xmldata='".$db->escape_string(base64_encode(serialize($spaceUserCat)))."' WHERE userid='{$GLOBALS['spaceUserID']}'");
	}
	spaceShowMsg($_strMsg.str_replace('{$Tpl_Num}',count($spaceUserCat['result_set']),$lang['tpl.str8']),1);
	exit;
}

function Update_UserspaceData(){//更新我的空间总数据
	global $lang,$dv,$db,$spaceUserInfo,$spaceSystemSetting;
	$_TopicNum = $db->scalar("SELECT COUNT(1) FROM {$dv}space_topic WHERE stype='0' AND userid='{$GLOBALS['spaceUserID']}'");
	$_FavNum = $db->scalar("SELECT COUNT(1) FROM {$dv}space_topic WHERE stype='1' AND userid='{$GLOBALS['spaceUserID']}'");
	$_PhotoNum = $db->scalar("SELECT COUNT(1) FROM {$dv}space_topic WHERE stype='4' AND userid='{$GLOBALS['spaceUserID']}'");
	$_MediaNum = $db->scalar("SELECT COUNT(1) FROM {$dv}space_topic WHERE stype='5' AND userid='{$GLOBALS['spaceUserID']}'");
	$_PostNum = $db->scalar("SELECT COUNT(1) FROM {$dv}space_post WHERE parentid>0 AND spaceuserid='{$GLOBALS['spaceUserID']}'");
	$time1 = strtotime('Y-m-d 00:00:00');
	$time2 = $time1 + (24 *3600) - 1;
	$_TodayNum = $db->scalar("SELECT COUNT(1) FROM {$dv}space_post WHERE spaceuserid='{$GLOBALS['spaceUserID']}' AND jointime BETWEEN '{$time1}' AND '{$time2}'");
	$_LastUpTime = $db->scalar("SELECT jointime FROM {$dv}space_post WHERE spaceuserid='{$GLOBALS['spaceUserID']}' ORDER BY jointime DESC");
	if( $_LastUpTime === false ){
		$_LastUpTime = TIME_NOW;
	}
	$_strMsg = str_replace(array('{$Tpl_TopicNum}','{$Tpl_FavNum}','{$Tpl_PhotoNum}','{$Tpl_PostNum}','{$Tpl_TodayNum}'),array($_TopicNum,$_FavNum,$_PhotoNum,$_PostNum,$_TodayNum),$lang['tpl.str9']);
	$spaceUserInfo['spacesize'] = php_cCur($spaceUserInfo['spacesize']);
	if( $spaceUserInfo['spacesize'] > 0 ){
		$_SpaceSize = $db->scalar("SELECT SUM(filesize) FROM {$dv}space_upfile WHERE spaceuserid='{$GLOBALS['spaceUserID']}'");
		if( $_SpaceSize > 0 ){
			$_SpaceSize = number_format(((float)$_SpaceSize/1024)/1024,4);
			$spaceUserInfo['spacesize'] = php_cCur($spaceSystemSetting[15]) - $_SpaceSize;
			if( $spaceUserInfo['spacesize'] < 0 ) {
				$spaceUserInfo['spacesize'] = 0;
			}
		}
		if( $spaceUserInfo['spacesize'] == 0 ){
			$_strMsg .= str_replace('{$Tpl_SpaceSize}',$spaceSystemSetting[15],$lang['tpl.str10']);
		} else{
			$_strMsg .= str_replace('{$Tpl_SpaceSize}',$spaceUserInfo['spacesize'],$lang['tpl.str11']);
		}
	}
	$db->query("UPDATE {$dv}space_user SET TopicNum='{$_TopicNum}',FavNum='{$_FavNum}',PhotoNum='{$_PhotoNum}',PostNum='{$_PostNum}',medianum='{$_MediaNum}',TodayNum='{$_TodayNum}',LastUpTime='{$_LastUpTime}',spacesize='{$spaceUserInfo['spacesize']}' WHERE userid='{$GLOBALS['spaceUserID']}'");
	spaceShowMsg($_strMsg,1);
	exit;
}

function Apply_Today_Star()	//	申请今日之星
{
	global $fsetting, $spaceSystemUpSetting, $lang, $dv, $db, $spaceUserInfo, $userid;
	if (empty($spaceUserInfo['myphoto_path'])) {	//	申请今日之星之前，必须先上传个人相片
		spaceShowMsg($lang['spaceError.str54'], 0, '', false);
		return false;
	}
	$myphoto_path = $fsetting['forumuploadname'].'/'.$spaceSystemUpSetting[19].'/'.$spaceUserInfo['myphoto_path'];
	if (!FileHandler::is_file($myphoto_path)) {	//	个人相片不存在或已丢失，请重新上传个人相片再申请
		spaceShowMsg($lang['spaceError.str55'], 0, '', false);
		return false;
	}
	if ($db->query("REPLACE INTO {$dv}space_apply_today_star(userid, apply_timestamp, username, nickname, user_photo, user_preview_photo, status, apply_desc) VALUES('{$userid}', ".TIME_NOW.", '{$spaceUserInfo['username']}', '{$spaceUserInfo['nickname']}', '{$spaceUserInfo['myphoto_path']}', '{$spaceUserInfo['myphoto_preview_path']}', '0', '')")) {
		spaceShowMsg($lang['tpl.str135'], 1, '', false);
		return true;
	} else {
		spaceShowMsg($lang['spaceError.str56'], 0, '', false);
		return false;
	}
}//end function Apply_Today_Star

function uploadedFilesProc(&$arg_postcontent) // 对已成功上传的文件进行处理，包括预览图片的生成
{
	global $fsetting, $spaceSystemUpSetting, $upfileinfo, $ihaveupfile, $uploadedfilesinfo, $fsetting, $boardid, $userid, $membername, $db, $dv, $__upfileinfo;
	if (empty($_P_PostContent)) {
		$_P_PostContent =& $GLOBALS['postcontent'];
	}
	$ihaveupfile = 0;
	$upfileinfo = '';
	//Start 检查上传临时目录中是否有此次上传的相关文件
		if (false !== strpos($__upfileinfo, '||')) {
			if ($tmparr = explode('||', $__upfileinfo)) {
				foreach ($tmparr AS $val) {
					$tmp1 = unserialize(base64_decode($val));
					foreach ($tmp1 AS $tmp2) {
						$uploadedfilesinfo[] = $tmp2;
					}
				}
				unset($tmparr, $tmp);
			}
		} else {
			$uploadedfilesinfo = unserialize(base64_decode($__upfileinfo));
		}
		if (empty($uploadedfilesinfo) OR !is_array($uploadedfilesinfo)) {
			return false;
		}
	//End 检查上传临时目录中是否有此次上传的相关文件

	//Start 初始化相关目录
		require_once INC_PATH.'upload.functions.php';
		$updirs = initUploadDirectories(array('init_updestdir'=>false, 'destdir'=>$uploadedfilesinfo[0]['subuploaddir']));
		FileHandler::find_writable_dir($uptopdir); // 设置可写目录
		$tempdir = $updirs['uptmpdir'];
		$destdir = $updirs['spacedestdir'];
		$canmakethumbnail = (($spaceSystemUpSetting[17] != 0) AND canmakethumbnail());
		$previewimgdir = $updirs['spacepreviewdestdir'];
	//End 初始化相关目录

	$documentroot = $updirs['documentroot'];
	$comma = '';
	$insert_stmt = $renamelist_src = $renamelist_dest = array();
	$nowdate = TIME_NOW;
	$arrtmpname = array();
	foreach ($uploadedfilesinfo AS $val) {
		$val['ext'] = strtolower($val['ext']);
		//关于文件后缀/文件扩展名的一劳永逸的防范说明：除了图片以外的所有文件，都将在其文件名的末尾，追加一个下划线"_"，用于提高安全性
		if ($val['ftype'] != 1 OR false === strpos('|gif|jpg|jpeg|png|bmp|tif|iff|', '|'.strtolower(trim($val['ext'])).'|')) {
			$val['ext'] .= '_';
		}
		$val['name'] = strtolower($val['name']);
		$thumbnailfile = $tempdir.'/__dv_tmp_preview_file__'.$val['name'];
		$destfile = $destdir.'/'.$val['name'].'.'.$val['ext'];			// 即将移动到的正式存储位置
		$tmpfile = realpath($tempdir.'/'.$val['uploaded_tmpfile']);	// 成功上传的在临时存储目录内的文件
		if (false === $tmpfile) {
			continue;
		}
		$previewfile = '';
		if ($val['ftype'] == 1 AND true === $canmakethumbnail) {			
			if (@image_thumbnail($tmpfile, $spaceSystemUpSetting[14], $spaceSystemUpSetting[15], $thumbnailfile)) {
				$previewfile = $previewimgdir.'/'.$val['name'].'.jpg';
				$renamelist_src[] = $thumbnailfile.'.jpg';
				$renamelist_dest[] = $previewfile;
				//$previewfile = str_replace($documentroot.'/', '', $previewfile);
			}
		}
		$renamelist_src[] = $tmpfile;
		$renamelist_dest[] = $destfile;
		//$destfile = str_replace($documentroot.'/', '', $destfile);
		$arrtmpname[] = $val['name'];
		$destfile = $db->escape_string(str_replace($updirs['spaceuptopdir'].'/', '', $destfile));
		$previewfile = $db->escape_string(str_replace($updirs['spaceuptopdir'].'/', '', $previewfile));
		$insert_stmt[] = "INSERT INTO {$dv}space_upfile(spaceuserid,userid,username,filename,sfilename,filetype,filesize,previewimage,islock,istopic,dateandtime) VALUES('{$GLOBALS['spaceUserID']}', '{$GLOBALS['userid']}', '{$GLOBALS['spaceUserName']}', '{$destfile}', '".$db->escape_string(basename($destfile))."', '".$db->escape_string($val['ftype'])."', '".$db->escape_string($val['size'])."', '".$db->escape_string($previewfile)."', 4, -1, '{$nowdate}')";
	}
	if (!empty($renamelist_src) AND !empty($renamelist_dest)) {
		if (count($renamelist_src) == count($renamelist_dest)) {
			if (FileHandler::rename($renamelist_src, $renamelist_dest)) {
				$arrfind = $arrrepl = array();
				foreach ($insert_stmt AS $index => $stmt) {
					if ($db->query($stmt)) {
						$insertedid = $db->insert_id();
						if ($insertedid <= 0) {
							$insertedid = $db->scalar("SELECT MAX(f_id) FROM {$dv}upfile");
						}
						if ($insertedid > 0) {
							$ihaveupfile = 1;
							$upfileinfo .= $comma.$insertedid;
							$comma =',';
							$arrfind[] = ']viewfile.php?src=space&amp;id=ViewFileID_'.$arrtmpname[$index].'[/upload]';
							$arrrepl[] = ']viewfile.php?src=space&id='.$insertedid.'[/upload]';
						}
					}
				}//end foreach
				if (!empty($arg_postcontent)) {
					$arg_postcontent = str_replace($arrfind, $arrrepl, $arg_postcontent);
				}
				@FileHandler::chmod($renamelist_dest, 0755);
			}
		}
	}
	return array($ihaveupfile, $upfileinfo);
}//end function uploadedFilesProc
?>