1<?php
2/**
3 * MyBB 1.8
4 * Copyright 2014 MyBB Group, All Rights Reserved
5 *
6 * Website: http://www.mybb.com
7 * License: http://www.mybb.com/about/license
8 *
9 */
10
11define("IN_MYBB", 1);
12define('THIS_SCRIPT', 'newthread.php');
13
14$templatelist = "newthread,previewpost,loginbox,changeuserbox,newthread_postpoll,posticons,codebuttons,postbit,post_attachments_attachment_unapproved,newreply_modoptions_close,newreply_modoptions_stick";
15$templatelist .= ",newthread_disablesmilies,post_attachments_new,post_attachments,post_savedraftbutton,post_subscription_method,post_attachments_attachment_remove,postbit_warninglevel_formatted,postbit_icon";
16$templatelist .= ",forumdisplay_rules,forumdisplay_rules_link,post_attachments_attachment_postinsert,post_attachments_attachment,newthread_signature,post_prefixselect_prefix,post_prefixselect_single,posticons_icon";
17$templatelist .= ",post_captcha_hidden,post_captcha_recaptcha_invisible,post_captcha_nocaptcha,post_captcha_hcaptcha_invisible,post_captcha_hcaptcha,post_javascript,postbit_gotopost,newthread_postoptions,post_attachments_add,post_attachments_viewlink";
18$templatelist .= ",postbit_avatar,postbit_find,postbit_pm,postbit_rep_button,postbit_www,postbit_email,postbit_reputation,postbit_warn,postbit_warninglevel,postbit_author_user,postbit_author_guest,post_captcha";
19$templatelist .= ",postbit_signature,postbit_classic,postbit_attachments_thumbnails_thumbnail,postbit_attachments_images_image,postbit_attachments_attachment,postbit_attachments_attachment_unapproved";
20$templatelist .= ",postbit_attachments_thumbnails,postbit_attachments_images,postbit_attachments,postbit_reputation_formatted_link,post_attachments_update,postbit_offline,newreply_modoptions,newthread_multiquote_external";
21$templatelist .= ",postbit_profilefield_multiselect_value,postbit_profilefield_multiselect,newthread_draftinput,global_moderation_notice,postbit_online,postbit_away,attachment_icon,postbit_userstar,postbit_groupimage";
22
23require_once "./global.php";
24require_once MYBB_ROOT."inc/functions_post.php";
25require_once MYBB_ROOT."inc/functions_user.php";
26require_once MYBB_ROOT."inc/functions_upload.php";
27
28// Load global language phrases
29$lang->load("newthread");
30
31$tid = $pid = 0;
32$mybb->input['action'] = $mybb->get_input('action');
33$mybb->input['tid'] = $mybb->get_input('tid', MyBB::INPUT_INT);
34$mybb->input['pid'] = $mybb->get_input('pid', MyBB::INPUT_INT);
35if($mybb->input['action'] == "editdraft" || ($mybb->get_input('savedraft') && $mybb->input['tid']) || ($mybb->input['tid'] && $mybb->input['pid']))
36{
37	$thread = get_thread($mybb->input['tid']);
38
39	$query = $db->simple_select("posts", "*", "tid='".$mybb->get_input('tid', MyBB::INPUT_INT)."' AND visible='-2'", array('order_by' => 'dateline, pid', 'limit' => 1));
40	$post = $db->fetch_array($query);
41
42	if(!$thread['tid'] || !$post['pid'] || $thread['visible'] != -2 || $thread['uid'] != $mybb->user['uid'])
43	{
44		error($lang->invalidthread);
45	}
46
47	$pid = $post['pid'];
48	$fid = $thread['fid'];
49	$tid = $thread['tid'];
50	eval("\$editdraftpid = \"".$templates->get("newthread_draftinput")."\";");
51}
52else
53{
54	$fid = $mybb->get_input('fid', MyBB::INPUT_INT);
55	$editdraftpid = '';
56}
57
58// Fetch forum information.
59$forum = get_forum($fid);
60if(!$forum)
61{
62	error($lang->error_invalidforum);
63}
64
65// Draw the navigation
66build_forum_breadcrumb($fid);
67add_breadcrumb($lang->nav_newthread);
68
69$forumpermissions = forum_permissions($fid);
70
71if($forum['open'] == 0 || $forum['type'] != "f" || $forum['linkto'] != "")
72{
73	error($lang->error_closedinvalidforum);
74}
75
76if($forumpermissions['canview'] == 0 || $forumpermissions['canpostthreads'] == 0)
77{
78	error_no_permission();
79}
80
81if($mybb->user['suspendposting'] == 1)
82{
83	$suspendedpostingtype = $lang->error_suspendedposting_permanent;
84	if($mybb->user['suspensiontime'])
85	{
86		$suspendedpostingtype = $lang->sprintf($lang->error_suspendedposting_temporal, my_date($mybb->settings['dateformat'], $mybb->user['suspensiontime']));
87	}
88
89	$lang->error_suspendedposting = $lang->sprintf($lang->error_suspendedposting, $suspendedpostingtype, my_date($mybb->settings['timeformat'], $mybb->user['suspensiontime']));
90
91	error($lang->error_suspendedposting);
92}
93
94// Check if this forum is password protected and we have a valid password
95check_forum_password($forum['fid']);
96
97// If MyCode is on for this forum and the MyCode editor is enabled in the Admin CP, draw the code buttons and smilie inserter.
98if($mybb->settings['bbcodeinserter'] != 0 && $forum['allowmycode'] != 0 && (!$mybb->user['uid'] || $mybb->user['showcodebuttons'] != 0))
99{
100	$codebuttons = build_mycode_inserter("message", $forum['allowsmilies']);
101	if($forum['allowsmilies'] != 0)
102	{
103		$smilieinserter = build_clickable_smilies();
104	}
105}
106
107// Does this forum allow post icons? If so, fetch the post icons.
108if($forum['allowpicons'] != 0)
109{
110	$posticons = get_post_icons();
111}
112
113// If we have a currently logged in user then fetch the change user box.
114if($mybb->user['uid'] != 0)
115{
116	$mybb->user['username'] = htmlspecialchars_uni($mybb->user['username']);
117	eval("\$loginbox = \"".$templates->get("changeuserbox")."\";");
118}
119
120// Otherwise we have a guest, determine the "username" and get the login box.
121else
122{
123	if(!isset($mybb->input['previewpost']) && $mybb->input['action'] != "do_newthread")
124	{
125		$username = '';
126	}
127	else
128	{
129		$username = htmlspecialchars_uni($mybb->get_input('username'));
130	}
131	eval("\$loginbox = \"".$templates->get("loginbox")."\";");
132}
133
134// If we're not performing a new thread insert and not editing a draft then we're posting a new thread.
135if($mybb->input['action'] != "do_newthread" && $mybb->input['action'] != "editdraft")
136{
137	$mybb->input['action'] = "newthread";
138}
139
140// Previewing a post, overwrite the action to the new thread action.
141if(!empty($mybb->input['previewpost']))
142{
143	$mybb->input['action'] = "newthread";
144}
145
146// Setup a unique posthash for attachment management
147if(!$mybb->get_input('posthash') && !$pid)
148{
149	$mybb->input['posthash'] = md5($mybb->user['uid'].random_str());
150}
151
152if((empty($_POST) && empty($_FILES)) && $mybb->get_input('processed', MyBB::INPUT_INT) == 1)
153{
154	error($lang->error_empty_post_input);
155}
156
157$errors = array();
158$maximageserror = $attacherror = '';
159
160// Handle attachments if we've got any.
161if($mybb->settings['enableattachments'] == 1 && ($mybb->get_input('newattachment') || $mybb->get_input('updateattachment') || ((($mybb->input['action'] == "do_newthread" && $mybb->get_input('submit')) || ($mybb->input['action'] == "newthread" && isset($mybb->input['previewpost'])) || isset($mybb->input['savedraft'])) && $_FILES['attachments'])))
162{
163	// Verify incoming POST request
164	verify_post_check($mybb->get_input('my_post_key'));
165
166	if($mybb->input['action'] == "editdraft" || ($mybb->input['tid'] && $mybb->input['pid']))
167	{
168		$attachwhere = "pid='{$pid}'";
169	}
170	else
171	{
172		$attachwhere = "posthash='".$db->escape_string($mybb->get_input('posthash'))."'";
173	}
174
175	$ret = add_attachments($pid, $forumpermissions, $attachwhere, "newthread");
176
177	if($mybb->get_input('ajax', MyBB::INPUT_INT) == 1)
178	{
179		if(isset($ret['success']))
180		{
181			$attachment = array('aid'=>'{1}', 'icon'=>'{2}', 'filename'=>'{3}', 'size'=>'{4}');
182			if($mybb->settings['bbcodeinserter'] != 0 && $forum['allowmycode'] != 0 && $mybb->user['showcodebuttons'] != 0)
183			{
184				eval("\$postinsert = \"".$templates->get("post_attachments_attachment_postinsert")."\";");
185			}
186			eval("\$attach_rem_options = \"".$templates->get("post_attachments_attachment_remove")."\";");
187			eval("\$attemplate = \"".$templates->get("post_attachments_attachment")."\";");
188			$ret['template'] = $attemplate;
189
190			$query = $db->simple_select("attachments", "SUM(filesize) AS ausage", "uid='".$mybb->user['uid']."'");
191			$usage = $db->fetch_array($query);
192			$ret['usage'] = get_friendly_size($usage['ausage']);
193		}
194
195		header("Content-type: application/json; charset={$lang->settings['charset']}");
196		echo json_encode($ret);
197		exit();
198	}
199
200	if(!empty($ret['errors']))
201	{
202		$errors = $ret['errors'];
203	}
204
205	// If we were dealing with an attachment but didn't click 'Post Thread' or 'Save as Draft', force the new thread page again.
206	if(!$mybb->get_input('submit') && !$mybb->get_input('savedraft'))
207	{
208		$mybb->input['action'] = "newthread";
209	}
210}
211
212detect_attachmentact();
213
214// Are we removing an attachment from the thread?
215if($mybb->settings['enableattachments'] == 1 && $mybb->get_input('attachmentaid', MyBB::INPUT_INT) && $mybb->get_input('attachmentact') == "remove")
216{
217	// Verify incoming POST request
218	verify_post_check($mybb->get_input('my_post_key'));
219
220	remove_attachment($pid, $mybb->get_input('posthash'), $mybb->get_input('attachmentaid', MyBB::INPUT_INT));
221
222	if(!$mybb->get_input('submit'))
223	{
224		$mybb->input['action'] = "newthread";
225	}
226
227	if($mybb->get_input('ajax', MyBB::INPUT_INT) == 1)
228	{
229		$query = $db->simple_select("attachments", "SUM(filesize) AS ausage", "uid='".$mybb->user['uid']."'");
230		$usage = $db->fetch_array($query);
231
232		header("Content-type: application/json; charset={$lang->settings['charset']}");
233		echo json_encode(array("success" => true, "usage" => get_friendly_size($usage['ausage'])));
234		exit();
235	}
236}
237
238$thread_errors = "";
239$hide_captcha = false;
240
241// Check the maximum posts per day for this user
242if($mybb->usergroup['maxposts'] > 0)
243{
244	$daycut = TIME_NOW-60*60*24;
245	$query = $db->simple_select("posts", "COUNT(*) AS posts_today", "uid='{$mybb->user['uid']}' AND visible !='-1' AND dateline>{$daycut}");
246	$post_count = $db->fetch_field($query, "posts_today");
247	if($post_count >= $mybb->usergroup['maxposts'])
248	{
249		$lang->error_maxposts = $lang->sprintf($lang->error_maxposts, $mybb->usergroup['maxposts']);
250		error($lang->error_maxposts);
251	}
252}
253
254// Performing the posting of a new thread.
255if($mybb->input['action'] == "do_newthread" && $mybb->request_method == "post")
256{
257	// Verify incoming POST request
258	verify_post_check($mybb->get_input('my_post_key'));
259
260	$plugins->run_hooks("newthread_do_newthread_start");
261
262	// If this isn't a logged in user, then we need to do some special validation.
263	if($mybb->user['uid'] == 0)
264	{
265		// If they didn't specify a username leave blank so $lang->guest can be used on output
266		if(!$mybb->get_input('username'))
267		{
268			$username = '';
269		}
270		// Otherwise use the name they specified.
271		else
272		{
273			$username = $mybb->get_input('username');
274		}
275		$uid = 0;
276
277		if(!$mybb->user['uid'] && $mybb->settings['stopforumspam_on_newthread'])
278		{
279			require_once MYBB_ROOT . '/inc/class_stopforumspamchecker.php';
280
281			$stop_forum_spam_checker = new StopForumSpamChecker(
282				$plugins,
283				$mybb->settings['stopforumspam_min_weighting_before_spam'],
284				$mybb->settings['stopforumspam_check_usernames'],
285				$mybb->settings['stopforumspam_check_emails'],
286				$mybb->settings['stopforumspam_check_ips'],
287				$mybb->settings['stopforumspam_log_blocks']
288			);
289
290			try {
291				if($stop_forum_spam_checker->is_user_a_spammer($mybb->get_input('username'), '', get_ip()))
292				{
293					$errors[] = $lang->sprintf($lang->error_stop_forum_spam_spammer,
294						$stop_forum_spam_checker->getErrorText(array(
295							'stopforumspam_check_usernames',
296							'stopforumspam_check_ips'
297							)));
298				}
299			}
300			catch (Exception $e)
301			{
302				if($mybb->settings['stopforumspam_block_on_error'])
303				{
304					$errors[] = $lang->error_stop_forum_spam_fetching;
305				}
306			}
307		}
308	}
309	// This user is logged in.
310	else
311	{
312		$username = $mybb->user['username'];
313		$uid = $mybb->user['uid'];
314	}
315
316	// Attempt to see if this post is a duplicate or not
317	if($uid > 0)
318	{
319		$user_check = "p.uid='{$uid}'";
320	}
321	else
322	{
323		$user_check = "p.ipaddress=".$db->escape_binary($session->packedip);
324	}
325	if(!$mybb->get_input('savedraft') && !$pid)
326	{
327		$query = $db->simple_select("posts p", "p.pid", "$user_check AND p.fid='{$forum['fid']}' AND p.subject='".$db->escape_string($mybb->get_input('subject'))."' AND p.message='".$db->escape_string($mybb->get_input('message'))."' AND p.dateline>".(TIME_NOW-600));
328		if($db->num_rows($query) > 0)
329		{
330			error($lang->error_post_already_submitted);
331		}
332	}
333
334	// Set up posthandler.
335	require_once MYBB_ROOT."inc/datahandlers/post.php";
336	$posthandler = new PostDataHandler("insert");
337	$posthandler->action = "thread";
338
339	// Set the thread data that came from the input to the $thread array.
340	$new_thread = array(
341		"fid" => $forum['fid'],
342		"subject" => $mybb->get_input('subject'),
343		"prefix" => $mybb->get_input('threadprefix', MyBB::INPUT_INT),
344		"icon" => $mybb->get_input('icon', MyBB::INPUT_INT),
345		"uid" => $uid,
346		"username" => $username,
347		"message" => $mybb->get_input('message'),
348		"ipaddress" => $session->packedip,
349		"posthash" => $mybb->get_input('posthash')
350	);
351
352	if($pid != '')
353	{
354		$new_thread['pid'] = $pid;
355	}
356
357	// Are we saving a draft thread?
358	if($mybb->get_input('savedraft') && $mybb->user['uid'])
359	{
360		$new_thread['savedraft'] = 1;
361	}
362	else
363	{
364		$new_thread['savedraft'] = 0;
365	}
366
367	// Is this thread already a draft and we're updating it?
368	if(isset($thread['tid']) && $thread['visible'] == -2)
369	{
370		$new_thread['tid'] = $thread['tid'];
371	}
372
373	$postoptions = $mybb->get_input('postoptions', MyBB::INPUT_ARRAY);
374	if(!isset($postoptions['signature']))
375	{
376		$postoptions['signature'] = 0;
377	}
378	if(!isset($postoptions['subscriptionmethod']))
379	{
380		$postoptions['subscriptionmethod'] = 0;
381	}
382	if(!isset($postoptions['disablesmilies']))
383	{
384		$postoptions['disablesmilies'] = 0;
385	}
386
387	// Set up the thread options from the input.
388	$new_thread['options'] = array(
389		"signature" => $postoptions['signature'],
390		"subscriptionmethod" => $postoptions['subscriptionmethod'],
391		"disablesmilies" => $postoptions['disablesmilies']
392	);
393
394	// Apply moderation options if we have them
395	$new_thread['modoptions'] = $mybb->get_input('modoptions', MyBB::INPUT_ARRAY);
396
397	$posthandler->set_data($new_thread);
398
399	// Now let the post handler do all the hard work.
400	$valid_thread = $posthandler->validate_thread();
401
402	$post_errors = array();
403	// Fetch friendly error messages if this is an invalid thread
404	if(!$valid_thread)
405	{
406		$post_errors = $posthandler->get_friendly_errors();
407	}
408
409	// Check captcha image
410	if($mybb->settings['captchaimage'] && !$mybb->user['uid'])
411	{
412		require_once MYBB_ROOT.'inc/class_captcha.php';
413		$post_captcha = new captcha;
414
415		if($post_captcha->validate_captcha() == false)
416		{
417			// CAPTCHA validation failed
418			foreach($post_captcha->get_errors() as $error)
419			{
420				$post_errors[] = $error;
421			}
422		}
423		else
424		{
425			$hide_captcha = true;
426		}
427	}
428
429	// One or more errors returned, fetch error list and throw to newthread page
430	if(count($post_errors) > 0)
431	{
432		$thread_errors = inline_error($post_errors);
433		$mybb->input['action'] = "newthread";
434	}
435	// No errors were found, it is safe to insert the thread.
436	else
437	{
438		$thread_info = $posthandler->insert_thread();
439		$tid = $thread_info['tid'];
440		$visible = $thread_info['visible'];
441
442		// Invalidate solved captcha
443		if($mybb->settings['captchaimage'] && !$mybb->user['uid'])
444		{
445			$post_captcha->invalidate_captcha();
446		}
447
448		$force_redirect = false;
449
450		// Mark thread as read
451		require_once MYBB_ROOT."inc/functions_indicators.php";
452		mark_thread_read($tid, $fid);
453
454		// We were updating a draft thread, send them back to the draft listing.
455		if($new_thread['savedraft'] == 1)
456		{
457			$lang->redirect_newthread = $lang->draft_saved;
458			$url = "usercp.php?action=drafts";
459		}
460
461		// A poll was being posted with this thread, throw them to poll posting page.
462		else if($mybb->get_input('postpoll', MyBB::INPUT_INT) && $forumpermissions['canpostpolls'])
463		{
464			$url = "polls.php?action=newpoll&tid=$tid&polloptions=".$mybb->get_input('numpolloptions', MyBB::INPUT_INT);
465			$lang->redirect_newthread .= $lang->redirect_newthread_poll;
466		}
467
468		// This thread is stuck in the moderation queue, send them back to the forum.
469		else if(!$visible)
470		{
471			// Moderated thread
472			$lang->redirect_newthread .= $lang->redirect_newthread_moderation;
473			$url = get_forum_link($fid);
474
475			// User must see moderation notice, regardless of redirect settings
476			$force_redirect = true;
477		}
478
479		// The thread is being made in a forum the user cannot see threads in, send them back to the forum.
480		else if($visible == 1 && $forumpermissions['canviewthreads'] != 1)
481		{
482			$lang->redirect_newthread .= $lang->redirect_newthread_unviewable;
483			$url = get_forum_link($fid);
484
485			// User must see permission notice, regardless of redirect settings
486			$force_redirect = true;
487		}
488
489		// This is just a normal thread - send them to it.
490		else
491		{
492			// Visible thread
493			$lang->redirect_newthread .= $lang->redirect_newthread_thread;
494			$url = get_thread_link($tid);
495		}
496
497		// Mark any quoted posts so they're no longer selected - attempts to maintain those which weren't selected
498		if(isset($mybb->input['quoted_ids']) && isset($mybb->cookies['multiquote']) && $mybb->settings['multiquote'] != 0)
499		{
500			// We quoted all posts - remove the entire cookie
501			if($mybb->get_input('quoted_ids') == "all")
502			{
503				my_unsetcookie("multiquote");
504			}
505		}
506
507		$plugins->run_hooks("newthread_do_newthread_end");
508
509		// Hop to it! Send them to the next page.
510		if(!$mybb->get_input('postpoll', MyBB::INPUT_INT))
511		{
512			$lang->redirect_newthread .= $lang->sprintf($lang->redirect_return_forum, get_forum_link($fid));
513		}
514		redirect($url, $lang->redirect_newthread, "", $force_redirect);
515	}
516}
517
518if($mybb->input['action'] == "newthread" || $mybb->input['action'] == "editdraft")
519{
520	$plugins->run_hooks("newthread_start");
521
522	// Do we have attachment errors?
523	if(count($errors) > 0)
524	{
525		$thread_errors = inline_error($errors);
526	}
527
528	$multiquote_external = $quoted_ids = '';
529
530	$subject = $message = '';
531	// If this isn't a preview and we're not editing a draft, then handle quoted posts
532	if(empty($mybb->input['previewpost']) && !$thread_errors && $mybb->input['action'] != "editdraft")
533	{
534		$quoted_posts = array();
535		// Handle multiquote
536		if(isset($mybb->cookies['multiquote']) && $mybb->settings['multiquote'] != 0)
537		{
538			$multiquoted = explode("|", $mybb->cookies['multiquote']);
539			foreach($multiquoted as $post)
540			{
541				$quoted_posts[$post] = (int)$post;
542			}
543		}
544
545		// Quoting more than one post - fetch them
546		if(count($quoted_posts) > 0)
547		{
548			$external_quotes = 0;
549			$quoted_posts = implode(",", $quoted_posts);
550			$unviewable_forums = get_unviewable_forums();
551			$inactiveforums = get_inactive_forums();
552			if($unviewable_forums)
553			{
554				$unviewable_forums = "AND t.fid NOT IN ({$unviewable_forums})";
555			}
556			if($inactiveforums)
557			{
558				$inactiveforums = "AND t.fid NOT IN ({$inactiveforums})";
559			}
560
561			if(is_moderator($fid))
562			{
563				$visible_where = "AND p.visible != 2";
564			}
565			else
566			{
567				$visible_where = "AND p.visible > 0";
568			}
569
570			// Check group permissions if we can't view threads not started by us
571			$group_permissions = forum_permissions();
572			$onlyusfids = array();
573			$onlyusforums = '';
574			foreach($group_permissions as $gpfid => $forum_permissions)
575			{
576				if(isset($forum_permissions['canonlyviewownthreads']) && $forum_permissions['canonlyviewownthreads'] == 1)
577				{
578					$onlyusfids[] = $gpfid;
579				}
580			}
581			if(!empty($onlyusfids))
582			{
583				$onlyusforums = "AND ((t.fid IN(".implode(',', $onlyusfids).") AND t.uid='{$mybb->user['uid']}') OR t.fid NOT IN(".implode(',', $onlyusfids)."))";
584			}
585
586			if($mybb->get_input('load_all_quotes', MyBB::INPUT_INT) == 1)
587			{
588				$query = $db->query("
589					SELECT p.subject, p.message, p.pid, p.tid, p.username, p.dateline, u.username AS userusername
590					FROM ".TABLE_PREFIX."posts p
591					LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
592					LEFT JOIN ".TABLE_PREFIX."users u ON (u.uid=p.uid)
593					WHERE p.pid IN ({$quoted_posts}) {$unviewable_forums} {$inactiveforums} {$onlyusforums} {$visible_where}
594					ORDER BY p.dateline, p.pid
595				");
596				while($quoted_post = $db->fetch_array($query))
597				{
598					if($quoted_post['userusername'])
599					{
600						$quoted_post['username'] = $quoted_post['userusername'];
601					}
602					$quoted_post['message'] = preg_replace('#(^|\r|\n)/me ([^\r\n<]*)#i', "\\1* {$quoted_post['username']} \\2", $quoted_post['message']);
603					$quoted_post['message'] = preg_replace('#(^|\r|\n)/slap ([^\r\n<]*)#i', "\\1* {$quoted_post['username']} {$lang->slaps} \\2 {$lang->with_trout}", $quoted_post['message']);
604					$quoted_post['message'] = preg_replace("#\[attachment=([0-9]+?)\]#i", '', $quoted_post['message']);
605					$message .= "[quote='{$quoted_post['username']}' pid='{$quoted_post['pid']}' dateline='{$quoted_post['dateline']}']\n{$quoted_post['message']}\n[/quote]\n\n";
606				}
607
608				$quoted_ids = "all";
609			}
610			else
611			{
612				$query = $db->query("
613					SELECT COUNT(*) AS quotes
614					FROM ".TABLE_PREFIX."posts p
615					LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
616					WHERE p.pid IN ({$quoted_posts}) {$unviewable_forums} {$inactiveforums} {$onlyusforums} {$visible_where}
617				");
618				$external_quotes = $db->fetch_field($query, 'quotes');
619
620				if($external_quotes > 0)
621				{
622					if($external_quotes == 1)
623					{
624						$multiquote_text = $lang->multiquote_external_one;
625						$multiquote_deselect = $lang->multiquote_external_one_deselect;
626						$multiquote_quote = $lang->multiquote_external_one_quote;
627					}
628					else
629					{
630						$multiquote_text = $lang->sprintf($lang->multiquote_external, $external_quotes);
631						$multiquote_deselect = $lang->multiquote_external_deselect;
632						$multiquote_quote = $lang->multiquote_external_quote;
633					}
634					eval("\$multiquote_external = \"".$templates->get("newthread_multiquote_external")."\";");
635				}
636			}
637		}
638	}
639
640	if(isset($mybb->input['quoted_ids']))
641	{
642		$quoted_ids = htmlspecialchars_uni($mybb->get_input('quoted_ids'));
643	}
644
645	$postoptionschecked = array('signature' => '', 'disablesmilies' => '');
646	$subscribe = $nonesubscribe = $emailsubscribe = $pmsubscribe = '';
647	$postpollchecked = '';
648
649	// Check the various post options if we're
650	// a -> previewing a post
651	// b -> removing an attachment
652	// c -> adding a new attachment
653	// d -> have errors from posting
654
655	if(!empty($mybb->input['previewpost']) || $mybb->get_input('attachmentaid', MyBB::INPUT_INT) || $mybb->get_input('newattachment') || $mybb->get_input('updateattachment') || $thread_errors)
656	{
657		$postoptions = $mybb->get_input('postoptions', MyBB::INPUT_ARRAY);
658		if(isset($postoptions['signature']) && $postoptions['signature'] == 1)
659		{
660			$postoptionschecked['signature'] = " checked=\"checked\"";
661		}
662		if(isset($postoptions['disablesmilies']) && $postoptions['disablesmilies'] == 1)
663		{
664			$postoptionschecked['disablesmilies'] = " checked=\"checked\"";
665		}
666		if($mybb->get_input('postpoll', MyBB::INPUT_INT) == 1)
667		{
668			$postpollchecked = "checked=\"checked\"";
669		}
670		$subscription_method = get_subscription_method($tid, $postoptions);
671		$numpolloptions = $mybb->get_input('numpolloptions', MyBB::INPUT_INT);
672	}
673
674	// Editing a draft thread
675	else if($mybb->input['action'] == "editdraft" && $mybb->user['uid'])
676	{
677		$mybb->input['threadprefix'] = $thread['prefix'];
678		$message = htmlspecialchars_uni($post['message']);
679		$subject = htmlspecialchars_uni($post['subject']);
680		if($post['includesig'] != 0)
681		{
682			$postoptionschecked['signature'] = " checked=\"checked\"";
683		}
684		if($post['smilieoff'] == 1)
685		{
686			$postoptionschecked['disablesmilies'] = " checked=\"checked\"";
687		}
688		$icon = $post['icon'];
689		if($forum['allowpicons'] != 0)
690		{
691			$posticons = get_post_icons();
692		}
693		$subscription_method = get_subscription_method($tid); // Subscription method doesn't get saved in drafts
694	}
695
696	// Otherwise, this is our initial visit to this page.
697	else
698	{
699		if($mybb->user['signature'] != '')
700		{
701			$postoptionschecked['signature'] = " checked=\"checked\"";
702		}
703		$subscription_method = get_subscription_method($tid); // Fresh thread, let the function set the appropriate method
704		$numpolloptions = "2";
705	}
706
707	${$subscription_method.'subscribe'} = "checked=\"checked\" ";
708	$preview = '';
709
710	// If we're previewing a post then generate the preview.
711	if(!empty($mybb->input['previewpost']))
712	{
713		// If this isn't a logged in user, then we need to do some special validation.
714		if($mybb->user['uid'] == 0)
715		{
716			// If they didn't specify a username leave blank so $lang->guest can be used on output
717			if(!$mybb->get_input('username'))
718			{
719				$username = '';
720			}
721			// Otherwise use the name they specified.
722			else
723			{
724				$username = $mybb->get_input('username');
725			}
726			$uid = 0;
727		}
728		// This user is logged in.
729		else
730		{
731			$username = $mybb->user['username'];
732			$uid = $mybb->user['uid'];
733		}
734
735		// Set up posthandler.
736		require_once MYBB_ROOT."inc/datahandlers/post.php";
737		$posthandler = new PostDataHandler("insert");
738		$posthandler->action = "thread";
739
740		// Set the thread data that came from the input to the $thread array.
741		$new_thread = array(
742			"fid" => $forum['fid'],
743			"prefix" => $mybb->get_input('threadprefix', MyBB::INPUT_INT),
744			"subject" => $mybb->get_input('subject'),
745			"icon" => $mybb->get_input('icon'),
746			"uid" => $uid,
747			"username" => $username,
748			"message" => $mybb->get_input('message'),
749			"ipaddress" => $session->packedip,
750			"posthash" => $mybb->get_input('posthash')
751		);
752
753		if($pid != '')
754		{
755			$new_thread['pid'] = $pid;
756		}
757
758		$posthandler->set_data($new_thread);
759
760		// Now let the post handler do all the hard work.
761		$valid_thread = $posthandler->verify_message();
762		$valid_subject = $posthandler->verify_subject();
763
764		// guest post --> verify author
765		if($new_thread['uid'] == 0)
766		{
767			$valid_username = $posthandler->verify_author();
768		}
769		else
770		{
771			$valid_username = true;
772		}
773
774		$post_errors = array();
775		// Fetch friendly error messages if this is an invalid post
776		if(!$valid_thread || !$valid_subject || !$valid_username)
777		{
778			$post_errors = $posthandler->get_friendly_errors();
779		}
780
781		// One or more errors returned, fetch error list and throw to newreply page
782		if(count($post_errors) > 0)
783		{
784			$thread_errors = inline_error($post_errors);
785		}
786		else
787		{
788			$query = $db->query("
789				SELECT u.*, f.*
790				FROM ".TABLE_PREFIX."users u
791				LEFT JOIN ".TABLE_PREFIX."userfields f ON (f.ufid=u.uid)
792				WHERE u.uid='".$mybb->user['uid']."'
793			");
794			$post = $db->fetch_array($query);
795			$post['username'] = $username;
796			if($mybb->user['uid'])
797			{
798				$post['userusername'] = $mybb->user['username'];
799			}
800			$previewmessage = $mybb->get_input('message');
801			$post['message'] = $previewmessage;
802			$post['subject'] = $mybb->get_input('subject');
803			$post['icon'] = $mybb->get_input('icon', MyBB::INPUT_INT);
804			$mybb->input['postoptions'] = $mybb->get_input('postoptions', MyBB::INPUT_ARRAY);
805			if(isset($mybb->input['postoptions']['disablesmilies']))
806			{
807				$post['smilieoff'] = $mybb->input['postoptions']['disablesmilies'];
808			}
809			$post['dateline'] = TIME_NOW;
810			if(isset($mybb->input['postoptions']['signature']))
811			{
812				$post['includesig'] = $mybb->input['postoptions']['signature'];
813			}
814			if(!isset($post['includesig']) || $post['includesig'] != 1)
815			{
816				$post['includesig'] = 0;
817			}
818
819			// Fetch attachments assigned to this post
820			if($mybb->get_input('pid', MyBB::INPUT_INT))
821			{
822				$attachwhere = "pid='".$mybb->get_input('pid', MyBB::INPUT_INT)."'";
823			}
824			else
825			{
826				$attachwhere = "posthash='".$db->escape_string($mybb->get_input('posthash'))."'";
827			}
828
829			$query = $db->simple_select("attachments", "*", $attachwhere);
830			while($attachment = $db->fetch_array($query))
831			{
832				$attachcache[0][$attachment['aid']] = $attachment;
833			}
834
835			$postbit = build_postbit($post, 1);
836			eval("\$preview = \"".$templates->get("previewpost")."\";");
837		}
838		$message = htmlspecialchars_uni($mybb->get_input('message'));
839		$subject = htmlspecialchars_uni($mybb->get_input('subject'));
840	}
841
842	// Removing an attachment or adding a new one, or showing thread errors.
843	else if($mybb->get_input('attachmentaid', MyBB::INPUT_INT) || $mybb->get_input('newattachment') || $mybb->get_input('updateattachment') || $thread_errors)
844	{
845		$message = htmlspecialchars_uni($mybb->get_input('message'));
846		$subject = htmlspecialchars_uni($mybb->get_input('subject'));
847	}
848
849	// Generate thread prefix selector
850	if(!$mybb->get_input('threadprefix', MyBB::INPUT_INT))
851	{
852		$mybb->input['threadprefix'] = 0;
853	}
854
855	$prefixselect = build_prefix_select($forum['fid'], $mybb->get_input('threadprefix', MyBB::INPUT_INT));
856
857	$posthash = htmlspecialchars_uni($mybb->get_input('posthash'));
858
859	// Hide signature option if no permission
860	$signature = '';
861	if($mybb->usergroup['canusesig'] == 1 && !$mybb->user['suspendsignature'])
862	{
863		eval("\$signature = \"".$templates->get('newthread_signature')."\";");
864	}
865
866	// Can we disable smilies or are they disabled already?
867	$disablesmilies = '';
868	if($forum['allowsmilies'] != 0)
869	{
870		eval("\$disablesmilies = \"".$templates->get("newthread_disablesmilies")."\";");
871	}
872
873	$postoptions = '';
874	if(!empty($signature) || !empty($disablesmilies))
875	{
876		eval("\$postoptions = \"".$templates->get("newthread_postoptions")."\";");
877		$bgcolor = "trow2";
878		$bgcolor2 = "trow1";
879	}
880	else
881	{
882		$bgcolor = "trow1";
883		$bgcolor2 = "trow2";
884	}
885
886	$modoptions = '';
887	// Show the moderator options
888	if(is_moderator($fid))
889	{
890		$modoptions = $mybb->get_input('modoptions', MyBB::INPUT_ARRAY);
891		if(isset($modoptions['closethread']) && $modoptions['closethread'] == 1)
892		{
893			$closecheck = "checked=\"checked\"";
894		}
895		else
896		{
897			$closecheck = '';
898		}
899		if(isset($modoptions['stickthread']) && $modoptions['stickthread'] == 1)
900		{
901			$stickycheck = "checked=\"checked\"";
902		}
903		else
904		{
905			$stickycheck = '';
906		}
907
908		$closeoption = '';
909		if(is_moderator($fid, "canopenclosethreads"))
910		{
911			eval("\$closeoption = \"".$templates->get("newreply_modoptions_close")."\";");
912		}
913
914		$stickoption = '';
915		if(is_moderator($fid, "canstickunstickthreads"))
916		{
917			eval("\$stickoption = \"".$templates->get("newreply_modoptions_stick")."\";");
918		}
919
920		if(!empty($closeoption) || !empty($stickoption))
921		{
922			eval("\$modoptions = \"".$templates->get("newreply_modoptions")."\";");
923			$bgcolor = "trow1";
924			$bgcolor2 = "trow2";
925		}
926		else
927		{
928			$bgcolor = "trow2";
929			$bgcolor2 = "trow1";
930		}
931	}
932	else
933	{
934		$bgcolor = "trow2";
935		$bgcolor2 = "trow1";
936	}
937
938	// Fetch subscription select box
939	eval("\$subscriptionmethod = \"".$templates->get("post_subscription_method")."\";");
940
941	if($mybb->settings['enableattachments'] != 0 && $forumpermissions['canpostattachments'] != 0)
942	{ // Get a listing of the current attachments, if there are any
943		$attachcount = 0;
944		if($mybb->input['action'] == "editdraft" || ($mybb->input['tid'] && $mybb->input['pid']))
945		{
946			$attachwhere = "pid='$pid'";
947		}
948		else
949		{
950			$attachwhere = "posthash='".$db->escape_string($posthash)."'";
951		}
952		$query = $db->simple_select("attachments", "*", $attachwhere);
953		$attachments = '';
954		while($attachment = $db->fetch_array($query))
955		{
956			$attachment['size'] = get_friendly_size($attachment['filesize']);
957			$attachment['icon'] = get_attachment_icon(get_extension($attachment['filename']));
958			$attachment['filename'] = htmlspecialchars_uni($attachment['filename']);
959
960			if($mybb->settings['bbcodeinserter'] != 0 && $forum['allowmycode'] != 0 && (!$mybb->user['uid'] || $mybb->user['showcodebuttons'] != 0))
961			{
962				eval("\$postinsert = \"".$templates->get("post_attachments_attachment_postinsert")."\";");
963			}
964
965			eval("\$attach_rem_options = \"".$templates->get("post_attachments_attachment_remove")."\";");
966
967			$attach_mod_options = '';
968			if($attachment['visible'] != 1)
969			{
970				eval("\$attachments .= \"".$templates->get("post_attachments_attachment_unapproved")."\";");
971			}
972			else
973			{
974				eval("\$attachments .= \"".$templates->get("post_attachments_attachment")."\";");
975			}
976			$attachcount++;
977		}
978		$query = $db->simple_select("attachments", "SUM(filesize) AS ausage", "uid='".$mybb->user['uid']."'");
979		$usage = $db->fetch_array($query);
980		if($usage['ausage'] > ($mybb->usergroup['attachquota']*1024) && $mybb->usergroup['attachquota'] != 0)
981		{
982			$noshowattach = 1;
983		}
984		if($mybb->usergroup['attachquota'] == 0)
985		{
986			$friendlyquota = $lang->unlimited;
987		}
988		else
989		{
990			$friendlyquota = get_friendly_size($mybb->usergroup['attachquota']*1024);
991		}
992		$lang->attach_quota = $lang->sprintf($lang->attach_quota, $friendlyquota);
993
994		$link_viewattachments = '';
995		if($usage['ausage'] !== NULL)
996		{
997			$friendlyusage = get_friendly_size($usage['ausage']);
998			$lang->attach_usage = $lang->sprintf($lang->attach_usage, $friendlyusage);
999			eval("\$link_viewattachments = \"".$templates->get("post_attachments_viewlink")."\";");
1000		}
1001		else
1002		{
1003			$lang->attach_usage = "";
1004		}
1005
1006		$attach_add_options = '';
1007		if($mybb->settings['maxattachments'] == 0 || ($mybb->settings['maxattachments'] != 0 && $attachcount < $mybb->settings['maxattachments']) && !isset($noshowattach))
1008		{
1009			eval("\$attach_add_options = \"".$templates->get("post_attachments_add")."\";");
1010		}
1011
1012		$attach_update_options = '';
1013		if(($mybb->usergroup['caneditattachments'] || $forumpermissions['caneditattachments']) && $attachcount > 0)
1014		{
1015			eval("\$attach_update_options = \"".$templates->get("post_attachments_update")."\";");
1016		}
1017
1018		if($attach_add_options || $attach_update_options)
1019		{
1020			eval("\$newattach = \"".$templates->get("post_attachments_new")."\";");
1021		}
1022		eval("\$attachbox = \"".$templates->get("post_attachments")."\";");
1023
1024		$bgcolor = alt_trow();
1025	}
1026	else
1027	{
1028		$attachbox = '';
1029	}
1030
1031	if($mybb->user['uid'])
1032	{
1033		eval("\$savedraftbutton = \"".$templates->get("post_savedraftbutton", 1, 0)."\";");
1034	}
1035
1036	$captcha = '';
1037
1038	// Show captcha image for guests if enabled
1039	if($mybb->settings['captchaimage'] && !$mybb->user['uid'])
1040	{
1041		$correct = false;
1042		require_once MYBB_ROOT.'inc/class_captcha.php';
1043		$post_captcha = new captcha(false, "post_captcha");
1044
1045		if((!empty($mybb->input['previewpost']) || $hide_captcha == true) && $post_captcha->type == 1)
1046		{
1047			// If previewing a post - check their current captcha input - if correct, hide the captcha input area
1048			// ... but only if it's a default one, reCAPTCHA and Are You a Human must be filled in every time due to draconian limits
1049			if($post_captcha->validate_captcha() == true)
1050			{
1051				$correct = true;
1052
1053				// Generate a hidden list of items for our captcha
1054				$captcha = $post_captcha->build_hidden_captcha();
1055			}
1056		}
1057
1058		if(!$correct)
1059		{
1060 			if($post_captcha->type == captcha::DEFAULT_CAPTCHA)
1061			{
1062				$post_captcha->build_captcha();
1063			}
1064			elseif(in_array($post_captcha->type, array(captcha::NOCAPTCHA_RECAPTCHA, captcha::RECAPTCHA_INVISIBLE, captcha::RECAPTCHA_V3)))
1065			{
1066				$post_captcha->build_recaptcha();
1067			}
1068			elseif(in_array($post_captcha->type, array(captcha::HCAPTCHA, captcha::HCAPTCHA_INVISIBLE)))
1069			{
1070				$post_captcha->build_hcaptcha();
1071			}
1072		}
1073		else if($correct && (in_array($post_captcha->type, array(captcha::NOCAPTCHA_RECAPTCHA, captcha::RECAPTCHA_INVISIBLE, captcha::RECAPTCHA_V3))))
1074		{
1075			$post_captcha->build_recaptcha();
1076		}
1077		else if($correct && (in_array($post_captcha->type, array(captcha::HCAPTCHA, captcha::HCAPTCHA_INVISIBLE))))
1078		{
1079			$post_captcha->build_hcaptcha();
1080		}
1081
1082		if($post_captcha->html)
1083		{
1084			$captcha = $post_captcha->html;
1085		}
1086	}
1087
1088	if($forumpermissions['canpostpolls'] != 0)
1089	{
1090		$lang->max_options = $lang->sprintf($lang->max_options, $mybb->settings['maxpolloptions']);
1091		eval("\$pollbox = \"".$templates->get("newthread_postpoll")."\";");
1092	}
1093
1094	// Do we have any forum rules to show for this forum?
1095	$forumrules = '';
1096	if($forum['rulestype'] >= 2 && $forum['rules'])
1097	{
1098		if(!$forum['rulestitle'])
1099		{
1100			$forum['rulestitle'] = $lang->sprintf($lang->forum_rules, $forum['name']);
1101		}
1102
1103		if(!$parser)
1104		{
1105			require_once MYBB_ROOT.'inc/class_parser.php';
1106			$parser = new postParser;
1107		}
1108
1109		$rules_parser = array(
1110			"allow_html" => 1,
1111			"allow_mycode" => 1,
1112			"allow_smilies" => 1,
1113			"allow_imgcode" => 1
1114		);
1115
1116		$forum['rules'] = $parser->parse_message($forum['rules'], $rules_parser);
1117		$foruminfo = $forum;
1118
1119		if($forum['rulestype'] == 3)
1120		{
1121			eval("\$forumrules = \"".$templates->get("forumdisplay_rules")."\";");
1122		}
1123		else if($forum['rulestype'] == 2)
1124		{
1125			eval("\$forumrules = \"".$templates->get("forumdisplay_rules_link")."\";");
1126		}
1127	}
1128
1129	$moderation_notice = '';
1130	if(!is_moderator($forum['fid'], "canapproveunapproveattachs"))
1131	{
1132		if($forumpermissions['modattachments'] == 1  && $forumpermissions['canpostattachments'] != 0)
1133		{
1134			$moderation_text = $lang->moderation_forum_attachments;
1135			eval('$moderation_notice = "'.$templates->get('global_moderation_notice').'";');
1136		}
1137	}
1138
1139	if(!is_moderator($forum['fid'], "canapproveunapprovethreads"))
1140	{
1141		if($forumpermissions['modthreads'] == 1)
1142		{
1143			$moderation_text = $lang->moderation_forum_thread;
1144			eval('$moderation_notice = "'.$templates->get('global_moderation_notice').'";');
1145		}
1146	}
1147
1148	if(!is_moderator($forum['fid'], "canapproveunapproveposts"))
1149	{
1150		if($mybb->user['moderateposts'] == 1)
1151		{
1152			$moderation_text = $lang->moderation_user_posts;
1153			eval('$moderation_notice = "'.$templates->get('global_moderation_notice').'";');
1154		}
1155	}
1156
1157	$php_max_upload_size = get_php_upload_limit();
1158	$php_max_file_uploads = (int)ini_get('max_file_uploads');
1159	eval("\$post_javascript = \"".$templates->get("post_javascript")."\";");
1160
1161	$plugins->run_hooks("newthread_end");
1162
1163	$forum['name'] = strip_tags($forum['name']);
1164	$lang->newthread_in = $lang->sprintf($lang->newthread_in, $forum['name']);
1165
1166	eval("\$newthread = \"".$templates->get("newthread")."\";");
1167	output_page($newthread);
1168}
1169