<?php

/*
	[SupeSite/X-Space] (C)2001-2006 Comsenz Inc.
	查看个人空间信息内容页面

	$RCSfile: viewspace.php,v $
	$Revision: 1.157 $
	$Date: 2007/07/11 18:33:59 $
*/

if(!defined('IN_SUPESITE')) {
	exit('Access Denied');
}

$itemid = intval($_SGET['itemid']);
if(empty($itemid)) messagebox('error', 'not_found');

//来源
$referer = empty($_SERVER['HTTP_REFERER'])?'':$_SERVER['HTTP_REFERER'];

//统一风格显示
$viewspacetpl = 0;
if(empty($_SCONFIG['viewspacetplmode'])) {//不启用
	$viewspacetpl = 0;
} elseif ($_SCONFIG['viewspacetplmode'] == 1) {//自动识别
	$_SCONFIG['htmlviewspace'] = 0;//html生成失效
	if(!empty($referer) && (strpos($referer, 'spacecp') || preg_match("/(\/|\?|uid\-)\d(\/)*/", $referer))) {
		$viewspacetpl = 0;
	} else {
		$viewspacetpl = 1;
	}
} elseif ($_SCONFIG['viewspacetplmode'] == 2) {//强制
	$viewspacetpl = 1;
}
$_SGLOBAL['viewspacetpl'] = $viewspacetpl;

dbconnect();

$isupdate = freshcookie($itemid);

$query = $_SGLOBAL['db']->query('SELECT * FROM '.tname('spaceitems').' WHERE itemid=\''.$itemid.'\'');
if($item = $_SGLOBAL['db']->fetch_array($query)) {
	$uid = $item['uid'];
	$type = $_SGET['type'] = $item['type'];
	if(!empty($item['password'])) {
		getcookie(1);
		if($uid != $_SGLOBAL['supe_uid'] && $_SGLOBAL['member']['groupid'] != 1 && (empty($_COOKIE[$cookiepre.'viewpwd']) || $_COOKIE[$cookiepre.'viewpwd'] != md5($item['password'].$item['itemid']))) {
			$showtext = '<table>
				<form action="'.S_URL.'/batch.common.php?action=checkinfopwd" method="post">
				<tr><td>'.$lang['the_information_required_password_access'].':</td></tr>
				<tr><td>
				<input type="password" name="pwd" size="12" />
				<input type="hidden" name="itemid" value="'.$item['itemid'].'" />
				<input type="hidden" name="pwdsubmit" value="true" />
				<button type="submit" name="submit" value="true">'.$lang['visit_the_info'].'</button>
				</td></tr>
				</form>
				</table>';
			messagebox('error', $showtext);
		}
		$_SCONFIG['htmlviewspace'] = 0;
	}
} else {
	if(!empty($_GET['fromdiscuz']) && $_GET['fromdiscuz'] == md5($_SGLOBAL['authkey'].'-'.$itemid)) {
		dbconnect(1);
		$_SGLOBAL['db_bbs']->query('UPDATE '.tname('threads', 1).' SET itemid=0 WHERE itemid=\''.$itemid.'\'');
	}
	messagebox('error', 'not_found');
}

if($type == 'news') {
	sheader(geturl('action/viewnews/itemid/'.$item['itemid']));
}
if($item['folder'] != 1) {
	getcookie(1);
	$_SCONFIG['htmlviewspace'] = 0;
	if($uid != $_SGLOBAL['supe_uid'] && $_SGLOBAL['member']['groupid'] != 1) messagebox('error', 'not_view');
}

$space = getuserspace($uid);
getcookie();
if(empty($space)) {
	$_SGET['php'] = 1;
	$space['spacename'] = $item['username'];
}

if($space['islock']) {
	getcookie(1);
	if($uid != $_SGLOBAL['supe_uid'] && $_SGLOBAL['member']['groupid'] != 1) messagebox('error', 'space_lock', S_URL);
}
$space['showcp'] = 0;

$spaceself = 0;
if($uid == $_SGLOBAL['supe_uid']) {
	$spaceself = 1;
	$_SGET['php'] = 1;
} else {
	if($isupdate && $_SGLOBAL['supe_uid']) $_SGLOBAL['db']->query("REPLACE INTO ".tname('tracks')." (uid, itemid, dateline) VALUES ('$_SGLOBAL[supe_uid]', '$itemid', '$_SGLOBAL[timestamp]')");
}
if(!empty($_SGET['css'])) $_SCONFIG['htmlviewspace'] = 0;

