<?php
/*
	[SupeSite/X-Space] (C)2001-2006 Comsenz Inc.
	日志导入论坛功能

	$Id: blogpost.php 8965 2008-10-16 06:20:49Z zhaofei $
*/
include_once('./include/main.inc.php');
include_once(S_ROOT.'./language/batch.lang.php');
include_once(S_ROOT.'./data/system/bbsforums.cache.php');

if(empty($_SCONFIG['ucmode'])) {
	exit('Access Denied');
}

$action = empty($_GET['action'])? '': trim($_GET['action']);
$itemid = postget('itemid');

if($action == 'import') {
	$forum = getbbsforum();
	
	$html = '<h5><a href="javascript:;" onclick="getbyid(\'xspace-ajax-div\').style.display=\'none\';" target="_self">'.$blang['mail_close'].'</a>'.$blang['import_bbs'].'</h5>
		<div class="xspace-ajaxcontent">
		<form method="post" action="'.S_URL.'/blogpost.php">
			<table width="100%" summary="" cellpadding="5" cellspacing="0" border="0">
				<tr>
					<td>'.$blang['target_bbs'].'</td>
					<td>
	';
	if(!empty($forum)){
		$html .= '<select name="fid">';
		foreach($forum as $value) {
			if($value['allowpost'] == 1) {
				$html .= '<option value="'.$value['fid'].'">'.$value['pre'].$value['name'].'</option>';
			} else {
				$html .= '<optgroup label='.$value['pre'].$value['name'].'>'.$value['pre'].$value['name'].'</optgroup>';
			}
		}
		$html .= '</select>';
	}

	$html .= '</td></tr>
			<input type="hidden" name="itemid" value="'.$itemid.'">
			<tr>
				<td>&nbsp;</td>
				<td><button type="submit" name="blogpost" value="true">'.$blang['blog_submit'].'</button></td>
			</tr>
			</table>
		</form>
	</div>
	<iframe id="phpframe_import" name="phpframe_import" width="0" height="0" marginwidth="0" frameborder="0" src="about:blank"></iframe>';
	showxml($html);
}

