Passed
Pull Request — release-2.1 (#6891)
by John
05:02
created

index.php (4 issues)

1
<?php
2
3
/**
4
 * This, as you have probably guessed, is the crux on which SMF functions.
5
 * Everything should start here, so all the setup and security is done
6
 * properly.  The most interesting part of this file is the action array in
7
 * the smf_main() function.  It is formatted as so:
8
 * 	'action-in-url' => array('Source-File.php', 'FunctionToCall'),
9
 *
10
 * Then, you can access the FunctionToCall() function from Source-File.php
11
 * with the URL index.php?action=action-in-url.  Relatively simple, no?
12
 *
13
 * Simple Machines Forum (SMF)
14
 *
15
 * @package SMF
16
 * @author Simple Machines https://www.simplemachines.org
17
 * @copyright 2021 Simple Machines and individual contributors
18
 * @license https://www.simplemachines.org/about/smf/license.php BSD
19
 *
20
 * @version 2.1 RC4
21
 */
22
23
// Get everything started up...
24
define('SMF', 1);
25
define('SMF_VERSION', '2.1 RC4');
26
define('SMF_FULL_VERSION', 'SMF ' . SMF_VERSION);
27
define('SMF_SOFTWARE_YEAR', '2021');
28
29
define('JQUERY_VERSION', '3.6.0');
30
define('POSTGRE_TITLE', 'PostgreSQL');
31
define('MYSQL_TITLE', 'MySQL');
32
define('SMF_USER_AGENT', 'Mozilla/5.0 (' . php_uname('s') . ' ' . php_uname('m') . ') AppleWebKit/605.1.15 (KHTML, like Gecko)  SMF/' . strtr(SMF_VERSION, ' ', '.'));
33
34
if (!defined('TIME_START'))
35
	define('TIME_START', microtime(true));
36
37
// If anything goes wrong loading Settings.php, make sure the admin knows it.
38
error_reporting(E_ALL);
39
40
// This makes it so headers can be sent!
41
ob_start();
42
43
// Do some cleaning, just in case.
44
foreach (array('db_character_set', 'cachedir') as $variable)
45
	unset($GLOBALS[$variable]);
46
47
// Load the settings...
48
require_once(dirname(__FILE__) . '/Settings.php');
49
50
// Devs want all error messages, but others don't.
51
error_reporting(!empty($db_show_debug) ? E_ALL : E_ALL & ~E_DEPRECATED);
52
53
// Ensure there are no trailing slashes in these variables.
54
foreach (array('boardurl', 'boarddir', 'sourcedir', 'packagesdir', 'taskddir', 'cachedir') as $variable)
55
	if (!empty($GLOBALS[$variable]))
56
		$GLOBALS[$variable] = rtrim($GLOBALS[$variable], "\\/");
57
58
// Make absolutely sure the cache directory is defined and writable.
59
if (empty($cachedir) || !is_dir($cachedir) || !is_writable($cachedir))
60
{
61
	if (is_dir($boarddir . '/cache') && is_writable($boarddir . '/cache'))
62
		$cachedir = $boarddir . '/cache';
63
64
	else
65
	{
66
		$cachedir = sys_get_temp_dir() . '/smf_cache_' . md5($boarddir);
67
68
		@mkdir($cachedir, 0750);
69
	}
70
}
71
72
// Without those we can't go anywhere
73
require_once($sourcedir . '/QueryString.php');
74
require_once($sourcedir . '/Subs.php');
75
require_once($sourcedir . '/Subs-Auth.php');
76
require_once($sourcedir . '/Errors.php');
77
require_once($sourcedir . '/Load.php');
78
require_once($sourcedir . '/Security.php');
79
80
// If $maintenance is set specifically to 2, then we're upgrading or something.
81
if (!empty($maintenance) &&  2 === $maintenance)
82
{
83
	display_maintenance_message();
84
}
85
86
// Create a variable to store some SMF specific functions in.
87
$smcFunc = array();
88
89
// Initiate the database connection and define some database functions to use.
90
loadDatabase();
91
92
/**
93
 * An autoloader for certain classes.
94
 *
95
 * @param string $class The fully-qualified class name.
96
 */
97
spl_autoload_register(function ($class) use ($sourcedir)
98
{
99
	$classMap = array(
100
		'ReCaptcha\\' => 'ReCaptcha/',
101
		'MatthiasMullie\\Minify\\' => 'minify/src/',
102
		'MatthiasMullie\\PathConverter\\' => 'minify/path-converter/src/',
103
		'SMF\\Cache\\' => 'Cache/',
104
	);
105
106
	// Do any third-party scripts want in on the fun?
107
	call_integration_hook('integrate_autoload', array(&$classMap));
108
109
	foreach ($classMap as $prefix => $dirName)
110
	{
111
		// does the class use the namespace prefix?
112
		$len = strlen($prefix);
113
		if (strncmp($prefix, $class, $len) !== 0)
114
		{
115
			continue;
116
		}
117
118
		// get the relative class name
119
		$relativeClass = substr($class, $len);
120
121
		// replace the namespace prefix with the base directory, replace namespace
122
		// separators with directory separators in the relative class name, append
123
		// with .php
124
		$fileName = $dirName . strtr($relativeClass, '\\', '/') . '.php';
125
126
		// if the file exists, require it
127
		if (file_exists($fileName = $sourcedir . '/' . $fileName))
128
		{
129
			require_once $fileName;
130
131
			return;
132
		}
133
	}
134
});
135
136
// Load the settings from the settings table, and perform operations like optimizing.
137
$context = array();
138
reloadSettings();
139
140
// Clean the request variables, add slashes, etc.
141
cleanRequest();
142
143
// Seed the random generator.
144
if (empty($modSettings['rand_seed']) || mt_rand(1, 250) == 69)
145
	smf_seed_generator();
146
147
// And important includes.
148
require_once($sourcedir . '/Session.php');
149
require_once($sourcedir . '/Logging.php');
150
require_once($sourcedir . '/Class-BrowserDetect.php');
151
152
// If a Preflight is occurring, lets stop now.
153
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS')
154
{
155
	send_http_status(204);
156
	die;
157
}
158
159
// Before we get carried away, are we doing a scheduled task? If so save CPU cycles by jumping out!
160
if (isset($_GET['scheduled']))
161
{
162
	require_once($sourcedir . '/ScheduledTasks.php');
163
	AutoTask();
164
}
165
166
// Check if compressed output is enabled, supported, and not already being done.
167
if (!empty($modSettings['enableCompressedOutput']) && !headers_sent())
168
{
169
	// If zlib is being used, turn off output compression.
170
	if (ini_get('zlib.output_compression') >= 1 || ini_get('output_handler') == 'ob_gzhandler')
171
		$modSettings['enableCompressedOutput'] = '0';
172
173
	else
174
	{
175
		ob_end_clean();
176
		ob_start('ob_gzhandler');
177
	}
178
}
179
180
// Register an error handler.
181
set_error_handler('smf_error_handler');
182
183
// Start the session. (assuming it hasn't already been.)
184
loadSession();
185
186
// What function shall we execute? (done like this for memory's sake.)
187
call_user_func(smf_main());
188
189
// Call obExit specially; we're coming from the main area ;).
190
obExit(null, null, true);
191
192
/**
193
 * The main dispatcher.
194
 * This delegates to each area.
195
 *
196
 * @return array|string|void An array containing the file to include and name of function to call, the name of a function to call or dies with a fatal_lang_error if we couldn't find anything to do.
197
 */
198
function smf_main()
199
{
200
	global $modSettings, $settings, $user_info, $board, $topic;
201
	global $board_info, $maintenance, $sourcedir, $should_log;
202
203
	// Special case: session keep-alive, output a transparent pixel.
204
	if (isset($_GET['action']) && $_GET['action'] == 'keepalive')
205
	{
206
		header('content-type: image/gif');
207
		die("\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00\x21\xF9\x04\x01\x00\x00\x00\x00\x2C\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3B");
208
	}
209
210
	// We should set our security headers now.
211
	frameOptionsHeader();
0 ignored issues
show
The function frameOptionsHeader was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

211
	/** @scrutinizer ignore-call */ 
212
 frameOptionsHeader();
Loading history...
212
213
	// Set our CORS policy.
214
	corsPolicyHeader();
0 ignored issues
show
The function corsPolicyHeader was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

214
	/** @scrutinizer ignore-call */ 
215
 corsPolicyHeader();
Loading history...
215
216
	// Load the user's cookie (or set as guest) and load their settings.
217
	loadUserSettings();
218
219
	// Load the current board's information.
220
	loadBoard();
221
222
	// Load the current user's permissions.
223
	loadPermissions();
224
225
	// Attachments don't require the entire theme to be loaded.
226
	if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'dlattach' && empty($maintenance))
227
		detectBrowser();
228
	// Load the current theme.  (note that ?theme=1 will also work, may be used for guest theming.)
229
	else
230
		loadTheme();
231
232
	// Check if the user should be disallowed access.
233
	is_not_banned();
0 ignored issues
show
The function is_not_banned was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

233
	/** @scrutinizer ignore-call */ 
234
 is_not_banned();
Loading history...
234
235
	// If we are in a topic and don't have permission to approve it then duck out now.
236
	if (!empty($topic) && empty($board_info['cur_topic_approved']) && !allowedTo('approve_posts') && ($user_info['id'] != $board_info['cur_topic_starter'] || $user_info['is_guest']))
0 ignored issues
show
The function allowedTo was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

236
	if (!empty($topic) && empty($board_info['cur_topic_approved']) && !/** @scrutinizer ignore-call */ allowedTo('approve_posts') && ($user_info['id'] != $board_info['cur_topic_starter'] || $user_info['is_guest']))
Loading history...
237
		fatal_lang_error('not_a_topic', false);
238
239
	// Do some logging, unless this is an attachment, avatar, toggle of editor buttons, theme option, XML feed, popup, etc.
240
	$no_stat_actions = array(
241
		'about:unknown' => true,
242
		'clock' => true,
243
		'dlattach' => true,
244
		'findmember' => true,
245
		'helpadmin' => true,
246
		'jsoption' => true,
247
		'likes' => true,
248
		'modifycat' => true,
249
		'pm' => array('sa' => array('popup')),
250
		'profile' => array('area' => array('popup', 'alerts_popup', 'download', 'dlattach')),
251
		'requestmembers' => true,
252
		'smstats' => true,
253
		'suggest' => true,
254
		'verificationcode' => true,
255
		'viewquery' => true,
256
		'viewsmfile' => true,
257
		'xmlhttp' => true,
258
		'.xml' => true,
259
	);
260
	call_integration_hook('integrate_pre_log_stats', array(&$no_stat_actions));
261
262
	$should_log = !is_filtered_request($no_stat_actions, 'action');
263
	if ($should_log)
264
	{
265
		// Log this user as online.
266
		writeLog();
267
268
		// Track forum statistics and hits...?
269
		if (!empty($modSettings['hitStats']))
270
			trackStats(array('hits' => '+'));
271
	}
272
	unset($no_stat_actions);
273
274
	// Make sure that our scheduled tasks have been running as intended
275
	check_cron();
276
277
	// Is the forum in maintenance mode? (doesn't apply to administrators.)
278
	if (!empty($maintenance) && !allowedTo('admin_forum'))
279
	{
280
		// You can only login.... otherwise, you're getting the "maintenance mode" display.
281
		if (isset($_REQUEST['action']) && (in_array($_REQUEST['action'], array('login2', 'logintfa', 'logout'))))
282
		{
283
			require_once($sourcedir . '/LogInOut.php');
284
			return ($_REQUEST['action'] == 'login2' ? 'Login2' : ($_REQUEST['action'] == 'logintfa' ? 'LoginTFA' : 'Logout'));
285
		}
286
		// Don't even try it, sonny.
287
		else
288
			return 'InMaintenance';
289
	}
290
	// If guest access is off, a guest can only do one of the very few following actions.
291
	elseif (empty($modSettings['allow_guestAccess']) && $user_info['is_guest'] && (!isset($_REQUEST['action']) || !in_array($_REQUEST['action'], array('coppa', 'login', 'login2', 'logintfa', 'reminder', 'activate', 'help', 'helpadmin', 'smstats', 'verificationcode', 'signup', 'signup2'))))
292
		return 'KickGuest';
293
	elseif (empty($_REQUEST['action']))
294
	{
295
		// Action and board are both empty... BoardIndex! Unless someone else wants to do something different.
296
		if (empty($board) && empty($topic))
297
		{
298
			if (!empty($modSettings['integrate_default_action']))
299
			{
300
				$defaultAction = explode(',', $modSettings['integrate_default_action']);
301
302
				// Sorry, only one default action is needed.
303
				$defaultAction = $defaultAction[0];
304
305
				$call = call_helper($defaultAction, true);
306
307
				if (!empty($call))
308
					return $call;
309
			}
310
311
			// No default action huh? then go to our good old BoardIndex.
312
			else
313
			{
314
				require_once($sourcedir . '/BoardIndex.php');
315
316
				return 'BoardIndex';
317
			}
318
		}
319
320
		// Topic is empty, and action is empty.... MessageIndex!
321
		elseif (empty($topic))
322
		{
323
			require_once($sourcedir . '/MessageIndex.php');
324
			return 'MessageIndex';
325
		}
326
327
		// Board is not empty... topic is not empty... action is empty.. Display!
328
		else
329
		{
330
			require_once($sourcedir . '/Display.php');
331
			return 'Display';
332
		}
333
	}
334
335
	// Here's the monstrous $_REQUEST['action'] array - $_REQUEST['action'] => array($file, $function).
336
	$actionArray = array(
337
		'agreement' => array('Agreement.php', 'Agreement'),
338
		'acceptagreement' => array('Agreement.php', 'AcceptAgreement'),
339
		'activate' => array('Register.php', 'Activate'),
340
		'admin' => array('Admin.php', 'AdminMain'),
341
		'announce' => array('Post.php', 'AnnounceTopic'),
342
		'attachapprove' => array('ManageAttachments.php', 'ApproveAttach'),
343
		'buddy' => array('Subs-Members.php', 'BuddyListToggle'),
344
		'calendar' => array('Calendar.php', 'CalendarMain'),
345
		'clock' => array('Calendar.php', 'clock'),
346
		'coppa' => array('Register.php', 'CoppaForm'),
347
		'credits' => array('Who.php', 'Credits'),
348
		'deletemsg' => array('RemoveTopic.php', 'DeleteMessage'),
349
		'dlattach' => array('ShowAttachments.php', 'showAttachment'),
350
		'editpoll' => array('Poll.php', 'EditPoll'),
351
		'editpoll2' => array('Poll.php', 'EditPoll2'),
352
		'findmember' => array('Subs-Auth.php', 'JSMembers'),
353
		'groups' => array('Groups.php', 'Groups'),
354
		'help' => array('Help.php', 'ShowHelp'),
355
		'helpadmin' => array('Help.php', 'ShowAdminHelp'),
356
		'jsmodify' => array('Post.php', 'JavaScriptModify'),
357
		'jsoption' => array('Themes.php', 'SetJavaScript'),
358
		'likes' => array('Likes.php', 'Likes::call#'),
359
		'lock' => array('Topic.php', 'LockTopic'),
360
		'lockvoting' => array('Poll.php', 'LockVoting'),
361
		'login' => array('LogInOut.php', 'Login'),
362
		'login2' => array('LogInOut.php', 'Login2'),
363
		'logintfa' => array('LogInOut.php', 'LoginTFA'),
364
		'logout' => array('LogInOut.php', 'Logout'),
365
		'markasread' => array('Subs-Boards.php', 'MarkRead'),
366
		'mergetopics' => array('SplitTopics.php', 'MergeTopics'),
367
		'mlist' => array('Memberlist.php', 'Memberlist'),
368
		'moderate' => array('ModerationCenter.php', 'ModerationMain'),
369
		'modifycat' => array('ManageBoards.php', 'ModifyCat'),
370
		'movetopic' => array('MoveTopic.php', 'MoveTopic'),
371
		'movetopic2' => array('MoveTopic.php', 'MoveTopic2'),
372
		'notifyannouncements' => array('Notify.php', 'AnnouncementsNotify'),
373
		'notifyboard' => array('Notify.php', 'BoardNotify'),
374
		'notifytopic' => array('Notify.php', 'TopicNotify'),
375
		'pm' => array('PersonalMessage.php', 'MessageMain'),
376
		'post' => array('Post.php', 'Post'),
377
		'post2' => array('Post.php', 'Post2'),
378
		'printpage' => array('Printpage.php', 'PrintTopic'),
379
		'profile' => array('Profile.php', 'ModifyProfile'),
380
		'quotefast' => array('Post.php', 'QuoteFast'),
381
		'quickmod' => array('MessageIndex.php', 'QuickModeration'),
382
		'quickmod2' => array('Display.php', 'QuickInTopicModeration'),
383
		'recent' => array('Recent.php', 'RecentPosts'),
384
		'reminder' => array('Reminder.php', 'RemindMe'),
385
		'removepoll' => array('Poll.php', 'RemovePoll'),
386
		'removetopic2' => array('RemoveTopic.php', 'RemoveTopic2'),
387
		'reporttm' => array('ReportToMod.php', 'ReportToModerator'),
388
		'requestmembers' => array('Subs-Auth.php', 'RequestMembers'),
389
		'restoretopic' => array('RemoveTopic.php', 'RestoreTopic'),
390
		'search' => array('Search.php', 'PlushSearch1'),
391
		'search2' => array('Search.php', 'PlushSearch2'),
392
		'sendactivation' => array('Register.php', 'SendActivation'),
393
		'signup' => array('Register.php', 'Register'),
394
		'signup2' => array('Register.php', 'Register2'),
395
		'smstats' => array('Stats.php', 'SMStats'),
396
		'suggest' => array('Subs-Editor.php', 'AutoSuggestHandler'),
397
		'splittopics' => array('SplitTopics.php', 'SplitTopics'),
398
		'stats' => array('Stats.php', 'DisplayStats'),
399
		'sticky' => array('Topic.php', 'Sticky'),
400
		'theme' => array('Themes.php', 'ThemesMain'),
401
		'trackip' => array('Profile-View.php', 'trackIP'),
402
		'about:unknown' => array('Likes.php', 'BookOfUnknown'),
403
		'unread' => array('Recent.php', 'UnreadTopics'),
404
		'unreadreplies' => array('Recent.php', 'UnreadTopics'),
405
		'uploadAttach' => array('Attachments.php', 'Attachments::call#'),
406
		'verificationcode' => array('Register.php', 'VerificationCode'),
407
		'viewprofile' => array('Profile.php', 'ModifyProfile'),
408
		'vote' => array('Poll.php', 'Vote'),
409
		'viewquery' => array('ViewQuery.php', 'ViewQuery'),
410
		'viewsmfile' => array('Admin.php', 'DisplayAdminFile'),
411
		'who' => array('Who.php', 'Who'),
412
		'.xml' => array('News.php', 'ShowXmlFeed'),
413
		'xmlhttp' => array('Xml.php', 'XMLhttpMain'),
414
	);
415
416
	// Allow modifying $actionArray easily.
417
	call_integration_hook('integrate_actions', array(&$actionArray));
418
419
	// Get the function and file to include - if it's not there, do the board index.
420
	if (!isset($_REQUEST['action']) || !isset($actionArray[$_REQUEST['action']]))
421
	{
422
		// Catch the action with the theme?
423
		if (!empty($settings['catch_action']))
424
		{
425
			require_once($sourcedir . '/Themes.php');
426
			return 'WrapAction';
427
		}
428
429
		if (!empty($modSettings['integrate_fallback_action']))
430
		{
431
			$fallbackAction = explode(',', $modSettings['integrate_fallback_action']);
432
433
			// Sorry, only one fallback action is needed.
434
			$fallbackAction = $fallbackAction[0];
435
436
			$call = call_helper($fallbackAction, true);
437
438
			if (!empty($call))
439
				return $call;
440
		}
441
442
		// No fallback action, huh?
443
		else
444
		{
445
			fatal_lang_error('not_found', false, array(), 404);
446
		}
447
	}
448
449
	// Otherwise, it was set - so let's go to that action.
450
	if (!empty($actionArray[$_REQUEST['action']][0]))
451
		require_once($sourcedir . '/' . $actionArray[$_REQUEST['action']][0]);
452
453
	// Do the right thing.
454
	return call_helper($actionArray[$_REQUEST['action']][1], true);
455
}
456
457
?>