<?php
ini_set('track_errors','1');
ini_set('display_errors','1');
error_reporting(E_ERROR | E_WARNING | E_PARSE);
set_magic_quotes_runtime(0);

// #######################################################################
// #################### START FORUM INITIALIZE SCRIPT ####################
// #######################################################################

$time_array = explode(' ', microtime());
$time_start = $time_array[1] + $time_array[0];
define('ISDVBBS', TRUE);
define('DVBBS_SERVER_URL', 'http://server.dvbbs.net/');
define('DVBBS_PAYTO_URL', 'http://pay.dvbbs.net/');
define('ROOT_PATH', "./");

$cercode_len=4; //验证码长度
$cercode_type=9; //如果只允许数字，设为9;允许数字和小写英文字符，设为35;允许数字和大小写英文字符，设为65
$cercode_width=200;//图片长度
$cercode_height=48;//图片高度
$cercode_agif_delay=20;//设为gif动画时，背景图延时
$cercode_agif_lastDelay=80;//设为gif动画时，验证码延时

if(PHP_VERSION < '4.1.0') {
	$_GET = &$HTTP_GET_VARS;
	$_POST = &$HTTP_POST_VARS;
	$_COOKIE = &$HTTP_COOKIE_VARS;
	$_SERVER = &$HTTP_SERVER_VARS;
	$_ENV = &$HTTP_ENV_VARS;
	$_FILES = &$HTTP_POST_FILES;
	$_SESSION =& $HTTP_SESSION_VARS;
}
$tmpsessid = session_id() ? session_id() : 'PHPSESSID';
if (isset($_COOKIE[$tmpsessid]) AND empty($_COOKIE[$tmpsessid])) {
	unset($_COOKIE[$tmpsessid]);
}

define('INC_PATH', ROOT_PATH.'inc/');
!@is_dir(INC_PATH) AND exit('Cannot find inc directory '.INC_PATH);
require ROOT_PATH.'inc/constants_define.php';

defined('MAIN_DOMAIN_NAME') AND exit('Access denied');

require_once INC_PATH.'dv_clsmain.php';
if ((!isset($_SERVER['HTTP_ACCEPT']) OR !isset($_SERVER['HTTP_CONNECTION']) OR '::1' == $_SERVER['SERVER_ADDR'] OR '::1' == $_SERVER['REMOTE_ADDR']) AND (false === IsWebSearch())) {
	exit('Access denied!');
}

require_once INC_PATH.'general_funcs.php';

define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
$magic_quotes_gpc = MAGIC_QUOTES_GPC;
@extract(i_addslashes($_POST), EXTR_OVERWRITE);
@extract(i_addslashes($_GET), EXTR_OVERWRITE);
@extract(i_addslashes($_COOKIE), EXTR_OVERWRITE);
if(!$magic_quotes_gpc) {
	$_FILES = i_addslashes($_FILES);
}
//防止此变量被客户端有意覆盖
$magic_quotes_gpc = MAGIC_QUOTES_GPC;

function_exists('date_default_timezone_set') AND date_default_timezone_set('Asia/Shanghai');
!defined('TIME_NOW') AND define('TIME_NOW', time());

require_once CONFIG_PATH.'config.php';
header('Content-Type: text/html;charset='.$charset);
require_once INC_PATH.'dv_spacemain.php';

$zliboutputenable = @ini_get('zlib.output_compression');
if (!$zliboutputenable AND function_exists('ob_gzhandler')) {
	$db_obstart = 1;
} else {
	$db_obstart = 0;
}
(!$zliboutputenable AND (1 === $db_obstart)) ? ob_start('ob_gzhandler') : ob_start();
$istoptable=1;


if( $IsSqlDataBase === true ) {
	require_once INC_PATH.'dv_clssql.mssql.php';
} else {
	require_once INC_PATH.'dv_clssql.php';
}

$db = new sqldb();
//模板设置路径，正式版程序中应可根据用户选择判断并读取相关文件
$db->connect($dbhost, $dbuser, $dbpw, $dbname , $charset,$pconnect);

