<?php
/**
 * @version $Id: postnew.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!');

if ($submitted)
{
	$fession = $singlecate = $linkhost = $username = $ishtml = $titlestyle = $titlecolor = $convert = $attatid = $tagid = $attanum = $ainfo = '';
	$attachment_pattern = $attachment_replace = array();
	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']);
	$title = trim($_POST['title']);
	$summary = trim($_POST['summary']);
	$content = trim($_POST['content']);
	$anonname = HConvert(trim($_POST['anonname']));
	if ($anonname && ($ck = checkAnonName($anonname))) showMsg($ck);
	$anonsite = ($anonsite == 'http://') ? '' : HConvert($_POST['anonsite']);
	$username = $anonname ? $anonname : $customer['username'];
	$tag = trim($_POST['tag']);

	if ($ck = checkTitle($title))
	{
		showMsg($ck);
	}
	if ($ck = checkContent($content))
	{
		showMsg($ck);
	}
	if ($tag && $ck = checkTag($tag))
	{
		showMsg($ck);
	}
	$tag = array_filter(array_unique(explode(',', str_replace("\xa3\xac", ',', HConvert($tag)))));
	$seokeywords = $seodesc = '';
	include_once(PBDIGG_ROOT.'include/autotag.inc.php');
	$seokeywords = HConvert(autotags($title, $content));
	foreach ($tag as $t)
	{
		if (strpos($seokeywords, $t) === FALSE)
		{
			$seokeywords .= ','.$t;
		}
	}
	$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)));
	$title = HConvert($title);
	
	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;

	if (!@include(PBDIGG_ROOT.'data/cache/cache_singlecate_'.(int)$fsession['cid'].'.php'))
	{
		showMsg($u_message['post_cate_noexist']);
	}
	$cids = $singlecate['parcids'].$fsession['cid'];
	if ($fsession['source'])
	{
		preg_match('#^(https?|ftp|gopher|news|telnet|mms|rtsp):\/\/([^\/]*)#i', $fsession['source'], $linkhost);
		$linkhost = addslashes(HConvert($linkhost[2]));
	}
	$ifcheck = (($pb_tcheck && !$customer['adminid']) || ($pb_anonnews && !$customer['uid'])) ? '0' : '1';
	$uploaddir = getUploadDir($fsession['cid']);
	if ($pb_urlsaveimg && preg_match('/(https?|ftp):\/\/([^\[\<\r\n]+?)\.(gif|jpg|jpeg|bmp|png)/im', $content))
	{
		require_once(PBDIGG_ROOT.'include/remotefile.func.php');
		$content = get_remote_files($content, $uploaddir);
	}
	$topicimg = $topicimgh = $topicimgw = '';
	$untopicming = TRUE;
	if ($allowaupload && $pb_allowupload)
	{
		$filepath = PBDIGG_ROOT.'attachments/'.$uploaddir.'/';
		if($pb_watertype && !isset($WM))
		{
			require_once(PBDIGG_ROOT.'include/Watermark.class.php');
			$WM = new Watermark();
		}
		if ($pb_uploadtopicimg)
		{
			$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')
				{
					//upload 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;
				}
			}
		}
		if ($fsession['attachment'])
		{
			foreach ($fsession['attachment'] as $k => $fa)
			{
				rename(PBDIGG_ROOT.'attachments/temp/'.$fa[3], $filepath.$fa[3]);
				if ($fa[4])
				{
					if ($untopicming)
					{
						$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,uid,filename,filetype,filesize,filepath,isimg,uploaddate) VALUES (".$fsession['cid'].",".$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.']';
				$attatid .= $aid.',';
				$ainfo[$aid] = array('aid'=>$aid,'filename'=>addslashes($fa[0]),'filesize'=>$fa[2],'filepath'=>$uploaddir.'/'.$fa[3],'filetype'=>$fa[1],'isimg'=>$fa[4],);
				++$attanum;
			}
		}
	}
	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';
		if (in_array('color', $tu_tmp) && preg_match('/^[0-9a-f]{6}$/i', $title_color))
		{
			$titlecolor = $title_color;
		}
	}
	$DB->db_query("INSERT INTO {$db_prefix}threads (cid,author,uid,subject,content,contentlink,linkhost,topicimg,ifcheck,postdate,postip,diggdate) VALUES (".$fsession['cid'].",'$username','".$customer['uid']."','$title','','".$fsession['source']."','$linkhost','$topicimg',$ifcheck,$timestamp,'".$_PBDEV['PB_IP']."',$timestamp)");
	$tid = $DB->db_insertID();
	$ainfo && $ainfo = addslashes(serialize($ainfo));

	$DB->db_query("INSERT INTO {$db_prefix}tinfo (tid,skeywords,sdesc,ishtml,titlecolor,titlestyle,ainfo,ifconvert,anonsite,anonymity) VALUES ($tid,'$seokeywords','$seodesc',".(int)$ishtml.",'$titlecolor','$titlestyle','$ainfo',".(int)$convert.",'$anonsite',".(intval($log_status)^1).")");
	//attachments
	if ($attatid)
	{
		$content = str_replace($attachment_pattern, $attachment_replace, $content);
		$DB->db_query("UPDATE {$db_prefix}attachments SET tid = $tid WHERE aid IN (".substr($attatid, 0, -1).")", 0);
	}
	$DB->db_query("DELETE FROM {$db_prefix}fsession WHERE (fsid = '".$fsession['fsid']."' AND uid = ".$customer['uid'].") OR exptime <= $timestamp", 0);

	//tags
	foreach ($tag 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($tag[$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)");
	}

	$DB->db_query("UPDATE {$db_prefix}threads SET content = '$content', keywords = '".implode(',', $tag)."' WHERE tid = ".$tid, 0);
	$DB->db_query("UPDATE {$db_prefix}categories SET tnum = tnum + 1 WHERE cid IN (".$cids.")");
	$pb_creditdb = explode("\t", $pb_creditdb);
	$DB->db_query("UPDATE {$db_prefix}memberdata SET uploadnum = uploadnum + ".(int)$attanum.", postnum = postnum + 1, currency = currency + ".$pb_creditdb[0].", lastpost = '$timestamp' WHERE uid = ".$customer['uid'], 0);
	$DB->db_query("UPDATE {$db_prefix}sitestat SET artnum = artnum + 1 WHERE id = 1", 0);
	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);
}

if (!$step)
{
	$TPL->assign('cid', $cid);
}
elseif ($step == '2')
{
	$exts = $swfext = $titleubb = '';
	$source = trim($_POST['source']);
	$cid = intval($_POST['cid']);
	if (!$cid || !array_key_exists($cid, $categories)) showMsg('请选择一个合适的分类');
	if (!$categories[$cid]['status'] && !$pbadmin) showMsg('你无权在关闭的分类中发布信息');
	$source && ($ck = checkURL($source)) && showMsg($ck);
	$fsid = md5($timestamp.$customer['uid'].$_PBDEV['PB_IP'].random(8));
	$DB->db_query("INSERT INTO {$db_prefix}fsession (fsid,attachment,cid,source,uid,ip,exptime) VALUES ('".$fsid."','',".$cid.",'".$source."',".$customer['uid'].",'".$_PBDEV['PB_IP']."',".($timestamp+3600).")");
	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);
	}
	if ($pb_titleubb)
	{
		$tu_tmp = explode("\t", $pb_titleubb);
		if (in_array('b', $tu_tmp))
		{
			$TPL->assign('title_b', '1');
		}
		if (in_array('i', $tu_tmp))
		{
			$TPL->assign('title_i', '1');
		}
		if (in_array('u', $tu_tmp))
		{
			$TPL->assign('title_u', '1');
		}
		if (in_array('color', $tu_tmp))
		{
			$TPL->assign('title_color', '1');
		}
		$TPL->assign('title_ubb', '1');
	}
	$Cache->loadCache('systags');
	$TPL->assign('systags', $Cache->getCacheContent());
	$seo['pagetitle'] = $seo['keywords'] = $seo['description'] = $u_message['post'];
	$TPL->assign('seo', $seo);
	$TPL->assign('content', gEditor());
	$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');
	$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('uploadtopicimg', $allowaupload && $pb_allowupload && $pb_uploadtopicimg);
	$TPL->assign('showupload', $allowaupload && $pb_allowupload);
	$TPL->assign('postanonnews', ($customer['uid'] ? '0' : '1'));
	$TPL->assign('color_list', $OPTIONS['title_color']);
	$TPL->assign('step', '2');
}

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

PBOutPut('post.html');
?>