if(!empty($_SCONFIG['htmlviewspace'])) {
	$_SHTML['uid'] = $uid;
	$_SHTML['action'] = 'viewspace';
	$_SHTML['itemid'] = $itemid;
	$_SGLOBAL['htmlfile'] = gethtmlfile($_SHTML);
	ehtml('get', $_SCONFIG['htmlviewspacetime']);
	$_SCONFIG['debug'] = 0;
}

//更新统计数
if($isupdate || !$_SCONFIG['updateview']) {
	//更新主题查看数
	updateviewnum($itemid);
	//更新作者空间查看数
	updatespaceviewnum($uid);
}

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

$keywords = array();
$description = '';
$perpage = $_SCONFIG['viewspace_pernum'];

$item['itemtypename'] = '';
if($item['itemtypeid']) {
	$_SGET['itemtypeid'] = $item['itemtypeid'];
	$query = $_SGLOBAL['db']->query('SELECT * FROM '.tname('itemtypes').' WHERE typeid=\''.$item['itemtypeid'].'\'');
	if($value = $_SGLOBAL['db']->fetch_array($query)) {
		if($value['viewperm']) {
			$_SCONFIG['htmlviewspace'] = 0;
			if($item['uid'] != $_SGLOBAL['supe_uid']) {
				$query2 = $_SGLOBAL['db']->query('SELECT * FROM '.tname('friends').' WHERE uid=\''.$uid.'\' AND frienduid=\''.$_SGLOBAL['supe_uid'].'\' AND grade IN ('.$value['viewperm'].') LIMIT 1');
				if(!$_SGLOBAL['db']->fetch_array($query2)) {
					getcookie(1);
					if($_SGLOBAL['member']['groupid'] != 1) messagebox('error', 'not_friend');
				}
			}
		}
		$item['itemtypename'] = $value['typename'];
	}
}

$typeaction = gettypetablename($item['type']);