if($attackevasive) {
	include_once INC_PATH.'security.php';
}

$timestamp = TIME_NOW;//time();
$ScriptName = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
if( $_SERVER['SERVER_PORT'] == 80 ){
	$ForumUrl = "http://{$_SERVER['SERVER_NAME']}".dirname($ScriptName);
}else{
	$ForumUrl = "http://{$_SERVER['SERVER_NAME']}:{$_SERVER['SERVER_PORT']}".dirname($ScriptName);
}
$ScriptName = strtolower(basename($ScriptName));
$usertrueip = forumusertrueip();
$boardid = ( is_numeric($boardid) ? $boardid : 0 );

require_once CACHE_PATH.'forum_setting.php';
$fsetting =& $_DCACHE['settings'];
$cercode_image=empty($fsetting['cercode_image'])?'swf':$fsetting['cercode_image'];

(0 == $fsetting['plus_blog']) AND exit('My space is disabled!');

$nowtimes = TIME_NOW;//time();
if ( get_cookie("language") !='' ){
	$_lang = get_cookie("language");
	if (false !== strpos($_lang, '..')) {
		set_cookie("language", '', $GLOBALS['user_selected_cookiedate']);
	} else {
		$fsetting['lang'] = $_lang;
	}
}
if ( get_cookie("style_{$boardid}") !='' ){
	$_css = get_cookie("style_{$boardid}");
	if (false !== strpos($_css, '..')) {
		set_cookie("css", '', $GLOBALS['user_selected_cookiedate']);
	} else {
		$fsetting['css'] = $_css;
	}
}
$cssname = explode('/',$fsetting['css']);
$cssnum = count($cssname);
$cssname = str_replace('.css','',$cssname[count($cssname)-1]);
require_once CACHE_PATH.'style/'.$cssname.'.php';
$imgurl = $_DCACHE['stylecss'][21];
$fsetting['styletpl'] = $_DCACHE['stylecss'][0];
$forumChanSetting = explode(',',$fsetting['chansetting']);
$userid = get_cookie("userid");
if( !is_numeric($userid) ){
	$userid = 0;
}
$membername = strip_tags(trim(get_cookie("username")));
$memberword = trim(get_cookie("password"));
$userhidden = get_cookie("userhidden");

//Start 默认的 COOKIE 超时时间
	$user_selected_cookiedate = get_cookie('selected_cookiedate');
	if (!is_numeric($user_selected_cookiedate)) {
		$user_selected_cookiedate = 24*3600;
		set_cookie('selected_cookiedate', $user_selected_cookiedate, $user_selected_cookiedate);
	} else {
		set_cookie('selected_cookiedate', intval($user_selected_cookiedate), $user_selected_cookiedate);
	}
//End 默认的 COOKIE 超时时间
if ($userid > 0) {
	$_COOKIE_USERID = $userid;
	$_COOKIE_USERNAME = $membername;
	$_COOKIE_USERPASSWD = $memberword;
	$_COOKIE_COME_TIME = get_cookie('cometime');
	$_COOKIE_CBOARDID = get_cookie('cboardid');
	$_COOKIE_SYS_USERNAME = get_cookie('sysusername');
	$_COOKIE_SYS_PASSWD = get_cookie('syspassword');
}

$lang = load_lang($lang, 'space.global' );

if (!isset($fsetting['time_zone_supported']) OR true !== $fsetting['time_zone_supported']) {
	print $lang['space.global.str4'];
	exit;
}

