<?php
/**
 * @version $Id: postedit.inc.php v2.0 $
 * @package PBDigg
 * @copyright Copyright (C) 2007 - 2008 PBDigg.com. All Rights Reserved.
 * @license PBDigg is free software and use is subject to license terms
 */

!defined('IN_PBDIGG') && exit ('Access Denied!');

$post = $DB->db_fetch_one_array("SELECT t.tid, t.cid, t.author, t.uid, t.subject title, t.content, t.contentlink source, t.topicimg, t.ifcheck, ti.skeywords, ti.sdesc, ti.ainfo, ti.anonsite, ti.anonymity, ti.titlecolor, ti.titlestyle FROM {$db_prefix}threads t LEFT JOIN {$db_prefix}tinfo ti ON t.tid = ti.tid WHERE t.tid = $tid");

if (!$post || !$customer['uid'] || (($post['uid'] != $customer['uid']) && (!$pbadmin || !$alloweditatc)) || (!$post['ifcheck'] && !$allowshield))
{
	showMsg($u_message['post_edit_error']);
}
if ($submitted)
{
	if ($pb_gdcheck['post'] && (!$captcha || !ckgdcode($captcha)))
	{
		showMsg($u_message['checkcode_error']);
	}
	$fsession = $DB->db_fetch_one_array("SELECT * FROM {$db_prefix}fsession WHERE fsid = '".$_POST['fsid']."' AND uid = ".$customer['uid']);
	!$fsession && showMsg('请从正确的途径递交数据');
	$fsession['attachment'] && $fsession['attachment'] = unserialize($fsession['attachment']);
	$updatesql = $updateinfosql = $linkhost = $seokeywords = '';
	$ainfo = array();
	addS($post);
	$title = HConvert(trim($_POST['title']));
	if ($post['title'] != $title && !checkTitle($title))
	{
		$updatesql .= " subject = '".$title."',";
	}
	$content = trim($_POST['content']);
	if ($ck = checkContent($content))
	{
		showMsg($ck);
	}
	$source = trim($_POST['source']);
	if (!$source || ($post['source'] != $source && !checkURL($source)))
	{
		$updatesql .= " contentlink = '".$source."',";
		preg_match('#^(https?|ftp|gopher|news|telnet|mms|rtsp):\/\/([^\/]*)#i', $source, $linkhost);
		$updatesql .= " linkhost = '".(string)$linkhost[2]."',";
	}

	if ($allowhtml)
	{
		$content = ($customer['adminid'] == '1') ? $content : safeConvert($content);
	}
	else
	{
		require_once PBDIGG_ROOT.'include/safehtml.php';
		$safehtml = & new HTML_Safe();
		$content = addslashes($safehtml->parse(stripslashes($content)));
	}
	$ishtml = $convert = 1;

	$summary = trim($_POST['summary']);
	$seodesc = trim(HConvert(PBSubstr(preg_replace(array("~\x20+?(?!\w)~m","~<\/?[^\>]*>~im","~\[\/?[^\]]*\]~im","~(\r\n|\n\r|\r|\n){1,}~im"), array('','','',"\n"), ($summary ? $summary : $content)), 380, FALSE)));

	if ($post['sdesc'] != $seodesc)
	{
		$updateinfosql .= " sdesc = '".$seodesc."',";
	}
	if ($post['anonymity'])
	{
		$anonname = trim($_POST['anonname']);
		if ($post['author'] != $anonname && !checkAnonName($anonname))
		{
			$updatesql .= " author = '".HConvert($anonname)."',";
		}
		$anonsite = trim($_POST['anonsite']);
		if ($post['anonsite'] != $anonsite)
		{
			$updateinfosql .= " anonsite = '".(($anonsite == 'http://') ? '' : HConvert($_POST['anonsite']))."',";
		}
	}
	if ($post['cid'] != $cid)
	{
		if (!array_key_exists($cid, $categories)) showMsg('请选择一个合适的分类');
		$newcids = $oldcids = '';
		require(PBDIGG_ROOT.'data/cache/cache_singlecate_'.$cid.'.php');
		$newcids = $singlecate['parcids'].$cid;
		unset($singlecate);
		require(PBDIGG_ROOT.'data/cache/cache_singlecate_'.(int)$post['cid'].'.php');
		$oldcids = $singlecate['parcids'].$post['cid'];
		$DB->db_query("UPDATE {$db_prefix}categories SET tnum = tnum + 1 WHERE cid IN (".$newcids.")");
		$DB->db_query("UPDATE {$db_prefix}categories SET tnum = tnum - 1 WHERE cid IN (".$oldcids.")");
		$updatesql .= " cid = ".$cid.",";
	}
	$tag = str_replace("\xa3\xac", ',', HConvert(trim($_POST['tag'])));
	if ($post['keywords'] != $tag && !checkTag($tag))
	{
		$tag = array_filter(array_unique(explode(',', $tag)));
		$oldtag = array();
		$SQL = "SELECT tg.tagname 
				FROM {$db_prefix}tags tg, {$db_prefix}tagcache tc 
				WHERE tg.tagid = tc.tagid 
				AND tc.tid = $tid";
		$DB->db_query($SQL);
		while ($rs = $DB->db_fetch_array())
		{
			$oldtag[] = $rs['tagname'];
		}
		if ($tag != $oldtag)
		{
			$deltags = $addtags = $rs = $t_tags = array();
			$tagid = $tagname = '';
			$deltags = array_diff($oldtag, $tag);
			$addtags = array_diff($tag, $oldtag);
			if ($deltags)
			{
				foreach ($deltags as $value)
				{
					$tagname .= "'".$value."',";
				}
				$DB->db_query("SELECT tagid FROM {$db_prefix}tags WHERE tagname IN (".substr($tagname, 0, -1).")");
				while ($rs = $DB->db_fetch_array())
				{
					$tagid .= $rs['tagid'].',';
				}
				$tagid = substr($tagid, 0, -1);
				$DB->db_query("DELETE FROM {$db_prefix}tagcache WHERE tagid IN ($tagid) AND tid = $tid");
				$DB->db_query("UPDATE {$db_prefix}tags SET usenum = usenum - 1 WHERE tagid IN ($tagid)");
			}
			$t_tags = array_diff($oldtag, $deltags);
			$tagid = '';
			foreach ($addtags as $key => $value)
			{
				$rs = $DB->db_fetch_one_array("SELECT tagid, usenum, ifopen FROM {$db_prefix}tags WHERE tagname = '$value'");
				if ($DB->db_num() > 0)
				{
					if ($rs['ifopen'])
					{
						$DB->db_query("UPDATE {$db_prefix}tags SET usenum = usenum + 1 WHERE tagid = ".$rs['tagid']);
						$tagid = $rs['tagid'];
					}
					else
					{
						unset($addtags[$key]);
						continue;
					}
				}
				else
				{
					$DB->db_query("INSERT INTO {$db_prefix}tags (tagname, usenum, ifopen) VALUES ('$value', 1, 1)");
					$tagid = $DB->db_insertID();
				}
				$DB->db_query("INSERT INTO {$db_prefix}tagcache (tagid, tid) VALUES ($tagid, $tid)");
			}
			$updatesql .= " keywords = '".HConvert(addslashes(implode(',', array_merge($t_tags, $addtags))))."',";
		}
	}
	require_once(PBDIGG_ROOT.'include/autotag.inc.php');
	$seokeywords = HConvert(autotags($title, $content));
	if ($tag)
	{
		foreach ($tag as $t)
		{
			if (strpos($seokeywords, $t) === FALSE)
			{
				$seokeywords .= ','.$t;
			}
		}
	}
	if ($post['skeywords'] != $seokeywords)
	{
		$updateinfosql .= " skeywords = '".addslashes($seokeywords)."',";
	}
	$ifcheck = (($pb_tcheck && !$customer['adminid']) || ($pb_anonnews && !$customer['uid'])) ? '0' : '1';
	$uploaddir = getUploadDir($cid);
	if ($pb_urlsaveimg && preg_match('/(https?|ftp):\/\/([^\[\<\r\n]+?)\.(gif|jpg|jpeg|bmp|png)/i', $content))
	{
		require_once(PBDIGG_ROOT.'include/remotefile.func.php');
		$content = get_remote_files($content, $uploaddir);
	}
	if ($allowaupload && $pb_allowupload)
	{
		if($pb_watertype && !isset($WM))
		{
			require_once(PBDIGG_ROOT.'include/Watermark.class.php');
			$WM = new Watermark();
		}
		$filepath = PBDIGG_ROOT.'attachments/'.$uploaddir.'/';
		$untopicming = TRUE;
		if ($pb_uploadtopicimg && isset($_FILES['topicimg']))
		{
			$topicimg = '';
			$attasize = ($pb_uploadmaxsize > $uploadmax) ? $uploadmax : $pb_uploadmaxsize;
			require_once(PBDIGG_ROOT.'include/Upload.class.php');
			$Upload = new Upload();
			$files = & $Upload->getFiles();
			foreach ($files as $file)
			{
				if ($ck = $file->checkFile(array('gif','jpg','jpeg','bmp','png'), $attasize))
				{
					showMsg($ck);
				}
				elseif ($file->_name == 'topicimg')
				{
					$file->moveFile($filepath);
					$topicimg = $uploaddir.'/tpic_'.$file->getRealName().'.'.$file->getExtName();
					if ($pb_allowthumb)
					{
						$topicimginfo = thumb($file->getRealPath(), 'tpic_');
						$file->delRealFile();
						$topicimgh = $topicimginfo[1];
						$topicimgw = $topicimginfo[2];
					}
					else
					{
						$topicimginfo = @getimagesize($file->getRealPath());
						$topicimgh = floor($topicimginfo[1]);
						$topicimgw = floor($topicimginfo[0]);
						@rename($file->getRealPath(), PBDIGG_ROOT.'attachments/'.$topicimg);
					}
					$topicimg .= '|'.$topicimgh.'|'.$topicimgw;
					
					$untopicming = FALSE;
				}
			}
			$post['topicimg'] && (strpos($post['topicimg'], '..')===FALSE) && PDel(PBDIGG_ROOT.'attachments/'.$post['topicimg']);
			$updatesql .= " topicimg = '".$topicimg."',";
		}
		if ($fsession['attachment'])
		{
			$attanum = 0;
			$attachment_pattern = $attachment_replace = $ainfo = array();
			foreach ($fsession['attachment'] as $k => $fa)
			{
				rename(PBDIGG_ROOT.'attachments/temp/'.$fa[3], $filepath.$fa[3]);
				if ($fa[4])
				{
					if ($untopicming && isset($_FILES['topicimg']))
					{
						$topicimginfo = @getimagesize($filepath.$fa[3]);
						$topicimgh = floor($topicimginfo[1]);
						$topicimgw = floor($topicimginfo[0]);
						copy($filepath.$fa[3], $filepath.'tpic_'.$fa[3]);
						$topicimg = $uploaddir.'/tpic_'.$fa[3].'|'.$topicimgh.'|'.$topicimgw;
						$untopicming = FALSE;
					}
					if ($pb_watertype)
					{
						$WM->setImg($filepath.$fa[3]);
					}
				}
				$DB->db_query("INSERT INTO {$db_prefix}attachments (cid,tid,uid,filename,filetype,filesize,filepath,isimg,uploaddate) VALUES (".$fsession['cid'].",".$post['tid'].",".$fsession['uid'].",'".$fa[0]."','".$fa[1]."',".$fa[2].",'".$uploaddir.'/'.$fa[3]."',".$fa[4].",$timestamp)", 0);
				$aid = $DB->db_insertID();
				$attachment_pattern[] = '[file='.$k.']';
				$attachment_replace[] = '[attachment='.$aid.']';
				$ainfo[$aid] = array('aid'=>$aid,'filename'=>addslashes($fa[0]),'filesize'=>$fa[2],'filepath'=>$uploaddir.'/'.$fa[3],'filetype'=>$fa[1],'isimg'=>$fa[4],);
				++$attanum;
			}
			$DB->db_query("UPDATE {$db_prefix}memberdata SET uploadnum = uploadnum + ".$attanum." WHERE uid = '".$customer['uid']."'");
			if ($ainfo)
			{
				$post['ainfo'] = unserialize(stripslashes($post['ainfo']));
				is_array($post['ainfo']) && $ainfo += $post['ainfo'];
				$updateinfosql .= " ainfo = '".addslashes(serialize($ainfo))."',";
				$content = str_replace($attachment_pattern, $attachment_replace, $content);
			}
		}
	}
	if ($pb_titleubb)
	{
		$tu_tmp = explode("\t", $pb_titleubb);
		$titlestyle .= (isset($title_b) && in_array('b', $tu_tmp)) ? '1' : '0';
		$titlestyle .= (isset($title_i) && in_array('i', $tu_tmp)) ? '1' : '0';
		$titlestyle .= (isset($title_u) && in_array('u', $tu_tmp)) ? '1' : '0';
		$updateinfosql .= " titlestyle = '".$titlestyle."',";
		if (in_array('color', $tu_tmp) && preg_match('/^[0-9a-f]{6}$/i', $title_color))
		{
			$updateinfosql .= " titlecolor = '".addslashes($title_color)."',";
		}
	}
	if ($content != $post['content'])
	{
		$updatesql .= " content = '".$content."',";
	}
	$DB->db_query("UPDATE {$db_prefix}threads SET ".$updatesql." ifcheck = $ifcheck WHERE tid = $tid");
	$DB->db_query("UPDATE {$db_prefix}tinfo SET ".$updateinfosql." ishtml = ".(int)$ishtml.", ifconvert = ".(int)$convert." WHERE tid = $tid");

	if ($ifcheck)
	{
		$msg = $u_message['post_success'];
		$jurl = 'show.php?tid='.$tid;
	}
	else
	{
		$msg = $u_message['post_ready_check'];
		$jurl = $_PBENV['PB_URL'];
	}
	sCookie('pb_lastpost', $timestamp);
	$Cache->tags();
	$Cache->mktran();
	redirect($msg, $jurl);
}
else
{
	$tags = $attachments = $cateoption = $showtopicimg = $topicimg = $swfext = $exts = '';
	$fsid = md5($timestamp.$customer['uid'].$_PBDEV['PB_IP'].random(8));
	$DB->db_query("INSERT INTO {$db_prefix}fsession (fsid,attachment,uid,ip,exptime) VALUES ('".$fsid."','',".$customer['uid'].",'".$_PBDEV['PB_IP']."',".($timestamp+3600).")");
	$SQL = "SELECT tg.tagname
			FROM {$db_prefix}tags tg INNER JOIN {$db_prefix}tagcache tc 
			ON tg.tagid = tc.tagid 
			WHERE tc.tid = $tid";
	$DB->db_query($SQL);
	while ($rs = $DB->db_fetch_array())
	{
		$tags .= $rs['tagname'].',';
	}
	$post['tag'] = substr($tags, 0, -1);
	if ($post['ainfo'])
	{
		$post['ainfo'] = unserialize($post['ainfo']);
		foreach ($post['ainfo'] as $k => $v)
		{
			$attachments .= '<div class="attachment_show" id="e_attachment_'.$k.'"><img src="'.$_PBENV['PB_URL'].($v['isimg'] ? 'attachments/'.$v['filepath'] : 'images/icon.gif').'" /><ul><li>'.$v['filename'].'</li><li><a onclick="insertatt(\'[attachment='.$k.']\')" href="javascript:void(0);">插入</a> | <a onclick="supdelatt('.$k.')" href="javascript:void(0);">删除</a></li></ul></div>';
		}
	}
	$TPL->assign('attachments', $attachments);

	cate_Option($categories, $cateoption, 0, $post['cid']);
	$cateoption = '<select name="cid">'.$cateoption.'</select>';
	$TPL->assign('cateoption', $cateoption);

	$post['topicimg'] && $showtopicimg = '1';
	list($topicimg,,) = explode('|', $post['topicimg']);
	if (substr($topicimg, 0, 7) != 'http://')
	{
		$topicimg = 'attachments/'.$topicimg;
	}
	$TPL->assign('topicimg', $topicimg);
	$TPL->assign('showtopicimg', $showtopicimg);
	$TPL->assign('uploadtopicimg', $allowaupload && $pb_allowupload && $pb_uploadtopicimg);
	
	if ($post['anonymity'] && $pbadmin)
	{
		$TPL->assign('modanonnews', '1');
	}
	if ($pb_titleubb)
	{
		$tu_tmp = explode("\t", $pb_titleubb);
		if (in_array('b', $tu_tmp))
		{
			$TPL->assign('title_b', '1');
			$post['titlestyle']{0} && $TPL->assign('check_b', ' checked="checked"');
		}
		if (in_array('i', $tu_tmp))
		{
			$TPL->assign('title_i', '1');
			$post['titlestyle']{1} && $TPL->assign('check_i', ' checked="checked"');
		}
		if (in_array('u', $tu_tmp))
		{
			$TPL->assign('title_u', '1');
			$post['titlestyle']{2} && $TPL->assign('check_u', ' checked="checked"');
		}
		if (in_array('color', $tu_tmp))
		{
			$TPL->assign('title_color', '1');
			if ($post['titlecolor'])
			{
				if (strpos($OPTIONS['title_color'], $post['titlecolor']) !== FALSE)
				{
					$color_list = str_replace('value="'.$post['titlecolor'].'"', 'value="'.$post['titlecolor'].'" selected="selected"', $OPTIONS['title_color']);
				}
				else
				{
					$color_list = '<option value="'.$post['titlecolor'].'" style="background:#'.$post['titlecolor'].';color:#'.$post['titlecolor'].'">#'.$post['titlecolor'].'</option>'.$OPTIONS['title_color'];
				}
				$TPL->assign('color_list', $color_list);
			}
			else
			{
				$TPL->assign('color_list', $OPTIONS['title_color']);
			}
		}
		$TPL->assign('title_ubb', '1');
	}

	if ($pb_uploadfiletype && $uploadtype)
	{
		$exts = explode(',', $uploadtype);
		foreach ($exts as $key => $ext)
		{
			if (strpos($pb_uploadfiletype, $ext) === FALSE)
			{
				unset($exts[$key]);
			}
			else
			{
				$swfext .= '*.'.$ext.';';
			}
		}
		$exts = implode(',', $exts);
	}
	$Cache->loadCache('systags');
	$TPL->assign('systags', $Cache->getCacheContent());
	$seo['pagetitle'] = $seo['keywords'] = $seo['description'] = '编辑主题';
	$TPL->assign('seo', $seo);
	$TPL->assign('content', gEditor($post['content']));
	$allowuploadsize = ceil((($pb_uploadmaxsize > $uploadmax) ? $uploadmax : $pb_uploadmaxsize) / 1024);
	$TPL->assign('attanum', $pb_attachnum);
	$TPL->assign('allowuploadsize', $allowuploadsize);
	$TPL->assign('swfext', $swfext);
	$TPL->assign('fsid', $fsid);
	$TPL->assign('actionurl', 'post.php?action=edit&tid='.$tid);
	$TPL->assign('attaupload', sprintf('每次最多上传 %s 个附件<br />单个附件尺寸不能大于 %s KB<br />允许的后缀名：%s', $pb_attachnum, $allowuploadsize, $exts));
	list($title_min, $title_max) = explode("\t", $pb_titlelen);
	list($content_min, $content_max) = explode("\t", $pb_contentlen);
	$TPL->assign('title_min', $title_min);
	$TPL->assign('title_max', $title_max);
	$TPL->assign('title_tip', sprintf($u_message['thread_title_limit'], $title_min, $title_max));
	$TPL->assign('content_min', $content_min);
	$TPL->assign('content_max', $content_max);
	$TPL->assign('content_tip', sprintf($u_message['thread_content_limit'], $content_min, $content_max));
	$TPL->assign('showupload', $allowaupload && $pb_allowupload);
	$TPL->assign('post', $post);
	PBOutPut('edit_post.html');
}

?>