$commentlist = array();
if(empty($item['tid'])) {

	$listcount = $item['replynum'] + $item['trackbacknum'];
	if($listcount) {
		$query = $_SGLOBAL['db']->query('SELECT u.*, c.* FROM '.tname('spacecomments').' c LEFT JOIN '.tname('userspaces').' u ON u.uid=c.authorid WHERE c.itemid=\''.$itemid.'\' ORDER BY c.dateline DESC LIMIT 0,'.$perpage);
		while ($value = $_SGLOBAL['db']->fetch_array($query)) {
			$value['photo'] = getphoto($value['authorid'], $value['photo']);
			$commentlist[] = $value;
		}
	}
	
	include_once(S_ROOT.'./include/supe_bbcode.inc.php');
	$commenthtml = empty($commentlist)?'':getcommenthtml($commentlist);
	if(empty($item['subtype'])) {
		$showtplfile = 'styles/space/viewspace_'.$item['type'].'.html.php';
	} else {
		$showtplfile = 'styles/space/viewspace_'.$item['type'].'_'.$item['subtype'].'.html.php';
	}
} else {
	$item['type'] = 'blog';
	dbconnect(1);
	$query = $_SGLOBAL['db_bbs']->query('SELECT * FROM '.tname('threads', 1).' WHERE tid=\''.$item['tid'].'\' AND displayorder>=0');
	if(!$thread = $_SGLOBAL['db_bbs']->fetch_array($query)) {
		updatetable('spaceitems', array('folder'=>3, 'tid'=>0), array('itemid'=>$itemid));
		messagebox('error', 'not_found');
	}
	$updatesqlarr = array();
	if($thread['replies'] != $item['replynum']) {
		updatetable('spaceitems', array('replynum'=>$thread['replies']), array('itemid'=>$itemid));
	}
	$listcount = $thread['replies'];
	if($listcount) {
		$userspacearr = array();
		$query = $_SGLOBAL['db_bbs']->query('SELECT p.* FROM '.tname('posts', 1).' p WHERE p.tid=\''.$item['tid'].'\' AND p.invisible=\'0\' AND p.first != \'1\' ORDER BY p.dateline LIMIT 0,'.$perpage);
		include_once(S_ROOT.'/include/bbcode.inc.php');
		$attachtags = array();
		$attachpids = 0;
		while ($value = $_SGLOBAL['db_bbs']->fetch_array($query)) {
			
			$userspacearr[$value['authorid']] = $value['authorid'];
			$value['id'] = $value['pid'];
			$value['photo'] = getphoto($value['authorid'], '');//无头像
			if($value['attachment']) {
				$attachpids .= ",$value[pid]";
				$value['attachment'] = 0;
				if(preg_match("/\[attach\](\d+)\[\/attach\]/i", $value['message'])) {
					$attachtags[] = $value['pid'];
				}
			}
			$value['message'] = bbcode($value['message'], $value['bbcodeoff'], $value['smileyoff'], $value['htmlon'], $space['jammer']);
			$commentlist[$value['pid']] = $value;
		}
		
		if(!empty($userspacearr)) {
			$userarr = array();
			$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('userspaces')." WHERE uid IN (".simplode($userspacearr).")");
			while ($value = $_SGLOBAL['db']->fetch_array($query)) {
				$value['photo'] = getphoto($value['uid'], $value['photo']);//重构图像
				unset($value['dateline']);
				$userarr[$value['uid']] = $value;
			}
			
			foreach ($commentlist as $pid => $post) {
				if(!empty($userarr[$post['authorid']])) {
					$commentlist[$pid] = array_merge($post, $userarr[$post['authorid']]);
				}
			}
		}

		if($attachpids) {
			$query = $_SGLOBAL['db_bbs']->query("SELECT * FROM ".tname('attachments', 1)." WHERE pid IN ($attachpids)");
			while($attach = $_SGLOBAL['db_bbs']->fetch_array($query)) {
				if(B_VER == '4') {
					$extension = strtolower(fileext($attach['filename']));
					$attach['isimage'] = in_array($extension, array('jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp')) ? 1 : 0;
				}
				$attach['dateline'] = sgmdate($attach['dateline']);
				$attach['attachsize'] = formatsize($attach['filesize']);
				$attach['attachment'] = getbbsattachment($attach);
				$commentlist[$attach['pid']]['attachments'][$attach['aid']] = $attach;
			}
			foreach($attachtags as $pid) {
				$attachlist = $commentlist[$pid]['attachments'];
				$commentlist[$pid]['message'] = preg_replace("/\[attach\](\d+)\[\/attach\]/ie", "attachtag(\\1)", $commentlist[$pid]['message']);
				$commentlist[$pid]['attachments'] = $attachlist;
			}
		}
		
	}
	$showtplfile = 'styles/space/viewspace_bbs.html.php';
}

$tablename = gettypetablename($type);
$query = $_SGLOBAL['db']->query('SELECT * FROM '.tname($tablename).' WHERE itemid=\''.$itemid.'\'');
if(!$itemmsg = $_SGLOBAL['db']->fetch_array($query)) {
	$itemmsg = array();
	updatetable('spaceitems', array('folder'=>3), array('itemid'=>$itemid));
}
$item = array_merge($item, $itemmsg);

$item['attach'] = array();
$item['attachcount'] = 0;
if($item['haveattach'] && ($item['type'] == 'blog' || $item['type'] == 'file')) {
	$query = $_SGLOBAL['db']->query('SELECT * FROM '.tname('attachments').' WHERE itemid=\''.$itemid.'\'');
	while($value = $_SGLOBAL['db']->fetch_array($query)) {
		if($item['type'] == 'blog') {
			if(strpos($item['message'], $value['thumbpath']) === false && strpos($item['message'], $value['filepath']) === false && strpos($item['message'], 'batch.download.php?aid='.$value['aid']) === false) {
				$item['attachcount']++;
				$value['filepath'] = A_URL.'/'.$value['filepath'];
				$value['thumbpath'] = A_URL.'/'.$value['thumbpath'];
				$item['attach'][] = $value;
			}
		} else {
			$item['attachcount']++;
			$value['filepath'] = A_URL.'/'.$value['filepath'];
			$value['thumbpath'] = A_URL.'/'.$value['thumbpath'];
			if(empty($item['picurl'])) $item['picurl'] = $value['filepath'];
			$item['attach'][] = $value;
		}
	}
}

if(!empty($item['remoteurl'])) $item['remoteurl'] = unserialize($item['remoteurl']);
if(!empty($item['relativetags'])) $item['relativetags'] = unserialize($item['relativetags']);