//获取和验证用户信息
$boardmaster = $superboardmaster = $master = $vipuser = $cls_issearch = $founduserper = $vipgroupuser = false;
$statuserid = get_cookie("statuserid");
if($statuserid=='' || !is_numeric($statuserid)){
	$statuserid = str_replace(".","",$usertrueip);
	$statuserid = $statuserid + $timestamp;
	set_cookie("statuserid",$statuserid,7200);
}
if ($userid && strlen($memberword)==16){
	$query=$db->query("Select /*!40001 SQL_CACHE */ u.userid,u.username,u.userpassword,u.useremail,u.userpost,u.usertopic,u.usersex,u.userface,u.userwidth,u.userheight,u.joindate,u.lastlogin,u.userlogins,u.lockuser,u.userclass,u.usergroupid,u.usergroup,u.userwealth,u.userep,u.usercp,u.userpower,u.userbirthday,u.userlastip,u.userdel,u.userisbest,u.userhidden,u.usermsg,u.ischallenge,u.usermobile,u.titlepic,u.usertitle,u.truepassword,u.usertoday,u.usermoney,u.userticket,u.followmsgid,u.vip_startime,u.vip_endtime,u.userfav,o.id,o.actforip as getcode,o.boardid,o.ip,o.lastimebk,o.browser,o.usergroupid as nowgroupid From {$dv}user u,{$dv}online o Where u.userid=o.userid And u.userid=$userid");
	$userinfo = $db->fetch_array($query);
	if ($memberword != $userinfo['truepassword'] || $userinfo['lockuser']==1 || $userinfo['usergroupid']==5){
		$myuserid = 1;
	}
	if($myuserid == 1){
		$query=$db->query("Select /*!40001 SQL_CACHE */ userid,username,userpassword,useremail,userpost,usertopic,usersex,userface,userwidth,userheight,joindate,lastlogin,userlogins,lockuser,userclass,usergroupid,usergroup,userwealth,userep,usercp,userpower,userbirthday,userlastip,userdel,userisbest,userhidden,usermsg,ischallenge,usermobile,titlepic,usertitle,truepassword,usertoday,usermoney,userticket,followmsgid,vip_startime,vip_endtime,userfav From {$dv}user Where userid=$userid");
		$userinfo = $db->fetch_array($query);
		if ($memberword != $userinfo['truepassword'] || $userinfo['lockuser']==1 || $userinfo['usergroupid']==5){
			$userid = 0;
		}else{
			$onlineexists = 1;
		}
	}
	if($userid>0){
		$userid = $userinfo['userid'];
		$usergroupid = $userinfo['usergroupid'];
		if ( $userinfo['nowgroupid'] == '' ){$userinfo['nowgroupid'] = $userinfo['usergroupid'];}
		switch($userinfo['usergroupid']){
			case 8:
				$vipuser = true;
				break;
			case 3:
				$boardmaster = true;
				break;
			case 2:
				$boardmaster = true;
				$superboardmaster = true;
				break;
			case 1:
				$master = true;
				$boardmaster = true;
				break;
		}
		//用户信息处理
		if ( $userinfo['usertoday'] == '' ){
			$db->query("Update {$dv}user Set usertoday='0|0|0|0|0' Where userid=$userid");
			$userinfo['usertoday'] = '0|0|0|0|0';
			$UserToday = array(0,0,0,0,0);
		}else{
			$UserToday = explode('|',$userinfo['usertoday']);
			if ( count($UserToday) != 5 ){
				$db->query("Update {$dv}user Set usertoday='0|0|0|0|0' Where userid=$userid");
				$userinfo['usertoday'] = '0|0|0|0|0';
				$UserToday = array(0,0,0,0,0);
			}
		}
		if ($userinfo['vip_startime'] > 0){
			if ( dateDiff('d',$nowtimes,$userinfo['vip_startime']) > 0 ){
				$vipgroupuser = true;
			}else{
				if ( $usergroupid > 8 ){
					$userparentid = $db->scalar("SELECT parentgid FROM {$dv}usergroups WHERE usergroupid=$usergroupid");
					if ($userparentid == 5){
						$tquery=$db->query("Select /*!40001 SQL_CACHE */ usertitle,grouppic,usergroupid From {$dv}usergroups Where parentgid=3 And minarticle<={$userinfo[userpost]} Order By minarticle Desc Limit 1");
						if( $trs = $db->fetch_array($tquery) ){
							$db->query("Update {$dv}user Set userclass='{$trs[usertitle]}',titlepic='{$trs[grouppic]}',usergroupid='{$trs[usergroupid]}',vip_startime=null,vip_endtime=null Where userid=$userid");
						}
					}
				}else{
					$db->query("Update {$dv}user Set vip_startime=null,vip_endtime=null Where userid=$userid");
				}
				$userinfo['vip_startime'] = '';
				$userinfo['vip_endtime'] = '';
			}
		}
		if ( dateDiff('d',$nowtimes,$userinfo['lastlogin']) != 0 ){
			$db->query("Update {$dv}user Set usertoday='0|0|0|0|0',lastlogin='{$nowtimes}' Where userid=$userid");
			$userinfo['lastlogin'] = $nowtimes;
			$userinfo['usertoday'] = '0|0|0|0|0';
			$UserToday = array(0,0,0,0,0);
		}
		if (defined('THIS_SCRIPT') AND THIS_SCRIPT !== 'login') {
			$userhidden = $userinfo['userhidden'];
		}
		if ( $userhidden == 2 && dateDiff('s',$userinfo['lastlogin'],$nowtimes) > $fsetting['onlinetimeout']*60 ){
			$db->query("Update {$dv}user Set userlastip='{$usertrueip}',lastlogin='{$nowtimes}' Where userid=$userid");
			$userinfo['lastlogin'] = $nowtimes;
		}
		$sendmsgnum = $sendmsgid = 0;
		$sendmsguser = '';
		if ( $userinfo['usermsg'] != '' ){
			$usermsg = explode('||',$userinfo['usermsg']);
			if ( count($usermsg) == 3 ){
				$sendmsgnum = intval($usermsg[0]);
				$sendmsgid = $usermsg[1];
				$sendmsguser = $usermsg[2];
			}
		}
		if ( $userinfo['followmsgid'] != '' ){
			$followmsgid = explode(',',$userinfo['followmsgid']);
			foreach( $followmsgid as $val ){
				if ( strlen($val) > 0 && strlen($val) < 50 && $val != '' ){
					$val = addslashes($val);
					eval("\$lang['user.str1']=\"{$lang['user.str1']}\";");
					eval("\$lang['user.str2']=\"{$lang['user.str2']}\";");
					$db->query("Insert into {$dv}message (incept,sender,title,content,sendtime,flag,issend) values ('{$val}','{$fsetting[forumname]}','{$lang[user.str1]}','{$lang[user.str2]}','{$nowtimes}',0,1)");
					$tquery=$db->query("Select /*!40001 SQL_CACHE */ id,sender From {$dv}message Where incept='{$val}' Order By id Desc Limit 1");
					$trs = $db->fetch_array($tquery);
					$tools_inceptid = $trs['id']. '||' .$trs['sender'];
					$tools_newincept=$db->scalar("Select /*!40001 SQL_CACHE */ Count(id) From {$dv}message Where flag=0 and issend=1 and delr=0 And incept='{$val}'");
					if ( !is_numeric($tools_newincept) || $tools_newincept == '' ){$tools_newincept = 0;}
					$tools_msginfo = $tools_newincept. '||' .$tools_inceptid;
					$tools_msginfo = addslashes($tools_msginfo);
					$db->query("Update {$dv}user Set usermsg='{$tools_msginfo}' Where username='{$val}'");
				}
			}
			$db->query("Update {$dv}user Set followmsgid='' Where userid=$userid");
			$userinfo['followmsgid'] = '';
		}
	}else{
		$userid = 0;
		$usergroupid = 7;
		$query=$db->query("Select /*!40001 SQL_CACHE */ id,boardid,ip,actforip as getcode,lastimebk,browser,usergroupid as nowgroupid From {$dv}online Where id = $statuserid");
		$userinfo = $db->fetch_array($query);
	}
}else{
	$userid = 0;
	$usergroupid = 7;
	$query=$db->query("Select /*!40001 SQL_CACHE */ id,boardid,ip,actforip as getcode,lastimebk,browser,usergroupid as nowgroupid From {$dv}online Where id = $statuserid");
	$userinfo = $db->fetch_array($query);
}

