<?php

/*
	[Discuz!] (C)2001-2006 Comsenz Inc.
	This is NOT a freeware, use is subject to license terms

	$RCSfile: newthread.inc.php,v $
	$Revision: 1.74.2.2 $
	$Date: 2006/09/14 01:59:57 $
*/

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

$discuz_action = 11;

if(empty($forum['fid']) || $forum['type'] == 'group') {
	showmessage('forum_nonexistence');
}

if(!$discuz_uid && !((!$forum['postperm'] && $allowpost) || ($forum['postperm'] && forumperm($forum['postperm'])))) {
	showmessage('group_nopermission', NULL, 'NOPERM');
} elseif(empty($forum['allowpost'])) {
	if(!$forum['postperm'] && !$allowpost) {
		showmessage('group_nopermission', NULL, 'NOPERM');
	} elseif($forum['postperm'] && !forumperm($forum['postperm'])) {
		showmessage('post_forum_newthread_nopermission', NULL, 'HALTED');
	}
}

$isblog = empty($isblog) ? '' : 'yes';
if($isblog && (!$allowuseblog || !$forum['allowshare'])) {
	showmessage('post_newthread_blog_invalid', NULL, 'HALT');
}

checklowerlimit($postcredits);


if(isset($poll)) {
	$special = 1;
} elseif(isset($trade)) {
	$special = 2;
} elseif(isset($reward)) {
	$special = 3;
} elseif(isset($activity)) {
	$special = 4;
} else {
	$special = 0;
}