$item['custom'] = array('name'=>'', 'key'=>array(), 'value'=>array());
if(!empty($item['customfieldid'])) {
	$item['custom']['value'] = unserialize($item['customfieldtext']);
	if(!empty($item['custom']['value'])) {
		foreach ($item['custom']['value'] as $key => $value) {
			if(is_array($value)) {
				$item['custom']['value'][$key] = implode(', ', $value);
			}
		}
	}
	$query = $_SGLOBAL['db']->query('SELECT name, customfieldtext FROM '.tname('customfields').' WHERE customfieldid=\''.$item['customfieldid'].'\'');
	if($value = $_SGLOBAL['db']->fetch_array($query)) {
		$item['custom']['name'] = $value['name'];
		$item['custom']['key'] = unserialize($value['customfieldtext']);
	}
}

//页面描述
$description = trim(cutstr(str_replace(array('&nbsp;', "\r", "\n", '\'', '"'), '', strip_tags($item['message'])), 200));

if(!empty($item['includetags'])) {
	$newtagarr = explode("\t", $item['includetags']);
	$keywords = $newtagarr;
	if(!empty($_SCONFIG['allowtagshow'])) $item['message'] = tagshow($item['message'], $newtagarr);
}

if($space['jammer']) {
	mt_srand((double)microtime() * 1000000);
	$item['message'] = preg_replace("/(\<br\>|\<br\ \/\>|\<br\/\>|\<p\>|\<\/p\>)/ie", "sjammer('\\1')", $item['message']);
}

$item['tracks'] = array();
$query = $_SGLOBAL['db']->query('SELECT u.*, tr.dateline, tr.uid FROM '.tname('tracks').' tr LEFT JOIN '.tname('userspaces').' u ON u.uid=tr.uid WHERE tr.itemid=\''.$itemid.'\' ORDER BY tr.dateline DESC LIMIT 0, 24');
while ($value = $_SGLOBAL['db']->fetch_array($query)) {
	$value['photo'] = getphoto($value['uid'], $value['photo']);
	if(empty($value['username'])) {
		$value['username'] = $value['uid'];
	}
	$value['url'] = geturl("uid/$value[uid]");
	$item['tracks'][] = $value;
}

$item['relatives'] = array();
if(!empty($item['relativeitemids'])) {
	$query = $_SGLOBAL['db']->query('SELECT * FROM '.tname('spaceitems').' WHERE itemid IN ('.$item['relativeitemids'].')');
	while ($value = $_SGLOBAL['db']->fetch_array($query)) {
		if($value['type'] == 'news') {
			$value['url'] = geturl('action/viewnews/itemid/'.$value['itemid']);
		} else {
			$value['url'] = geturl('uid/'.$value['uid'].'/action/viewspace/itemid/'.$value['itemid']);
		}
		$item['relatives'][] = $value;
	}
}

if($item['type'] == 'goods') {
	
	$item['auctions'] = array();
	$item['auctionnum'] = 0;
	if($item['subtype'] == 'auction') {
		
		if((($item['starttime'] + $item['term']*3600*24) < $_SGLOBAL['timestamp']) && empty($item['status'])) {
			updatetable('spaceitems', array('folder'=>3), array('itemid'=>$item['itemid']));
		}
		
		$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('goodsprice')." WHERE itemid='$itemid' ORDER BY dateline DESC");
		while ($value = $_SGLOBAL['db']->fetch_array($query)) {
			$value['code'] = authcode($value['priceid'], 'ENCODE');
			$value['allow'] = 0;
			if(empty($item['auctionnum'])) {
				$value['allow'] = 1;
				$item['buyprice'] = $value['price'];
			}
			$item['auctions'][] = $value;
			$item['auctionnum']++;
		}
	} elseif($item['subtype'] == 'goods') {
		//支付宝付款链接
		if(!empty($_SCONFIG['usealipay'])) $item['payurl'] = S_URL.'/batch.common.php?action=alipay&itemid='.$item['itemid'];
	}
	
	dbconnect(1);
	$query = $_SGLOBAL['db_bbs']->query("SELECT * FROM ".tname('members', 1)." WHERE uid='$item[uid]'");
	$item['member'] = $_SGLOBAL['db_bbs']->fetch_array($query);
	include_once(S_ROOT.'./data/system/group.cache.php');
	if(!empty($_SGLOBAL['grouparr'][$item['member']['groupid']])) {
		$item['member']['group'] = $_SGLOBAL['grouparr'][$item['member']['groupid']]['grouptitle'];
	} else {
		$item['member']['group'] = $item['member']['groupid'].'*';
	}
}