include_once CACHE_PATH.'group/group_'.$usergroupid.'.php';
if( $userid > 0 ){
	if( is_file(CACHE_PATH.'group/user_'.$boardid.'_'.$userid.'.php') ){
		include_once CACHE_PATH.'group/user_'.$boardid.'_'.$userid.'.php';
	}
}

unset($_DCACHE['settings']);

//	other
defined('UPLOAD_BASEDIR') AND ($fsetting['forumuploadname'] = UPLOAD_BASEDIR);

// #######################################################################
// #################### END FORUM INITIALIZE SCRIPT ######################
// #######################################################################



// #######################################################################
// #################### START space INITIALIZE SCRIPT #####################
// #######################################################################

$fsetting['styletpl'] = 'space';
$fsetting['styletpl_prev'] = 'default.';
$spaceName = '';
$arrArchiveLink = array(null,null,null,null,null);
$_queryString = strtolower($_SERVER['QUERY_STRING']);
if( !empty($_queryString) ){
	$arrArchiveLink = explode('.', $_queryString);
	if (false === strpos($arrArchiveLink[0],'show_')) {
		$spaceName = str_replace('.html', '', $arrArchiveLink[0]).'';
	}
	
}
if (false === strpos($_queryString, '.html') AND false === strpos($_queryString, '.xml')) {
	$spaceName = strval(($_GET['user'] ? $_GET['user'] : $_POST['user']));	// 必须为字符串类型
}

