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
11$working_dir = dirname(__FILE__);
12if(!$working_dir)
13{
14	$working_dir = '.';
15}
16
17$shutdown_queries = $shutdown_functions = array();
18
19// Load main MyBB core file which begins all of the magic
20require_once $working_dir.'/inc/init.php';
21
22// Read the usergroups cache as well as the moderators cache
23$groupscache = $cache->read('usergroups');
24
25// If the groups cache doesn't exist, update it and re-read it
26if(!is_array($groupscache))
27{
28	$cache->update_usergroups();
29	$groupscache = $cache->read('usergroups');
30}
31
32$current_page = my_strtolower(basename(THIS_SCRIPT));
33
34// Send page headers - don't send no-cache headers for attachment.php
35if($current_page != 'attachment.php')
36{
37	send_page_headers();
38}
39
40// Do not use session system for defined pages
41if((isset($mybb->input['action']) && isset($nosession[$mybb->input['action']])) || (isset($mybb->input['thumbnail']) && $current_page == 'attachment.php'))
42{
43	define('NO_ONLINE', 1);
44}
45
46// Create session for this user
47require_once MYBB_ROOT.'inc/class_session.php';
48$session = new session;
49$session->init();
50$mybb->session = &$session;
51
52$mybb->user['ismoderator'] = is_moderator(0, '', $mybb->user['uid']);
53
54// Set our POST validation code here
55$mybb->post_code = generate_post_check();
56
57// Set and load the language
58if(isset($mybb->input['language']) && $lang->language_exists($mybb->get_input('language')) && verify_post_check($mybb->get_input('my_post_key'), true))
59{
60	$mybb->settings['bblanguage'] = $mybb->get_input('language');
61	// If user is logged in, update their language selection with the new one
62	if($mybb->user['uid'])
63	{
64		if(isset($mybb->cookies['mybblang']))
65		{
66			my_unsetcookie('mybblang');
67		}
68
69		$db->update_query('users', array('language' => $db->escape_string($mybb->settings['bblanguage'])), "uid = '{$mybb->user['uid']}'");
70	}
71	// Guest = cookie
72	else
73	{
74		my_setcookie('mybblang', $mybb->settings['bblanguage']);
75	}
76	$mybb->user['language'] = $mybb->settings['bblanguage'];
77}
78// Cookied language!
79else if(!$mybb->user['uid'] && !empty($mybb->cookies['mybblang']) && $lang->language_exists($mybb->cookies['mybblang']))
80{
81	$mybb->settings['bblanguage'] = $mybb->cookies['mybblang'];
82}
83else if(!isset($mybb->settings['bblanguage']))
84{
85	$mybb->settings['bblanguage'] = 'english';
86}
87
88// Load language
89$lang->set_language($mybb->settings['bblanguage']);
90$lang->load('global');
91$lang->load('messages');
92
93// Wipe lockout cookie if enough time has passed
94if(isset($mybb->cookies['lockoutexpiry']) && $mybb->cookies['lockoutexpiry'] < TIME_NOW)
95{
96	my_unsetcookie('lockoutexpiry');
97}
98
99// Run global_start plugin hook now that the basics are set up
100$plugins->run_hooks('global_start');
101
102if(function_exists('mb_internal_encoding') && !empty($lang->settings['charset']))
103{
104	@mb_internal_encoding($lang->settings['charset']);
105}
106
107// Select the board theme to use.
108$loadstyle = '';
109$load_from_forum = $load_from_user = 0;
110$style = array();
111
112// The user used our new quick theme changer
113if(isset($mybb->input['theme']) && verify_post_check($mybb->get_input('my_post_key'), true))
114{
115	// Set up user handler.
116	require_once MYBB_ROOT.'inc/datahandlers/user.php';
117	$userhandler = new UserDataHandler('update');
118
119	$user = array(
120		'uid'	=> $mybb->user['uid'],
121		'style'	=> $mybb->get_input('theme', MyBB::INPUT_INT),
122		'usergroup'	=> $mybb->user['usergroup'],
123		'additionalgroups'	=> $mybb->user['additionalgroups']
124	);
125
126	$userhandler->set_data($user);
127
128	// validate_user verifies the style if it is set in the data array.
129	if($userhandler->validate_user())
130	{
131		$mybb->user['style'] = $user['style'];
132
133		// If user is logged in, update their theme selection with the new one
134		if($mybb->user['uid'])
135		{
136			if(isset($mybb->cookies['mybbtheme']))
137			{
138				my_unsetcookie('mybbtheme');
139			}
140
141			$userhandler->update_user();
142		}
143		// Guest = cookie
144		else
145		{
146			my_setcookie('mybbtheme', $user['style']);
147		}
148	}
149}
150// Cookied theme!
151else if(!$mybb->user['uid'] && !empty($mybb->cookies['mybbtheme']))
152{
153	$mybb->user['style'] = (int)$mybb->cookies['mybbtheme'];
154}
155
156// This user has a custom theme set in their profile
157if(isset($mybb->user['style']) && (int)$mybb->user['style'] != 0)
158{
159	$mybb->user['style'] = (int)$mybb->user['style'];
160
161	$loadstyle = "tid = '{$mybb->user['style']}'";
162	$load_from_user = 1;
163}
164
165$valid = array(
166	'showthread.php',
167	'forumdisplay.php',
168	'newthread.php',
169	'newreply.php',
170	'ratethread.php',
171	'editpost.php',
172	'polls.php',
173	'sendthread.php',
174	'printthread.php',
175	'moderation.php'
176);
177
178if(in_array($current_page, $valid))
179{
180	cache_forums();
181
182	// If we're accessing a post, fetch the forum theme for it and if we're overriding it
183	if(isset($mybb->input['pid']) && THIS_SCRIPT != "polls.php")
184	{
185		$query = $db->simple_select("posts", "fid", "pid = '{$mybb->input['pid']}'", array("limit" => 1));
186
187		if($db->num_rows($query) > 0 && $fid = $db->fetch_field($query, 'fid'))
188		{
189			$style = $forum_cache[$fid];
190			$load_from_forum = 1;
191		}
192	}
193	// We have a thread id and a forum id, we can easily fetch the theme for this forum
194	else if(isset($mybb->input['tid']))
195	{
196		$query = $db->simple_select('threads', 'fid', "tid = '{$mybb->input['tid']}'", array('limit' => 1));
197
198		if($db->num_rows($query) > 0 && $fid = $db->fetch_field($query, 'fid'))
199		{
200			$style = $forum_cache[$fid];
201			$load_from_forum = 1;
202		}
203	}
204	// If we're accessing poll results, fetch the forum theme for it and if we're overriding it
205	else if(isset($mybb->input['pid']) && THIS_SCRIPT == "polls.php")
206	{
207		$query = $db->query("SELECT t.fid FROM ".TABLE_PREFIX."polls p INNER JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid) WHERE p.pid = '{$mybb->input['pid']}' LIMIT 1");
208
209		if($db->num_rows($query) > 0 && $fid = $db->fetch_field($query, 'fid'))
210		{
211			$style = $forum_cache[$fid];
212			$load_from_forum = 1;
213		}
214	}
215	// We have a forum id - simply load the theme from it
216	else if(isset($mybb->input['fid']) && isset($forum_cache[$mybb->input['fid']]))
217	{
218		$style = $forum_cache[$mybb->input['fid']];
219		$load_from_forum = 1;
220	}
221}
222unset($valid);
223
224// From all of the above, a theme was found
225if(isset($style['style']) && $style['style'] > 0)
226{
227	$style['style'] = (int)$style['style'];
228
229	// This theme is forced upon the user, overriding their selection
230	if($style['overridestyle'] == 1 || !isset($mybb->user['style']))
231	{
232		$loadstyle = "tid = '{$style['style']}'";
233	}
234}
235
236// After all of that no theme? Load the board default
237if(empty($loadstyle))
238{
239	$loadstyle = "def='1'";
240}
241
242// Fetch the theme to load from the cache
243if($loadstyle != "def='1'")
244{
245	$query = $db->simple_select('themes', 'name, tid, properties, stylesheets, allowedgroups', $loadstyle, array('limit' => 1));
246	$theme = $db->fetch_array($query);
247
248	if(isset($theme['tid']) && !$load_from_forum && !is_member($theme['allowedgroups']) && $theme['allowedgroups'] != 'all')
249	{
250		if($load_from_user == 1)
251		{
252			$db->update_query('users', array('style' => 0), "style='{$mybb->user['style']}' AND uid='{$mybb->user['uid']}'");
253		}
254
255		if(isset($mybb->cookies['mybbtheme']))
256		{
257			my_unsetcookie('mybbtheme');
258		}
259
260		$loadstyle = "def='1'";
261	}
262}
263
264if($loadstyle == "def='1'")
265{
266	if(!$cache->read('default_theme'))
267	{
268		$cache->update_default_theme();
269	}
270
271	$theme = $cache->read('default_theme');
272
273	$load_from_forum = $load_from_user = 0;
274}
275
276// No theme was found - we attempt to load the master or any other theme
277if(!isset($theme['tid']) || isset($theme['tid']) && !$theme['tid'])
278{
279	// Missing theme was from a forum, run a query to set any forums using the theme to the default
280	if($load_from_forum == 1)
281	{
282		$db->update_query('forums', array('style' => 0), "style = '{$style['style']}'");
283	}
284	// Missing theme was from a user, run a query to set any users using the theme to the default
285	else if($load_from_user == 1)
286	{
287		$db->update_query('users', array('style' => 0), "style = '{$mybb->user['style']}'");
288	}
289
290	// Attempt to load the master or any other theme if the master is not available
291	$query = $db->simple_select('themes', 'name, tid, properties, stylesheets', '', array('order_by' => 'tid', 'limit' => 1));
292	$theme = $db->fetch_array($query);
293}
294$theme = @array_merge($theme, my_unserialize($theme['properties']));
295
296// Fetch all necessary stylesheets
297$stylesheets = '';
298$theme['stylesheets'] = my_unserialize($theme['stylesheets']);
299$stylesheet_scripts = array("global", basename($_SERVER['PHP_SELF']));
300if(!empty($theme['color']))
301{
302	$stylesheet_scripts[] = $theme['color'];
303}
304$stylesheet_actions = array("global");
305if(!empty($mybb->input['action']))
306{
307	$stylesheet_actions[] = $mybb->get_input('action');
308}
309foreach($stylesheet_scripts as $stylesheet_script)
310{
311	// Load stylesheets for global actions and the current action
312	foreach($stylesheet_actions as $stylesheet_action)
313	{
314		if(!$stylesheet_action)
315		{
316			continue;
317		}
318
319		if(!empty($theme['stylesheets'][$stylesheet_script][$stylesheet_action]))
320		{
321			// Actually add the stylesheets to the list
322			foreach($theme['stylesheets'][$stylesheet_script][$stylesheet_action] as $page_stylesheet)
323			{
324				if(!empty($already_loaded[$page_stylesheet]))
325				{
326					continue;
327				}
328
329				if(strpos($page_stylesheet, 'css.php') !== false)
330				{
331					$stylesheet_url = $mybb->settings['bburl'] . '/' . $page_stylesheet;
332				}
333				else
334				{
335					$stylesheet_url = $mybb->get_asset_url($page_stylesheet);
336					if (file_exists(MYBB_ROOT.$page_stylesheet))
337					{
338						$stylesheet_url .= "?t=".filemtime(MYBB_ROOT.$page_stylesheet);
339					}
340				}
341
342				if($mybb->settings['minifycss'])
343				{
344					$stylesheet_url = str_replace('.css', '.min.css', $stylesheet_url);
345				}
346
347				if(strpos($page_stylesheet, 'css.php') !== false)
348				{
349					// We need some modification to get it working with the displayorder
350					$query_string = parse_url($stylesheet_url, PHP_URL_QUERY);
351					$id = (int) my_substr($query_string, 11);
352					$query = $db->simple_select("themestylesheets", "name", "sid={$id}");
353					$real_name = $db->fetch_field($query, "name");
354					$theme_stylesheets[$real_name] = $id;
355				}
356				else
357				{
358					$theme_stylesheets[basename($page_stylesheet)] = "<link type=\"text/css\" rel=\"stylesheet\" href=\"{$stylesheet_url}\" />\n";
359				}
360
361				$already_loaded[$page_stylesheet] = 1;
362			}
363		}
364	}
365}
366unset($actions);
367
368$css_php_script_stylesheets = array();
369
370if(!empty($theme_stylesheets) && is_array($theme['disporder']))
371{
372	foreach($theme['disporder'] as $style_name => $order)
373	{
374		if(!empty($theme_stylesheets[$style_name]))
375		{
376			if(is_int($theme_stylesheets[$style_name]))
377			{
378				$css_php_script_stylesheets[] = $theme_stylesheets[$style_name];
379			}
380			else
381			{
382				$stylesheets .= $theme_stylesheets[$style_name];
383			}
384		}
385	}
386}
387
388if(!empty($css_php_script_stylesheets))
389{
390	$sheet = $mybb->settings['bburl'] . '/css.php?' . http_build_query(array(
391		'stylesheet' => $css_php_script_stylesheets
392		));
393
394	$stylesheets .= "<link type=\"text/css\" rel=\"stylesheet\" href=\"{$sheet}\" />\n";
395}
396
397// Are we linking to a remote theme server?
398if(my_validate_url($theme['imgdir']))
399{
400	// If a language directory for the current language exists within the theme - we use it
401	if(!empty($mybb->user['language']))
402	{
403		$theme['imglangdir'] = $theme['imgdir'].'/'.$mybb->user['language'];
404	}
405	else
406	{
407		// Check if a custom language directory exists for this theme
408		if(!empty($mybb->settings['bblanguage']))
409		{
410			$theme['imglangdir'] = $theme['imgdir'].'/'.$mybb->settings['bblanguage'];
411		}
412		// Otherwise, the image language directory is the same as the language directory for the theme
413		else
414		{
415			$theme['imglangdir'] = $theme['imgdir'];
416		}
417	}
418}
419else
420{
421	$img_directory = $theme['imgdir'];
422
423	if($mybb->settings['usecdn'] && !empty($mybb->settings['cdnpath']))
424	{
425		$img_directory = rtrim($mybb->settings['cdnpath'], '/') . '/' . ltrim($theme['imgdir'], '/');
426	}
427
428	if(!@is_dir($img_directory))
429	{
430		$theme['imgdir'] = 'images';
431	}
432
433	// If a language directory for the current language exists within the theme - we use it
434	if(!empty($mybb->user['language']) && is_dir($img_directory.'/'.$mybb->user['language']))
435	{
436		$theme['imglangdir'] = $theme['imgdir'].'/'.$mybb->user['language'];
437	}
438	else
439	{
440		// Check if a custom language directory exists for this theme
441		if(is_dir($img_directory.'/'.$mybb->settings['bblanguage']))
442		{
443			$theme['imglangdir'] = $theme['imgdir'].'/'.$mybb->settings['bblanguage'];
444		}
445		// Otherwise, the image language directory is the same as the language directory for the theme
446		else
447		{
448			$theme['imglangdir'] = $theme['imgdir'];
449		}
450	}
451
452	$theme['imgdir'] = $mybb->get_asset_url($theme['imgdir']);
453	$theme['imglangdir'] = $mybb->get_asset_url($theme['imglangdir']);
454}
455
456// Theme logo - is it a relative URL to the forum root? Append bburl
457if(!preg_match("#^(\.\.?(/|$)|([a-z0-9]+)://)#i", $theme['logo']) && substr($theme['logo'], 0, 1) != '/')
458{
459	$theme['logo'] = $mybb->get_asset_url($theme['logo']);
460}
461
462// Load Main Templates and Cached Templates
463if(isset($templatelist))
464{
465	$templatelist .= ',';
466}
467else
468{
469	$templatelist = '';
470}
471
472$templatelist .= "headerinclude,header,footer,gobutton,htmldoctype,header_welcomeblock_member,header_welcomeblock_member_user,header_welcomeblock_member_moderator,header_welcomeblock_member_admin,error";
473$templatelist .= ",global_pending_joinrequests,global_awaiting_activation,nav,nav_sep,nav_bit,nav_sep_active,nav_bit_active,footer_languageselect,footer_themeselect,global_unreadreports,footer_contactus";
474$templatelist .= ",global_boardclosed_warning,global_bannedwarning,error_inline,error_inline_item,error_nopermission_loggedin,error_nopermission,global_pm_alert,header_menu_search,header_menu_portal,redirect,footer_languageselect_option";
475$templatelist .= ",video_dailymotion_embed,video_facebook_embed,video_liveleak_embed,video_metacafe_embed,video_myspacetv_embed,video_mixer_embed,video_vimeo_embed,video_yahoo_embed,video_youtube_embed,debug_summary";
476$templatelist .= ",smilieinsert_row,smilieinsert_row_empty,smilieinsert,smilieinsert_getmore,smilieinsert_smilie,global_board_offline_modal,footer_showteamlink,footer_themeselector,task_image,usercp_themeselector_option,php_warnings";
477$templatelist .= ",mycode_code,mycode_email,mycode_img,mycode_php,mycode_quote_post,mycode_size_int,mycode_url,global_no_permission_modal,global_boardclosed_reason,nav_dropdown,global_remote_avatar_notice,global_modqueue,global_modqueue_notice";
478$templatelist .= ",header_welcomeblock_member_buddy,header_welcomeblock_member_pms,header_welcomeblock_member_search,header_welcomeblock_guest,header_welcomeblock_guest_login_modal,header_welcomeblock_guest_login_modal_lockout";
479$templatelist .= ",header_menu_calendar,header_menu_memberlist,global_dst_detection,header_quicksearch,smilie,modal,modal_button";
480$templates->cache($db->escape_string($templatelist));
481
482// Set the current date and time now
483$datenow = my_date($mybb->settings['dateformat'], TIME_NOW, '', false);
484$timenow = my_date($mybb->settings['timeformat'], TIME_NOW);
485$lang->welcome_current_time = $lang->sprintf($lang->welcome_current_time, $datenow . $lang->comma . $timenow);
486
487// Format the last visit date of this user appropriately
488if(isset($mybb->user['lastvisit']))
489{
490	$lastvisit = my_date('relative', $mybb->user['lastvisit'], '', 2);
491}
492// Otherwise, they've never visited before
493else
494{
495	$lastvisit = $lang->lastvisit_never;
496}
497
498$plugins->run_hooks('global_intermediate');
499
500// If the board is closed and we have a usergroup allowed to view the board when closed, then show board closed warning
501$bbclosedwarning = '';
502if($mybb->settings['boardclosed'] == 1 && $mybb->usergroup['canviewboardclosed'] == 1)
503{
504	eval('$bbclosedwarning = "'.$templates->get('global_boardclosed_warning').'";');
505}
506
507// Prepare the main templates for use
508$admincplink = $modcplink = $usercplink = '';
509
510// Load appropriate welcome block for the current logged in user
511if($mybb->user['uid'] != 0)
512{
513	// User can access the admin cp and we're not hiding admin cp links, fetch it
514	if($mybb->usergroup['cancp'] == 1 && $mybb->config['hide_admin_links'] != 1)
515	{
516		$admin_dir = $config['admin_dir'];
517		eval('$admincplink = "'.$templates->get('header_welcomeblock_member_admin').'";');
518	}
519
520	if($mybb->usergroup['canmodcp'] == 1)
521	{
522		eval('$modcplink = "'.$templates->get('header_welcomeblock_member_moderator').'";');
523	}
524
525	if($mybb->usergroup['canusercp'] == 1)
526	{
527		eval('$usercplink = "'.$templates->get('header_welcomeblock_member_user').'";');
528	}
529
530	// Format the welcome back message
531	$lang->welcome_back = $lang->sprintf($lang->welcome_back, build_profile_link(htmlspecialchars_uni($mybb->user['username']), $mybb->user['uid']), $lastvisit);
532
533	$buddylink = $searchlink = $pmslink = '';
534
535	if(!empty($mybb->user['buddylist']))
536	{
537		eval('$buddylink = "' . $templates->get('header_welcomeblock_member_buddy') . '";');
538	}
539
540	if($mybb->usergroup['cansearch'] == 1)
541	{
542		eval('$searchlink = "'.$templates->get('header_welcomeblock_member_search').'";');
543	}
544
545	// Tell the user their PM usage
546	if($mybb->settings['enablepms'] != 0 && $mybb->usergroup['canusepms'] == 1)
547	{
548		$lang->welcome_pms_usage = $lang->sprintf($lang->welcome_pms_usage, my_number_format($mybb->user['pms_unread']), my_number_format($mybb->user['pms_total']));
549
550		eval('$pmslink = "'.$templates->get('header_welcomeblock_member_pms').'";');
551	}
552
553	eval('$welcomeblock = "'.$templates->get('header_welcomeblock_member').'";');
554}
555// Otherwise, we have a guest
556else
557{
558	switch($mybb->settings['username_method'])
559	{
560		case 0:
561			$login_username = $lang->login_username;
562			break;
563		case 1:
564			$login_username = $lang->login_username1;
565			break;
566		case 2:
567			$login_username = $lang->login_username2;
568			break;
569		default:
570			$login_username = $lang->login_username;
571			break;
572	}
573
574	if(!empty($mybb->cookies['lockoutexpiry']))
575	{
576		$secsleft = (int)($mybb->cookies['lockoutexpiry'] - TIME_NOW);
577		$hoursleft = floor($secsleft / 3600);
578		$minsleft = floor(($secsleft / 60) % 60);
579		$secsleft = floor($secsleft % 60);
580
581		$lang->failed_login_wait = $lang->sprintf($lang->failed_login_wait, $hoursleft, $minsleft, $secsleft);
582
583		eval('$loginform = "'.$templates->get('header_welcomeblock_guest_login_modal_lockout').'";');
584	}
585	else
586	{
587		eval('$loginform = "'.$templates->get('header_welcomeblock_guest_login_modal').'";');
588	}
589
590	eval('$welcomeblock = "'.$templates->get('header_welcomeblock_guest').'";');
591}
592
593// Display menu links and quick search if user has permission
594$menu_search = $menu_memberlist = $menu_portal = $menu_calendar = $quicksearch = '';
595if($mybb->usergroup['cansearch'] == 1)
596{
597	eval('$menu_search = "'.$templates->get('header_menu_search').'";');
598	eval('$quicksearch = "'.$templates->get('header_quicksearch').'";');
599}
600
601if($mybb->settings['enablememberlist'] == 1 && $mybb->usergroup['canviewmemberlist'] == 1)
602{
603	eval('$menu_memberlist = "'.$templates->get('header_menu_memberlist').'";');
604}
605
606if($mybb->settings['enablecalendar'] == 1 && $mybb->usergroup['canviewcalendar'] == 1)
607{
608	eval('$menu_calendar = "'.$templates->get('header_menu_calendar').'";');
609}
610
611if($mybb->settings['portal'] == 1)
612{
613	eval('$menu_portal = "'.$templates->get('header_menu_portal').'";');
614}
615
616// See if there are any pending join requests for group leaders
617$pending_joinrequests = '';
618$groupleaders = $cache->read('groupleaders');
619if($mybb->user['uid'] != 0 && is_array($groupleaders) && array_key_exists($mybb->user['uid'], $groupleaders))
620{
621	$groupleader = $groupleaders[$mybb->user['uid']];
622	$showjoinnotice = false;
623
624	$gids = "'0'";
625	foreach($groupleader as $user)
626	{
627		if($user['canmanagerequests'] != 1)
628		{
629			continue;
630		}
631
632		$user['gid'] = (int)$user['gid'];
633
634		if(!empty($groupscache[$user['gid']]['type']) && $groupscache[$user['gid']]['type'] == 4)
635		{
636			$showjoinnotice = true;
637			$gids .= ",'{$user['gid']}'";
638		}
639	}
640
641	if($showjoinnotice)
642	{
643		$query = $db->simple_select('joinrequests', 'COUNT(uid) as total', "gid IN ({$gids}) AND invite='0'");
644		$total_joinrequests = $db->fetch_field($query, 'total');
645
646		if($total_joinrequests > 0)
647		{
648			if($total_joinrequests == 1)
649			{
650				$lang->pending_joinrequests = $lang->pending_joinrequest;
651			}
652			else
653			{
654				$lang->pending_joinrequests = $lang->sprintf($lang->pending_joinrequests, my_number_format($total_joinrequests));
655			}
656
657			eval('$pending_joinrequests = "'.$templates->get('global_pending_joinrequests').'";');
658		}
659	}
660}
661
662$modnotice = '';
663$moderation_queue = array();
664$can_access_moderationqueue = false;
665
666// This user is a moderator, super moderator or administrator
667if($mybb->usergroup['cancp'] == 1 || ($mybb->user['ismoderator'] && $mybb->usergroup['canmodcp'] == 1 && $mybb->usergroup['canmanagereportedcontent'] == 1))
668{
669	// Only worth checking if we are here because we have ACP permissions and the other condition fails
670	if($mybb->usergroup['cancp'] == 1 && !($mybb->user['ismoderator'] && $mybb->usergroup['canmodcp'] == 1 && $mybb->usergroup['canmanagereportedcontent'] == 1))
671	{
672		// First we check if the user's a super admin: if yes, we don't care about permissions
673		$can_access_moderationqueue = true;
674		$is_super_admin = is_super_admin($mybb->user['uid']);
675		if(!$is_super_admin)
676		{
677			// Include admin functions
678			if(!file_exists(MYBB_ROOT.$mybb->config['admin_dir']."/inc/functions.php"))
679			{
680				$can_access_moderationqueue = false;
681			}
682
683			require_once MYBB_ROOT.$mybb->config['admin_dir']."/inc/functions.php";
684
685			// Verify if we have permissions to access forum-moderation_queue
686			require_once MYBB_ROOT.$mybb->config['admin_dir']."/modules/forum/module_meta.php";
687			if(function_exists("forum_admin_permissions"))
688			{
689				// Get admin permissions
690				$adminperms = get_admin_permissions($mybb->user['uid']);
691
692				$permissions = forum_admin_permissions();
693				if(array_key_exists('moderation_queue', $permissions['permissions']) && $adminperms['forum']['moderation_queue'] != 1)
694				{
695					$can_access_moderationqueue = false;
696				}
697			}
698		}
699	}
700	else
701	{
702		$can_access_moderationqueue = false;
703	}
704
705	if($can_access_moderationqueue || ($mybb->user['ismoderator'] && $mybb->usergroup['canmodcp'] == 1 && $mybb->usergroup['canmanagereportedcontent'] == 1))
706	{
707		// Read the reported content cache
708		$reported = $cache->read('reportedcontent');
709
710		// 0 or more reported items currently exist
711		if($reported['unread'] > 0)
712		{
713			// We want to avoid one extra query for users that can moderate any forum
714			if($mybb->usergroup['cancp'] || $mybb->usergroup['issupermod'])
715			{
716				$unread = (int)$reported['unread'];
717			}
718			else
719			{
720				$unread = 0;
721				$query = $db->simple_select('reportedcontent', 'id3', "reportstatus='0' AND (type = 'post' OR type = '')");
722
723				while($fid = $db->fetch_field($query, 'id3'))
724				{
725					if(is_moderator($fid, "canmanagereportedposts"))
726					{
727						++$unread;
728					}
729				}
730			}
731
732			if($unread > 0)
733			{
734				if($unread == 1)
735				{
736					$lang->unread_reports = $lang->unread_report;
737				}
738				else
739				{
740					$lang->unread_reports = $lang->sprintf($lang->unread_reports, my_number_format($unread));
741				}
742
743				eval('$moderation_queue[] = "'.$templates->get('global_unreadreports', 1, 0).'";');
744			}
745		}
746	}
747}
748
749// Get awaiting moderation queue stats, except if the page is editpost.php,
750// because that page can make changes - (un)approving attachments, or deleting
751// unapproved attachments - that would invalidate anything generated here.
752// Just leave this queue notification blank for editpost.php.
753if(!(defined('THIS_SCRIPT') && THIS_SCRIPT == 'editpost.php') && ($can_access_moderationqueue || ($mybb->user['ismoderator'] && $mybb->usergroup['canmodcp'] == 1 && $mybb->usergroup['canmanagemodqueue'] == 1)))
754{
755	$unapproved_posts = $unapproved_threads = 0;
756	$query = $db->simple_select("posts", "replyto", "visible = 0");
757	while($unapproved = $db->fetch_array($query))
758	{
759		if($unapproved["replyto"] == 0){
760			$unapproved_threads++;
761		} else {
762			$unapproved_posts++;
763		}
764	}
765
766	$query = $db->simple_select("attachments", "COUNT(aid) AS unapprovedattachments", "visible=0");
767	$unapproved_attachments = $db->fetch_field($query, "unapprovedattachments");
768
769	$modqueue_types = array('threads', 'posts', 'attachments');
770
771	foreach($modqueue_types as $modqueue_type)
772	{
773		if(!empty(${'unapproved_'.$modqueue_type}))
774		{
775			if(${'unapproved_'.$modqueue_type} == 1)
776			{
777				$modqueue_message = $lang->{'unapproved_'.substr($modqueue_type, 0, -1)};
778			}
779			else
780			{
781				$modqueue_message = $lang->sprintf($lang->{'unapproved_'.$modqueue_type}, my_number_format(${'unapproved_'.$modqueue_type}));
782			}
783
784			eval('$moderation_queue[] = "'.$templates->get('global_modqueue', 1, 0).'";');
785		}
786	}
787}
788
789if(!empty($moderation_queue))
790{
791	$moderation_queue_last = array_pop($moderation_queue);
792	if(empty($moderation_queue))
793	{
794		$moderation_queue = $moderation_queue_last;
795	}
796	else
797	{
798		$moderation_queue = implode($lang->comma, $moderation_queue).' '.$lang->and.' '.$moderation_queue_last;
799	}
800	$moderation_queue = $lang->sprintf($lang->mod_notice, $moderation_queue);
801
802	eval('$modnotice = "'.$templates->get('global_modqueue_notice').'";');
803}
804
805// Got a character set?
806$charset = 'UTF-8';
807if(isset($lang->settings['charset']) && $lang->settings['charset'])
808{
809	$charset = $lang->settings['charset'];
810}
811
812// Is this user apart of a banned group?
813$bannedwarning = '';
814if($mybb->usergroup['isbannedgroup'] == 1)
815{
816	// Format their ban lift date and reason appropriately
817	if(!empty($mybb->user['banned']))
818	{
819		if(!empty($mybb->user['banlifted']))
820		{
821			$banlift = my_date('normal', $mybb->user['banlifted']);
822		}
823		else
824		{
825			$banlift = $lang->banned_lifted_never;
826		}
827	}
828	else
829	{
830		$banlift = $lang->unknown;
831	}
832
833	if(!empty($mybb->user['banreason']))
834	{
835		$reason = htmlspecialchars_uni($mybb->user['banreason']);
836	}
837	else
838	{
839		$reason = $lang->unknown;
840	}
841
842	// Display a nice warning to the user
843	eval('$bannedwarning = "'.$templates->get('global_bannedwarning').'";');
844}
845
846$lang->ajax_loading = str_replace("'", "\\'", $lang->ajax_loading);
847
848// Check if this user has a new private message.
849$pm_notice = '';
850if(isset($mybb->user['pmnotice']) && $mybb->user['pmnotice'] == 2 && $mybb->user['pms_unread'] > 0 && $mybb->settings['enablepms'] != 0 && $mybb->usergroup['canusepms'] != 0 && $mybb->usergroup['canview'] != 0 && ($current_page != "private.php" || $mybb->get_input('action') != "read"))
851{
852	if(!isset($parser))
853	{
854		require_once MYBB_ROOT.'inc/class_parser.php';
855		$parser = new postParser;
856	}
857
858	$query = $db->query("
859		SELECT pm.subject, pm.pmid, fu.username AS fromusername, fu.uid AS fromuid
860		FROM ".TABLE_PREFIX."privatemessages pm
861		LEFT JOIN ".TABLE_PREFIX."users fu on (fu.uid=pm.fromid)
862		WHERE pm.folder = '1' AND pm.uid = '{$mybb->user['uid']}' AND pm.status = '0'
863		ORDER BY pm.dateline DESC
864		LIMIT 1
865	");
866
867	$pm = $db->fetch_array($query);
868	$pm['subject'] = $parser->parse_badwords($pm['subject']);
869
870	if($pm['fromuid'] == 0)
871	{
872		$pm['fromusername'] = $lang->mybb_engine;
873		$user_text = $pm['fromusername'];
874	}
875	else
876	{
877		$pm['fromusername'] = htmlspecialchars_uni($pm['fromusername']);
878		$user_text = build_profile_link($pm['fromusername'], $pm['fromuid']);
879	}
880
881	if($mybb->user['pms_unread'] == 1)
882	{
883		$privatemessage_text = $lang->sprintf($lang->newpm_notice_one, $user_text, $mybb->settings['bburl'], $pm['pmid'], htmlspecialchars_uni($pm['subject']));
884	}
885	else
886	{
887		$privatemessage_text = $lang->sprintf($lang->newpm_notice_multiple, $mybb->user['pms_unread'], $user_text, $mybb->settings['bburl'], $pm['pmid'], htmlspecialchars_uni($pm['subject']));
888	}
889	eval('$pm_notice = "'.$templates->get('global_pm_alert').'";');
890}
891
892$remote_avatar_notice = '';
893if(isset($mybb->user['avatartype']) && ($mybb->user['avatartype'] === 'remote' || $mybb->user['avatartype'] === 'gravatar') && !$mybb->settings['allowremoteavatars'])
894{
895	eval('$remote_avatar_notice = "'.$templates->get('global_remote_avatar_notice').'";');
896}
897
898$awaitingusers = '';
899if($mybb->settings['awactialert'] == 1 && $mybb->usergroup['cancp'] == 1)
900{
901	$awaitingusers = $cache->read('awaitingactivation');
902
903	if(isset($awaitingusers['time']) && $awaitingusers['time'] + 86400 < TIME_NOW)
904	{
905		$cache->update_awaitingactivation();
906		$awaitingusers = $cache->read('awaitingactivation');
907	}
908
909	if(!empty($awaitingusers['users']))
910	{
911		$awaitingusers = (int)$awaitingusers['users'];
912	}
913	else
914	{
915		$awaitingusers = 0;
916	}
917
918	if($awaitingusers < 1)
919	{
920		$awaitingusers = 0;
921	}
922	else
923	{
924		$awaitingusers = my_number_format($awaitingusers);
925	}
926
927	if($awaitingusers > 0)
928	{
929		if($awaitingusers == 1)
930		{
931			$awaiting_message = $lang->awaiting_message_single;
932		}
933		else
934		{
935			$awaiting_message = $lang->sprintf($lang->awaiting_message_plural, $awaitingusers);
936		}
937
938		if($admincplink)
939		{
940			$awaiting_message .= $lang->sprintf($lang->awaiting_message_link, $mybb->settings['bburl'], $admin_dir);
941		}
942
943		eval('$awaitingusers = "'.$templates->get('global_awaiting_activation').'";');
944	}
945	else
946	{
947		$awaitingusers = '';
948	}
949}
950
951$jsTemplates = array();
952foreach (array('modal', 'modal_button') as $template) {
953	eval('$jsTemplates["'.$template.'"] = "'.$templates->get($template, 1, 0).'";');
954	$jsTemplates[$template] = str_replace(array("\n","\r"), array("\\\n", ""), addslashes($jsTemplates[$template]));
955}
956
957// Set up some of the default templates
958eval('$headerinclude = "'.$templates->get('headerinclude').'";');
959eval('$gobutton = "'.$templates->get('gobutton').'";');
960eval('$htmldoctype = "'.$templates->get('htmldoctype', 1, 0).'";');
961eval('$header = "'.$templates->get('header').'";');
962
963$copy_year = my_date('Y', TIME_NOW);
964
965// Are we showing version numbers in the footer?
966$mybbversion = '';
967if($mybb->settings['showvernum'] == 1)
968{
969	$mybbversion = ' '.$mybb->version;
970}
971
972// Check to see if we have any tasks to run
973$task_image = '';
974$task_cache = $cache->read('tasks');
975if(!$task_cache['nextrun'])
976{
977	$task_cache['nextrun'] = TIME_NOW;
978}
979
980if($task_cache['nextrun'] <= TIME_NOW)
981{
982	eval("\$task_image = \"".$templates->get("task_image")."\";");
983}
984
985// Post code
986$post_code_string = '';
987if($mybb->user['uid'])
988{
989	$post_code_string = '&amp;my_post_key='.$mybb->post_code;
990}
991
992// Are we showing the quick language selection box?
993$lang_select = $lang_options = '';
994if($mybb->settings['showlanguageselect'] != 0)
995{
996	$languages = $lang->get_languages();
997
998	if(count($languages) > 1)
999	{
1000		foreach($languages as $key => $language)
1001		{
1002			$language = htmlspecialchars_uni($language);
1003
1004			// Current language matches
1005			if($lang->language == $key)
1006			{
1007				$selected = " selected=\"selected\"";
1008			}
1009			else
1010			{
1011				$selected = '';
1012			}
1013
1014			eval('$lang_options .= "'.$templates->get('footer_languageselect_option').'";');
1015		}
1016
1017		$lang_redirect_url = get_current_location(true, 'language');
1018		eval('$lang_select = "'.$templates->get('footer_languageselect').'";');
1019	}
1020}
1021
1022// Are we showing the quick theme selection box?
1023$theme_select = $theme_options = '';
1024if($mybb->settings['showthemeselect'] != 0)
1025{
1026	if(isset($mybb->user['style']))
1027	{
1028		$selected = $mybb->user['style'];
1029	}
1030	else
1031	{
1032		$selected = -1;
1033	}
1034
1035	$theme_options = build_theme_select("theme", $selected, 0, '', false, true);
1036
1037	if(!empty($theme_options))
1038	{
1039		$theme_redirect_url = get_current_location(true, 'theme');
1040		eval('$theme_select = "'.$templates->get('footer_themeselect').'";');
1041	}
1042}
1043
1044$showteamlink = '';
1045if($mybb->settings['enableshowteam'] != 0)
1046{
1047	eval('$showteamlink = "'.$templates->get('footer_showteamlink').'";');
1048}
1049
1050// If we use the contact form, show 'Contact Us' link when appropriate
1051$contact_us = '';
1052if(($mybb->settings['contactlink'] == "contact.php" && $mybb->settings['contact'] == 1 && ($mybb->settings['contact_guests'] != 1 && $mybb->user['uid'] == 0 || $mybb->user['uid'] > 0)) || $mybb->settings['contactlink'] != "contact.php")
1053{
1054	if(!my_validate_url($mybb->settings['contactlink'], true) && my_substr($mybb->settings['contactlink'], 0, 7) != 'mailto:')
1055	{
1056		$mybb->settings['contactlink'] = $mybb->settings['bburl'].'/'.$mybb->settings['contactlink'];
1057	}
1058
1059	eval('$contact_us = "'.$templates->get('footer_contactus').'";');
1060}
1061
1062// DST Auto detection enabled?
1063$auto_dst_detection = '';
1064if($mybb->user['uid'] > 0 && $mybb->user['dstcorrection'] == 2)
1065{
1066	$timezone = (float)$mybb->user['timezone'] + $mybb->user['dst'];
1067	eval('$auto_dst_detection = "'.$templates->get('global_dst_detection').'";');
1068}
1069
1070eval('$footer = "'.$templates->get('footer').'";');
1071
1072// Add our main parts to the navigation
1073$navbits = array();
1074$navbits[0]['name'] = $mybb->settings['bbname_orig'];
1075$navbits[0]['url'] = $mybb->settings['bburl'].'/index.php';
1076
1077// Set the link to the archive.
1078$archive_url = build_archive_link();
1079
1080// Check banned ip addresses
1081if(is_banned_ip($session->ipaddress, true))
1082{
1083	if($mybb->user['uid'])
1084	{
1085		$db->delete_query('sessions', "ip = ".$db->escape_binary($session->packedip)." OR uid='{$mybb->user['uid']}'");
1086	}
1087	else
1088	{
1089		$db->delete_query('sessions', "ip = ".$db->escape_binary($session->packedip));
1090	}
1091	error($lang->error_banned);
1092}
1093
1094$closed_bypass = array(
1095	'member.php' => array(
1096		'login',
1097		'do_login',
1098		'logout',
1099	),
1100	'captcha.php',
1101	'contact.php',
1102);
1103
1104// If the board is closed, the user is not an administrator and they're not trying to login, show the board closed message
1105if($mybb->settings['boardclosed'] == 1 && $mybb->usergroup['canviewboardclosed'] != 1 && !in_array($current_page, $closed_bypass) && (!is_array($closed_bypass[$current_page]) || !in_array($mybb->get_input('action'), $closed_bypass[$current_page])))
1106{
1107	// Show error
1108	if(!$mybb->settings['boardclosed_reason'])
1109	{
1110		$mybb->settings['boardclosed_reason'] = $lang->boardclosed_reason;
1111	}
1112
1113	eval('$reason = "'.$templates->get('global_boardclosed_reason').'";');
1114	$lang->error_boardclosed .= $reason;
1115
1116	if(!$mybb->get_input('modal'))
1117	{
1118		error($lang->error_boardclosed);
1119	}
1120	else
1121	{
1122		$output = '';
1123		eval('$output = "'.$templates->get('global_board_offline_modal', 1, 0).'";');
1124		echo($output);
1125	}
1126	exit;
1127}
1128
1129$force_bypass = array(
1130	'member.php' => array(
1131		'login',
1132		'do_login',
1133		'logout',
1134		'register',
1135		'do_register',
1136		'lostpw',
1137		'do_lostpw',
1138		'activate',
1139		'resendactivation',
1140		'do_resendactivation',
1141		'resetpassword',
1142	),
1143	'captcha.php',
1144	'contact.php',
1145);
1146
1147// If the board forces user to login/register, and the user is a guest, show the force login message
1148if($mybb->settings['forcelogin'] == 1 && $mybb->user['uid'] == 0 && !in_array($current_page, $force_bypass) && (!is_array($force_bypass[$current_page]) || !in_array($mybb->get_input('action'), $force_bypass[$current_page])))
1149{
1150	// Show error
1151	error_no_permission();
1152	exit;
1153}
1154
1155// Load Limiting
1156if($mybb->usergroup['cancp'] != 1 && $mybb->settings['load'] > 0 && ($load = get_server_load()) && $load != $lang->unknown && $load > $mybb->settings['load'])
1157{
1158	// User is not an administrator and the load limit is higher than the limit, show an error
1159	error($lang->error_loadlimit);
1160}
1161
1162// If there is a valid referrer in the URL, cookie it
1163if(!$mybb->user['uid'] && $mybb->settings['usereferrals'] == 1 && (isset($mybb->input['referrer']) || isset($mybb->input['referrername'])))
1164{
1165	if(isset($mybb->input['referrername']))
1166	{
1167		$condition = "username = '".$db->escape_string($mybb->get_input('referrername'))."'";
1168	}
1169	else
1170	{
1171		$condition = "uid = '".$mybb->get_input('referrer', MyBB::INPUT_INT)."'";
1172	}
1173
1174	$query = $db->simple_select('users', 'uid', $condition, array('limit' => 1));
1175	$referrer = $db->fetch_array($query);
1176
1177	if(!empty($referrer) && $referrer['uid'])
1178	{
1179		my_setcookie('mybb[referrer]', $referrer['uid']);
1180	}
1181}
1182
1183$output = '';
1184$notallowed = false;
1185if($mybb->usergroup['canview'] != 1)
1186{
1187	// Check pages allowable even when not allowed to view board
1188	if(defined('ALLOWABLE_PAGE'))
1189	{
1190		if(is_string(ALLOWABLE_PAGE))
1191		{
1192			$allowable_actions = explode(',', ALLOWABLE_PAGE);
1193			if(!in_array($mybb->get_input('action'), $allowable_actions))
1194			{
1195				$notallowed = true;
1196			}
1197
1198			unset($allowable_actions);
1199		}
1200		else if(ALLOWABLE_PAGE !== 1)
1201		{
1202			$notallowed = true;
1203		}
1204	}
1205	else
1206	{
1207		$notallowed = true;
1208	}
1209
1210	if($notallowed == true)
1211	{
1212		if(!$mybb->get_input('modal'))
1213		{
1214			error_no_permission();
1215		}
1216		else
1217		{
1218			eval('$output = "'.$templates->get('global_no_permission_modal', 1, 0).'";');
1219			echo($output);
1220			exit;
1221		}
1222	}
1223}
1224
1225// Find out if this user of ours is using a banned email address.
1226// If they are, redirect them to change it
1227if($mybb->user['uid'] && is_banned_email($mybb->user['email']) && $mybb->settings['emailkeep'] != 1)
1228{
1229	if(
1230		!(THIS_SCRIPT == 'usercp.php' && in_array($mybb->get_input('action'), array('email', 'do_email'))) &&
1231		!(THIS_SCRIPT == 'member.php' && $mybb->get_input('action') == 'activate')
1232	)
1233	{
1234		redirect('usercp.php?action=email');
1235	}
1236	else if($mybb->request_method != 'post')
1237	{
1238		$banned_email_error = inline_error(array($lang->banned_email_warning));
1239	}
1240}
1241
1242// work out which items the user has collapsed
1243$collapse = $collapsed = $collapsedimg = $collapsedthead = array();
1244
1245if(!empty($mybb->cookies['collapsed']))
1246{
1247	$colcookie = $mybb->cookies['collapsed'];
1248
1249	// Preserve and don't unset $collapse, will be needed globally throughout many pages
1250	$collapse = explode("|", $colcookie);
1251	foreach($collapse as $val)
1252	{
1253		$collapsed[$val."_e"] = "display: none;";
1254		$collapsedimg[$val] = "_collapsed";
1255		$collapsedthead[$val] = " thead_collapsed";
1256	}
1257}
1258
1259// Run hooks for end of global.php
1260$plugins->run_hooks('global_end');
1261
1262$globaltime = $maintimer->getTime();
1263