if(!empty($item['thumb'])) {
	$item['thumb'] = A_URL.'/'.$item['thumb'];
} else {
	$item['thumb'] = S_URL.'/images/base/nopic.gif';
}
if(!empty($item['image'])) {
	$item['image'] = A_URL.'/'.$item['image'];
} else {
	$item['image'] = S_URL.'/images/base/nopic.gif';
}

//处理商品的语言包
if(!empty($item['quality'])) $item['quality'] = $lang['quality_'.$item['quality']];
if(!empty($item['paymenttype'])) $item['paymenttype'] = $lang['paymenttype_'.$item['paymenttype']];

$item['fromsupesite'] = md5($_SCONFIG['sitekey'].$item['itemid']);
$item['jumpurl'] = geturl('uid/'.$item['uid'].'/action/viewspace/itemid/'.$item['itemid'].'/php/1');

//影音
if($item['type'] == 'video') {
	$item['vcode'] = num2char($item['videoname']);
}

if($space['spacemode'] != 'diy') $space['showside'] = 1;//显示侧边栏

if($item['type'] == 'image') {
	$remote = $space['showside'] = 0;//相册不显示侧边栏
	$item['fhash'] = md5($item['itemid'].$item['uid'].$_SCONFIG['sitekey']);
	if(!empty($item['remoteurl']) || !empty($item['bgmusic']))	$remote = 1;
	$flashurl = S_URL_ALL."/images/base/photov.swf?site=".S_URL_ALL."&itemid=$item[itemid]&hash=$item[fhash]&remote=$remote";
}
//文件处理
if($item['type'] == 'file') {
	$credits = getcredits('attachment');
}
$keywords = implode(',', $keywords);
$title = $item['subject'].' - '.$space['spacename'].' - '.$_SCONFIG['sitename'].' '.$_SCONFIG['seotitle'].' - Powered by X-Space';
$thepagename = '<a href="'.geturl("uid/$uid/action/spacelist/type/$type").'">'.$lang[$item['type']].'</a>';

//模块布局
$leftblock = $mainblock = $rightblock = '';
if(!empty($space['showside'])) {
	if(!empty($item['type']) && !empty($channels['types'][$item['type']])) {
		$leftblock = 'photo,action,itemtype,search,calendar,archive,information,rss';
	} else {
		$leftblock = 'photo,action,itemtype,search,archive,information,rss';
	}
}
if($space['spacemode'] == 'diy' && $space['layout'] == 2 && !empty($leftblock)) {
	$rightblock = $leftblock;
	$leftblock = '';
}
$effect = '';

if(!empty($viewspacetpl)) {

	//默认系统风格
	$title = strip_tags($title);
	$keywords = strip_tags($keywords);
	$description = strip_tags($description);
	//处理导航
	$guidearr[] = array('url' => geturl("uid/$uid"), 'name' => $space[spacename]);
	$guidearr[] = array('url' => geturl("uid/$uid/action/spacelist/type/$type"), 'name' => $channels['menus'][$item['type']]['name']);
	include template('blog_view');
	ob_out();
	
	if(!empty($_SCONFIG['htmlviewspace'])) {
		ehtml('make');
	} else {
		maketplblockvalue('cache');
	}

} else {

	//自己风格
	include_once(S_ROOT.'./include/space_template.inc.php');
	ob_out();
	
	if(!empty($_SCONFIG['htmlviewspace'])) {
		ehtml('make');
	}
}

/**
 * 生成随机对应字符串
 * @param string $numchar 视频文件名
 */
function num2char($numchar) {
	$arr1 = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '_');
	$arr2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	$newarr = array();
	$rand = rand(0, 15);
	//生成一个码表
	foreach ($arr1 as $index => $value) {
		$newarr[$value] = $arr2{$index+$rand};
	}
	$newchar = '';
	$charlen = strlen($numchar);
	//根据码表生成字符串
	for ($i=0; $i<$charlen; $i++) {
		$newchar .= $newarr[$numchar[$i]];
	}
	//格式化随机数并链接新字符串
	$newchar = sprintf("%02d", $rand).$newchar;
	return $newchar;
}

?>