$spaceUserID = $userid;
$_strTmp = str_replace('userid_','',$arrArchiveLink[0]);
if( is_numeric($_strTmp) && strpos($arrArchiveLink[0],'userid_') !== false ){
	$spaceUserID = php_cCur($_strTmp);
	$spaceName = '';
}
if( $userid > 0 ){
	$spaceUserName = $membername;
} else{
	$spaceUserName = '';
}

//Start Initialize System Config
	require_once CACHE_PATH.'space/space_config.php';
	$spaceConfig_System =& $_DCACHE['spaceConfig_system'];
	$spaceSystemSetting = explode(',',$spaceConfig_System['s_setting']);
	$spaceSystemUpSetting = explode('|',$spaceSystemSetting[12]);
	$spaceConfig_Syscat =& $_DCACHE['spaceConfig_syscat'];
	$spaceConfig_Syschatcat =& $_DCACHE['spaceConfig_syschatcat'];
	$spaceConfig_Syschatcat_parent =& $_DCACHE['spaceConfig_syscat_parent'];
	$spaceConfig_Default =& $_DCACHE['spaceConfig_default'];
	$spaceConfig_UserCat =& $_DCACHE['spaceConfig_usercat'];
//End Initialize System Config

//Start UrlRewrite
$urlRewriteEnable = false;
if( $urlRewriteEnable === false ){
	$ModHtmlLinked = "space.php?";
	$mArchiveLink = "spaceindex.php?";
	$spaceurl_r = "spacerss.php?";
} else{
	$ModHtmlLinked = '';
	$mArchiveLink = '';
	$spaceurl_r = '';
}
//End UrlRewrite