if(submitcheck('blogpost')) {
	include_once(S_ROOT.'./function/editor.func.php');
	include_once(S_ROOT.'./function/common.func.php');

	getcookie();

	$fid = intval($_POST['fid']);

	if($_SGLOBAL['bbsforumarr'][$fid]['allowpost'] != 1) {
		messagebox('error', 'forum_not_import');
	}
	dbconnect(1);
	$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('spaceitems')." si, ".tname('spaceblogs')." sb where si.itemid=sb.itemid AND si.itemid='$itemid'");
	if($itemarr = $_SGLOBAL['db']->fetch_array($query)) {
		$itemarr['subject'] = addslashes(html2bbcode($itemarr['subject']));
		$itemarr['message'] = addslashes(html2bbcode($itemarr['message']));

		//处理自定义字段
		$message_customfield = '';
		if($itemarr['customfieldid'] && $itemarr['customfieldtext']) {

			$customfielddata = unserialize($itemarr['customfieldtext']);
			$query = $_SGLOBAL['db']->query("SELECT name, customfieldtext FROM ".tname('customfields')." WHERE customfieldid='$itemarr[customfieldid]'");

			$querydata = $_SGLOBAL['db']->fetch_array($query);
			$customfieldname = $querydata['name'];
			$customfieldstruct = unserialize($querydata['customfieldtext']);
			unset($querydata);
			$len = count($customfieldstruct);
			$message_customfield .= "[quote][b]{$customfieldname}[/b]:\r\n";

			for($i = 0; $i < $len; $i++) {
				switch($customfieldstruct[$i]['type']) {
					case 'input':
					case 'textarea':
					case 'select':
						$message_customfield .= "[*][b]{$customfieldstruct[$i][name]}[/b] : {$customfielddata[$i]} \r\n";
						break;
					case 'checkbox':
						$message_customfield .= "[*][b]{$customfieldstruct[$i][name]}[/b] : ".join(',', $customfielddata[$i])."\r\n";
						break;
				}
			}
			unset($customfieldstruct, $customfieldname, $len);
			$message_customfield .= "[/quote]\r\n";
		}

		//处理附件
		$message_attachments = '';
		if($itemarr['haveattach']) {
			$message_attachments = $itemarr['type'] != 'file' ? "\r\n[b]$blang[blog_attach]:[/b]\r\n" : "[b]$blang[down_from_local]:[/b]  \r\n";
			$query = $_SGLOBAL['db']->query("SELECT aid, dateline, filename, subject, attachtype, isimage, size, filepath, thumbpath, downloads FROM ".tname('attachments')." WHERE hash='$itemarr[hash]'");
			while($attach = $_SGLOBAL['db']->fetch_array($query)) {
				if($attach['isimage']) {
					$attach['dateline'] = sgmdate($attach['dateline']);

					if($itemarr['message'] && !preg_match("/src=\"[^\"]*".preg_quote($attach[filepath], '/')."\"/is", $itemarr['message'])) {
						$message_attachments .= "[url=".A_URL."/$attach[filepath]][img]".A_URL."/{$attach[thumbpath]}[/img][/url]\r\n";
						$message_attachments .= "[b]{$attach[subject]}[/b]  [$blang[dateline]:$attach[dateline]]\r\n";
					}

				} else {
					$attach['dateline'] = sgmdate($attach['dateline']);
					$attach['filesize'] = formatsize($attach['filesize']);
					$attach['filetype'] = html2bbcode(attachtype(fileext($attach['attachment'])."\t".$attach['filetype']));
					$message_attachments .= "$attach[filetype] [url=".S_URL."/batch.download.php?aid=$attach[aid]][b]{$attach[filename]}[/b][/url]\r\n";
					$message_attachments .= "[$blang[dateline]:$attach[dateline] - $blang[down_counts]:$attach[downloads]]\r\n";
				}
			}
		}
		$itemarr['message'] .= $message_customfield.$message_attachments;
	} else {
		messagebox('error', 'itemid_not_exists');
	}

	if(!empty($itemarr['tid'])) {
		messagebox('error', 'resource_have_imported_into_forum');
	}

	if($itemarr['uid'] != $_SGLOBAL['supe_uid']) {
		messagebox('error', 'resource_is_not_of_you');
	}

	$query = $_SGLOBAL['db_bbs']->query("SELECT fup , type FROM ".tname('forums', 1)." WHERE fid='$fid'");
	$forum = $_SGLOBAL['db_bbs']->fetch_array($query);
	if(empty($forum)) {
		messagebox('error', 'forum_not_exists');
	}

	$_SGLOBAL['db_bbs']->query("INSERT INTO ".tname('threads', 1)." (fid, readperm, price, iconid, typeid, author, authorid, subject, dateline, lastpost, lastposter, displayorder, digest, blog, special, attachment, moderated, itemid)
		VALUES ('$fid', '0', '0', '0', '0', '$itemarr[username]', '$itemarr[uid]', '$itemarr[subject]', '$itemarr[dateline]', '$_SGLOBAL[timestamp]', '$itemarr[username]', '0', '0', '0', '0', '0', '0', '$itemid')");
	$tid = $_SGLOBAL['db_bbs']->insert_id();

	$_SGLOBAL['db_bbs']->query("INSERT INTO ".tname('posts', 1)." (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
		VALUES ('$fid', '$tid', '1', '$itemarr[username]', '$itemarr[uid]', '$itemarr[subject]', '$itemarr[dateline]', '$itemarr[message]', '$_SGLOBAL[onlineip]', '0', '1', '0', '0', '1', '0', '0')");
	$pid = $_SGLOBAL['db_bbs']->insert_id();

	updateposts('+', $_SGLOBAL['supe_uid']);

	$postuids = $lastreply = $reply = array();
	$replypost = 0;

	if($itemarr['replynum'] == 0) {

		$lastpost = "$tid\t$itemarr[subject]\t$_SGLOBAL[timestamp]\t$itemarr[username]";
		$_SGLOBAL['db_bbs']->query("UPDATE ".tname('forums', 1)." SET lastpost='$lastpost', threads=threads+1, posts=posts+1, todayposts=todayposts+1 WHERE fid='$fid'", 'UNBUFFERED');

		if($forum['type'] == 'sub') {
			$_SGLOBAL['db_bbs']->query("UPDATE ".tname('forums', 1)." SET lastpost='$lastpost' WHERE fid='$fourm[fup]'", 'UNBUFFERED');
		}
		unset($lastpost);

		$_SGLOBAL['db']->query("UPDATE ".tname('spaceitems')." SET tid='$tid' WHERE itemid='$itemid'", 'UNBUFFERED');
		messagebox('ok', 'imported_succeed',geturl('action/viewspace/itemid/'.$itemid));

	} else {
		$query = $_SGLOBAL['db']->query("SELECT cid, itemid, type, uid, authorid, author, ip, dateline, rates, message FROM ".tname('spacecomments')." WHERE itemid='$itemid' ORDER BY dateline ASC");
		while($reply = $_SGLOBAL['db']->fetch_array($query)) {
			$reply = saddslashes($reply);

			$_SGLOBAL['db_bbs']->query("INSERT INTO ".tname('posts', 1)." (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
				VALUES ('$fid', '$tid', '0', '$reply[author]', '$reply[authorid]', '', '$reply[dateline]', '$reply[message]', '$reply[ip]', '0', '', '0', '0', '0', '1', '0')");

			$postuids[] = $reply['uid'];

			$lastreply = $reply;
			$replypost++;
		}

		$_SGLOBAL['db_bbs']->query("UPDATE ".tname('threads', 1)." SET lastpost='$_SGLOBAL[timestamp]', replies=replies+$replypost WHERE fid='$fid' AND tid='$tid'", 'UNBUFFERED');

		updateposts('+', $postuids);

		unset($postuids, $reply);

		$lastpost = "$tid\t$subject\t$timestamp\t$lastreply[author]";
		$_SGLOBAL['db_bbs']->query("UPDATE ".tname('forums', 1)." SET lastpost='$lastpost', threads=threads+1, posts=posts+$replypost, todayposts=todayposts+$replypost WHERE fid='$fid'", 'UNBUFFERED');
		unset($lastreply, $replypost);

		if($forum['type'] == 'sub') {
			$_SGLOBAL['db_bbs']->query("UPDATE ".tname('forums', 1)." SET lastpost='$lastpost' WHERE fid='$forum[fup]'", 'UNBUFFERED');
		}

		$_SGLOBAL['db']->query("DELETE FROM ".tname('spacecomments')." WHERE itemid='$itemid'", 'UNBUFFERED');
		$_SGLOBAL['db']->query("UPDATE ".tname('spaceitems')." SET tid='$tid' WHERE itemid='$itemid'", 'UNBUFFERED');
		messagebox('ok', 'imported_succeed', geturl('action/viewspace/itemid/'.$itemid));
	}
} elseif(submitcheck('submitcomment')) {
	include_once(S_ROOT.'./include/common.inc.php');
	getcookie(1);
	if(empty($_SGLOBAL['supe_uid'])) {
		messagebox('error', 'no_login', geturl('action/login'));
	}

	if(!submitcheck('submitcomment', 1)) {
		messagebox('error', 'seccode_error');
	}

	$tid = intval($_POST['tid']);
	$query = $_SGLOBAL['db_bbs']->query("SELECT fid, replies FROM ".tname('threads', 1)." WHERE tid='$tid'");
	$thread = $_SGLOBAL['db_bbs']->fetch_array($query);
	if(empty($thread)) {
		messagebox('error', 'thread_not_exists');
	}


	$subject = empty($_POST['subject']) ? '' : addslashes(shtmlspecialchars($_POST['subject']));
	if(empty($_POST['message'])) {
		messagebox('error', 'message_length_error');
	} else {
		$message = cutstr(addslashes(shtmlspecialchars($_POST['message'])), '200');
	}

	$_SGLOBAL['db_bbs']->query("INSERT INTO ".tname('posts', 1)." (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, anonymous, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
			VALUES ('$thread[fid]', '$tid', '0', '$_SGLOBAL[supe_username]', '$_SGLOBAL[supe_uid]', '$subject', '$_SGLOBAL[timestamp]', '$message', '$_SGLOBAL[onlineip]', '0', '0', '0', '0', '0', '0', '0', '0')");
	$pid = $_SGLOBAL['db_bbs']->insert_id();

	$_SGLOBAL['db_bbs']->query("REPLACE INTO ".tname('myposts', 1)." (uid, tid, pid, position, dateline, special) VALUES ('$_SGLOBAL[supe_uid]', '$tid', '$pid', '".($thread['replies'] + 1)."', '$_SGLOBAL[timestamp]', '0')", 'UNBUFFERED');

	$_SGLOBAL['db_bbs']->query("UPDATE ".tname('threads', 1)." SET lastposter='$_SGLOBAL[supe_username]', lastpost='$_SGLOBAL[timestamp]', replies=replies+1  WHERE tid='$tid'", 'UNBUFFERED');

	updateposts('+', $_SGLOBAL['supe_uid']);

	$lastpost = "$tid\t".addslashes($subject)."\t$_SGLOBAL[timestamp]\t$_SGLOBAL[supe_username]";

	$_SGLOBAL['db_bbs']->query("UPDATE ".tname('forums', 1)." SET lastpost='$lastpost', posts=posts+1, todayposts=todayposts+1 WHERE fid='$thread[fid]'", 'UNBUFFERED');

	messagebox('ok', 'comment_succeed', geturl('action/viewspace/itemid/'.$itemid));
}

function attachtype($type, $returnval = 'html') {

	static $attachicons = array(
			1 => 'common.gif',
			2 => 'binary.gif',
			3 => 'zip.gif',
			4 => 'rar.gif',
			5 => 'msoffice.gif',
			6 => 'text.gif',
			7 => 'html.gif',
			8 => 'real.gif',
			9 => 'av.gif',
			10 => 'flash.gif',
			11 => 'image.gif',
			12 => 'pdf.gif',
			13 => 'torrent.gif'
		);

	if(is_numeric($type)) {
		$typeid = $type;
	} else {
		if(preg_match("/bittorrent|^torrent\t/", $type)) {
			$typeid = 13;
		} elseif(preg_match("/pdf|^pdf\t/", $type)) {
			$typeid = 12;
		} elseif(preg_match("/image|^(jpg|gif|png|bmp)\t/", $type)) {
			$typeid = 11;
		} elseif(preg_match("/flash|^(swf|fla|swi)\t/", $type)) {
			$typeid = 10;
		} elseif(preg_match("/audio|video|^(wav|mid|mp3|m3u|wma|asf|asx|vqf|mpg|mpeg|avi|wmv)\t/", $type)) {
			$typeid = 9;
		} elseif(preg_match("/real|^(ra|rm|rv)\t/", $type)) {
			$typeid = 8;
		} elseif(preg_match("/htm|^(php|js|pl|cgi|asp)\t/", $type)) {
			$typeid = 7;
		} elseif(preg_match("/text|^(txt|rtf|wri|chm)\t/", $type)) {
			$typeid = 6;
		} elseif(preg_match("/word|powerpoint|^(doc|ppt)\t/", $type)) {
			$typeid = 5;
		} elseif(preg_match("/^rar\t/", $type)) {
			$typeid = 4;
		} elseif(preg_match("/compressed|^(zip|arj|arc|cab|lzh|lha|tar|gz)\t/", $type)) {
			$typeid = 3;
		} elseif(preg_match("/octet-stream|^(exe|com|bat|dll)\t/", $type)) {
			$typeid = 2;
		} elseif($type) {
			$typeid = 1;
		} else {
			$typeid = 0;
		}
	}
	if($returnval == 'html') {
		return '<img src="'.B_URL.'/images/attachicons/'.$attachicons[$typeid].'" border="0" class="absmiddle" alt="" />';
	} elseif($returnval == 'id') {
		return $typeid;
	}
}

function updateposts($operator, $uidarray) {
	global $_SGLOBAL;

	$membersarray = $postsarray = array();
	foreach((is_array($uidarray) ? $uidarray : array($uidarray)) as $id) {
		$membersarray[intval(trim($id))]++;
	}
	foreach($membersarray as $uid => $posts) {
		$postsarray[$posts][] = $uid;
	}
	$lastpostadd = $uidarray == $_SGLOBAL['supe_uid'] ? ", lastpost='$_SGLOBAL[timestamp]'" : '';

	foreach($postsarray as $posts => $uidarray) {
		$uids = implode(',', $uidarray);
		$_SGLOBAL['db_bbs']->query("UPDATE ".tname('members', 1)." SET posts=posts+('$operator$posts') $lastpostadd WHERE uid IN ($uids)", 'UNBUFFERED');
	}
}

function getbbsforum($space='|----') {
	global $_SGLOBAL;
	
	$forumarr = array();
	include_once(S_ROOT.'./class/tree.class.php');
	$tree = new Tree('blogpost');
	$minfup = '';
	if(!empty($_SGLOBAL['bbsforumarr']) && is_array($_SGLOBAL['bbsforumarr'])){
		foreach($_SGLOBAL['bbsforumarr'] as $forum) {
			if($minfup == '') $minfup = $forum['fup'];
			$tree->setNode($forum['fid'], $forum['fup'], $forum);
		}
	}

	//根目录
	$listarr = array();
	$categoryarr = $tree->getChilds();
	foreach ($categoryarr as $key => $catid) {
		$cat = $tree->getValue($catid);
		$cat['pre'] = $tree->getLayer($catid, $space);
		$listarr[$cat['fid']] = $cat;
	}
	return $listarr;
}

?>