if(!submitcheck('topicsubmit', 0, $seccodecheck)) {

	$typeselect = typeselect($typeid);

	$icons = '';
	if(is_array($_DCACHE['icons'])) {
		$key = 1;
		foreach($_DCACHE['icons'] as $id => $icon) {
			$icons .= ' <input class="radio" type="radio" name="iconid" value="'.$id.'"><img src="'.SMDIR.'/'.$icon.'" alt="" />';
			$icons .= !(++$key % 10) ? '<br>' : '';
		}
	}

	if($special == 2 && $allowposttrade) {
		$expiration_7 = date('Y-m-d', $timestamp + 86400 * 7);
		$expiration_14 = date('Y-m-d', $timestamp + 86400 * 14);
		$expiration_month = date('Y-m-d', mktime(0, 0, 0, date('m')+1, date('d'), date('Y')));
	}

	include template('post_newthread');

} else {

	if($subject == '' || $message == '') {
		showmessage('post_sm_isnull');
	}

	if($post_invalid = checkpost()) {
		showmessage($post_invalid);
	}

	if(checkflood()) {
		showmessage('post_flood_ctrl');
	}

	if($allowpostattach && is_array($_FILES['attach'])) {
		foreach($_FILES['attach']['name'] as $attachname) {
			if($attachname != '') {
				checklowerlimit($postattachcredits);
				break;
			}
		}
	}

	$typeid = isset($forum['threadtypes']['types'][$typeid]) ? $typeid : 0;
	$iconid = !empty($iconid) && isset($_DCACHE['icons'][$iconid]) ? $iconid : 0;
	$displayorder = $modnewthreads ? -2 : (($forum['ismoderator'] && !empty($sticktopic)) ? 1 : 0);
	$digest = ($forum['ismoderator'] && !empty($addtodigest)) ? 1 : 0;
	$blog = $allowuseblog && $forum['allowshare'] && !empty($addtoblog) ? 1 : 0;
	$readperm = $allowsetreadperm ? $readperm : 0;
	$isanonymous = $isanonymous && $allowanonymous ? 1 : 0;
	$price = $maxprice && !$special ? ($price <= $maxprice ? $price : $maxprice) : 0;

	if(!$typeid && $forum['threadtypes']['required']) {
		showmessage('post_type_isnull');
	}

	if($price > 0 && floor($price * (1 - $creditstax)) == 0) {
		showmessage('post_net_price_iszero');
	}

	if($special == 1 && $allowpostpoll && trim($polloptions)) {
		$pollarray = array();
		$polloptions = explode("\n", $polloptions);
		foreach($polloptions as $key => $value) {
			if(!trim($value)) {
				unset($polloptions[$key]);
			}
		}
		if(count($polloptions) > $maxpolloptions) {
			showmessage('post_poll_option_toomany');
		} elseif(count($polloptions) == 1) {
			showmessage('post_poll_inputmore');
		}
		$maxchoices = $maxchoices >= count($polloptions) ? count($polloptions) : $maxchoices;
		$pollarray['options'] = $polloptions;
		$pollarray['multiple'] = !empty($multiplepoll);
		$pollarray['visible'] = empty($visiblepoll);
		if(preg_match("/^\d*$/", trim($maxchoices)) && preg_match("/^\d*$/", trim($expiration))) {
			if(!$pollarray['multiple']) {
				$pollarray['maxchoices'] = 1;
			} elseif(empty($maxchoices)) {
				$pollarray['maxchoices'] = 0;
			} elseif($maxchoices == 1) {
				$pollarray['multiple'] = 0;
				$pollarray['maxchoices'] = $maxchoices;
			} else {
				$pollarray['maxchoices'] = $maxchoices;
			}
			if(empty($expiration)) {
				$pollarray['expiration'] = 0;
			} else {
				$pollarray['expiration'] = $timestamp + 86400 * $expiration;
			}
		} else {
			showmessage('poll_maxchoices_expiration_invalid');
		}
	} elseif($special == 2 && $allowposttrade) {
		$item_price = intval($item_price);
		if(!trim($seller)) {
			showmessage('trade_alipay_please');
		} elseif(!trim($item_name)) {
			showmessage('trade_please_name');
		} elseif($maxtradeprice && ($mintradeprice > $item_price || $maxtradeprice < $item_price)) {
			showmessage('trade_price_between');
		} elseif(!$maxtradeprice && $mintradeprice > $item_price) {
			showmessage('trade_price_more_than');
		} elseif(!trim($item_locus)) {
			showmessage('trade_please_locus');
		} elseif($item_number < 1) {
			showmessage('tread_please_number');
		}

	} elseif($special == 3 && $allowpostreward) {
		$rewardprice = intval($rewardprice);
		if(!$rewardprice) {
			showmessage('reward_credits_please');
		} elseif($rewardprice < $minrewardprice || ($maxrewardprice > 0 && $rewardprice > $maxrewardprice)) {
			showmessage('reward_credits_between');
		} elseif(($realprice = $rewardprice + ceil($rewardprice * $creditstax)) > $_DSESSION["extcredits$creditstrans"]) {
			showmessage('reward_credits_shortage');
		}

		$price = $rewardprice;

		$db->query("UPDATE {$tablepre}members SET extcredits$creditstrans=extcredits$creditstrans-$realprice WHERE uid='$discuz_uid'");
	} elseif($special == 4 && $allowpostactivity) {
		if(empty($starttimefrom[$activitytime])) {
			showmessage('activity_fromtime_please');
		} elseif(strtotime($starttimefrom[$activitytime]) === -1 || strtotime($starttimefrom[$activitytime]) === FALSE) {
			showmessage('activity_fromtime_error');
		} elseif(strtotime($starttimefrom[$activitytime]) < $timestamp) {
			showmessage('activity_smaller_current');
		} elseif($activitytime && ((strtotime($starttimefrom) > strtotime($starttimeto) || !$starttimeto))) {
			showmessage('activity_fromtime_error');
		} elseif(!trim($activityclass)) {
			showmessage('activity_sort_please');
		} elseif(!trim($activityplace)) {
			showmessage('activity_address_please');
		} elseif(trim($activityexpiration) && (strtotime($activityexpiration) === -1 || strtotime($activityexpiration) === FALSE)) {
			showmessage('activity_totime_error');
		}

		$activity = array();
		$activity['class'] = dhtmlspecialchars(trim($activityclass));
		$activity['starttimefrom'] = strtotime($starttimefrom[$activitytime]) - $timeoffset * 3600;
		$activity['starttimeto'] = $activitytime ? strtotime($starttimeto) - $timeoffset * 3600 : 0;
		$activity['place'] = dhtmlspecialchars(trim($activityplace));
		$activity['cost'] = intval($cost);
		$activity['gender'] = intval($gender);
		$activity['number'] = intval($activitynumber);

		if($activityexpiration) {
			$activity['expiration'] = strtotime($activityexpiration) - $timeoffset * 3600;
		} else {
			$activity['expiration'] = 0;
		}
		if(trim($activitycity)) {
			$subject .= '['.dhtmlspecialchars(trim($activitycity)).']';
		}
	}

	$author = !$isanonymous ? $discuz_user : '';

	$moderated = $digest || $displayorder > 0 ? 1 : 0;

	$attachment = ($allowpostattach && $attachments = attach_upload()) ? 1 : 0;

	$subscribed = !empty($emailnotify) && $discuz_uid ? 1 : 0;

	if($subscribed) {
		$db->query("REPLACE INTO {$tablepre}subscriptions (uid, tid, lastpost, lastnotify)
			VALUES ('$discuz_uid', '$tid', '$timestamp', '$timestamp')", 'UNBUFFERED');
	}

	$supe_pushstatus = $supe_status && $forum['supe_pushsetting']['status'] == 1 && !$modnewthreads ? '1' : '0';

	$db->query("INSERT INTO {$tablepre}threads (fid, readperm, price, iconid, typeid, author, authorid, subject, dateline, lastpost, lastposter, displayorder, digest, blog, special, attachment, subscribed, moderated, supe_pushstatus)
		VALUES ('$fid', '$readperm', '$price', '$iconid', '$typeid', '$author', '$discuz_uid', '$subject', '$timestamp', '$timestamp', '$author', '$displayorder', '$digest', '$blog', '$special', '$attachment', '$subscribed', '$moderated', '$supe_pushstatus')");
	$tid = $db->insert_id();

	if($special == 2 && $allowposttrade && !empty($seller) && !empty($item_name) && !empty($item_price)) {

		require_once DISCUZ_ROOT.'./api/tradeapi.php';
		trade_create(array(
			'tid' => $tid,
			'item_expiration' => $item_expiration,
			'thread' => $thread,
			'discuz_uid' => $discuz_uid,
			'author' => $author,
			'seller' => $seller,
			'item_name' => $item_name,
			'item_price' => $item_price,
			'item_number' => $item_number,
			'item_quality' => $item_quality,
			'item_locus' => $item_locus,
			'transport' => $transport,
			'postage_mail' => $postage_mail,
			'postage_express' => $postage_express,
			'postage_ems' => $postage_ems,
			'item_type' => $item_type
		));

	} elseif($special == 3 && $allowpostreward) {
		$db->query("INSERT INTO {$tablepre}rewardlog (tid, authorid, netamount, dateline) VALUES ('$tid', '$discuz_uid', $realprice, '$timestamp')");
	}

	$db->query("REPLACE INTO {$tablepre}mythreads (uid, tid, dateline) VALUES ('$discuz_uid', '$tid', '$timestamp')", 'UNBUFFERED');

	if($moderated) {
		updatemodlog($tid, ($displayorder > 0 ? 'STK' : 'DIG'));
		updatemodworks(($displayorder > 0 ? 'STK' : 'DIG'), 1);
	}

	if($special == 1 && $allowpostpoll && trim($polloptions)) {
		$db->query("INSERT INTO {$tablepre}polls (tid, multiple, visible, maxchoices, expiration)
			VALUES ('$tid', '$pollarray[multiple]', '$pollarray[visible]', '$pollarray[maxchoices]', '$pollarray[expiration]')");
		foreach($pollarray['options'] as $polloptvalue) {
			$polloptvalue = dhtmlspecialchars(trim($polloptvalue));
			$db->query("INSERT INTO {$tablepre}polloptions (tid, polloption) VALUES ('$tid', '$polloptvalue')");
		}
	} elseif($special == 4 && $allowpostactivity) {
		$db->query("INSERT INTO {$tablepre}activities (tid, uid, cost, starttimefrom, starttimeto, place, class, gender, number, expiration)
			VALUES ('$tid', '$discuz_uid', '$activity[cost]', '$activity[starttimefrom]', '$activity[starttimeto]', '$activity[place]', '$activity[class]', '$activity[gender]', '$activity[number]', '$activity[expiration]')");
	}

	$bbcodeoff = checkbbcodes($message, !empty($bbcodeoff));
	$smileyoff = checksmilies($message, !empty($smileyoff));
	$parseurloff = !empty($parseurloff);
	$htmlon = $allowhtml && !empty($htmlon) ? 1 : 0;

	$pinvisible = $modnewthreads ? -2 : 0;
	$db->query("INSERT INTO {$tablepre}posts (fid, tid, first, author, authorid, subject, dateline, message, useip, invisible, anonymous, usesig, htmlon, bbcodeoff, smileyoff, parseurloff, attachment)
		VALUES ('$fid', '$tid', '1', '$discuz_user', '$discuz_uid', '$subject', '$timestamp', '$message', '$onlineip', '$pinvisible', '$isanonymous', '$usesig', '$htmlon', '$bbcodeoff', '$smileyoff', '$parseurloff', '$attachment')");
	$pid = $db->insert_id();

	if($attachment) {
		foreach($attachments as $attach) {
			$db->query("INSERT INTO {$tablepre}attachments (tid, pid, dateline, readperm, filename, description, filetype, filesize, attachment, downloads, isimage, uid)
				VALUES ('$tid', '$pid', '$timestamp', '$attach[perm]', '$attach[name]', '$attach[description]', '$attach[type]', '$attach[size]', '$attach[attachment]', '0', '$attach[isimage]', '$attach[uid]')");
		}
		updatecredits($discuz_uid, $postattachcredits, count($attachments));
	}

	if($modnewthreads) {

		$allowuseblog && $isblog && $blog ? showmessage('post_newthread_mod_blog_succeed', "blog.php?uid=$discuz_uid") :
			showmessage('post_newthread_mod_succeed', "forumdisplay.php?fid=$fid");

	} else {

		if($digest) {
			foreach($digestcredits as $id => $addcredits) {
				$postcredits[$id] = (isset($postcredits[$id]) ? $postcredits[$id] : 0) + $addcredits;
			}
		}
		updatepostcredits('+', $discuz_uid, $postcredits);
                require_once DISCUZ_ROOT.'./include/cache.func.php';
                updatecache('newthread');
                require_once DISCUZ_ROOT.'./include/cache.func.php';
                updatecache('daystar');

		$lastpost = "$tid\t$subject\t$timestamp\t$author";
		$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost', threads=threads+1, posts=posts+1, todayposts=todayposts+1 WHERE fid='$fid'", 'UNBUFFERED');
		if($forum['type'] == 'sub') {
			$db->query("UPDATE {$tablepre}forums SET lastpost='$lastpost' WHERE fid='$forum[fup]'", 'UNBUFFERED');
		}
                        $db->query("UPDATE {$tablepre}mypetdata SET mypetexp= mypetexp+100 WHERE username ='$discuz_user'");

		if($allowuseblog && $isblog && $blog) {
			showmessage('post_newthread_blog_succeed', "blog.php?tid=$tid");
		} else {
			header("Location: viewthread.php?tid=$tid&extra=$extra");
		}

	}

}

?>