//Start Initialize space User Info
	$isSpaceMaster = $master;
	$isSpaceOwner = false;
	$spaceUserInfo =& $spaceConfig_Default['spaceUserInfo'];
	$spaceUserCat =& $_DCACHE['spaceConfig_usercat'];
	$_whereStmt = '';
	if( $spaceName !== '' ){
		$_whereStmt = " WHERE spacename='{$spaceName}' ";
	} elseif( $spaceUserID > 0 ){
		$_whereStmt = " WHERE userid='{$spaceUserID}' ";
	} else{
	}
	if( $_whereStmt !== '' ){
		if (!isset($mustselect)) {
			if (empty($_POST['postdiarytopic']) AND (defined('THIS_SCRIPT') AND in_array(THIS_SCRIPT, array('space', 'spacemanage', 'spacepostings')))) {
				$mustselect = true;
			} else {
				$mustselect = false;
			}
		}
		if( $query = $db->query("SELECT /*!40001 SQL_CACHE */ 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,S.s_skinname,S.s_path,S.s_viewpic,S.s_info,S.s_builder".(true === $mustselect ? ',U.diary_topic' : '')." FROM {$dv}space_user U INNER JOIN {$dv}space_skins S ON U.skinid=S.s_id {$_whereStmt}",array('pageSize'=>1,'debug'=>false)) ){
			set_magic_quotes_runtime(1);
			$spaceUserInfo =& $db->fetch_array($query);
			set_magic_quotes_runtime(0);
		}
	}
	if( $spaceUserInfo === false ){
		$spaceUserID = 0;
		$spaceUserInfo =& $_DCACHE['spaceConfig_default']['spaceUserInfo'];
		$spaceSetting = explode(',',$spaceUserInfo['spacesetting']);
		$spaceUserCat =& $_DCACHE['spaceConfig_usercat'];
	} else{
		if (!empty($_POST['postdiarytopic'])) {
			$spaceUserInfo['diary_topic'] = unserialize(base64_decode($_POST['postdiarytopic']));
		} elseif (isset($spaceUserInfo['diary_topic'])) {
			if (empty($spaceUserInfo['diary_topic'])) {
				$spaceUserInfo['diary_topic'] =& updateDiaryTopic(array('userid' => $spaceUserInfo['userid']));
			} else {
				$spaceUserInfo['diary_topic'] = unserialize(stripslashes($spaceUserInfo['diary_topic']));
			}
		}
		$spaceUserID = $spaceUserInfo['userid'];
		$spaceUserName = $spaceUserInfo['nickname'];
		$spaceName = $spaceUserInfo['spacename'];
		$spaceSetting = explode(',',$spaceUserInfo['spacesetting']);
		if( $userid > 0 && $spaceUserID == $userid ){
			$isSpaceOwner = true;
		}
		if( $isSpaceMaster === false ){
			$lang = load_lang($lang, 'space.error' );
			if( $spaceUserInfo['stats'] == 2 ){
				spaceshowmsg($lang['spaceError.str49']);
			} elseif( $spaceUserInfo['stats'] == 1 && $isSpaceOwner === true ){
				spaceshowmsg($lang['spaceError.str50']);
			}
			if( $spaceSetting[0] != 1 && $isSpaceOwner === false ){
				spaceshowmsg($lang['spaceError.str39']);
			}
		}
		if ($spaceUserInfo['todaynum'] > 0 AND dateDiff('d',$spaceUserInfo['lastuptime'],TIME_NOW) != 0) {
			$spaceUserInfo['todaynum'] = 0;
			$db->query("UPDATE {$dv}space_user SET todaynum=0 WHERE userid='{$spaceUserID}'");
		}
		if( $spaceUserInfo['spacesize'] == '' || $spaceUserInfo['xmldata'].'' === '' ){
			$spaceUserCat =& rebuildUserXmlData($spaceUserID, false);
			if (empty($spaceUserCat)) {
				$spaceUserCat =& $_DCACHE['spaceConfig_usercat'];
			}
		} else{
			if( ( $spaceUserCat = unserialize(base64_decode($spaceUserInfo['xmldata'])) ) === false ){
				$spaceUserCat =& $_DCACHE['spaceConfig_usercat'];
			}
		}
	}
//End Initialize space User Info

//清理临时变量
unset($_queryString,$_strTmp,$_whereStmt,$_DCACHE['spaceConfig_system'],$_DCACHE['spaceConfig_syscat'],$_DCACHE['spaceConfig_syschatcat'],$_DCACHE['spaceConfig_default']);
// #######################################################################
// ##################### END space INITIALIZE SCRIPT ######################
// #######################################################################
?>