Passed
Push — development ( da8715...080d06 )
by Spuds
01:08 queued 26s
created

bootstrap.php (2 issues)

1
<?php
2
3
/**
4
 * Initialize the ElkArte environment.
5
 *
6
 * @package   ElkArte Forum
7
 * @copyright ElkArte Forum contributors
8
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause (see accompanying LICENSE.txt file)
9
 *
10
 * This file contains code covered by:
11
 * copyright: 2011 Simple Machines (http://www.simplemachines.org)
12
 *
13
 * @version 2.0 dev
14
 */
15
16
use BBC\ParserWrapper;
17
use ElkArte\Cache\Cache;
18
use ElkArte\Controller\Auth;
19
use ElkArte\Debug;
20
use ElkArte\Errors\Errors;
0 ignored issues
show
The type ElkArte\Errors\Errors was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
21
use ElkArte\EventManager;
22
use ElkArte\ext\Composer\Autoload\ClassLoader;
23
use ElkArte\Helper\TokenHash;
24
use ElkArte\Hooks;
25
use ElkArte\MembersList;
26
use ElkArte\Server;
27
use ElkArte\Themes\ThemeLoader;
28
use ElkArte\User;
29
30
/**
31
 * Class Bootstrap
32
 *
33
 * Takes care of the initial loading and feeding of Elkarte from
34
 * either SSI or Index
35
 */
36
class Bootstrap
37
{
38
	/** @var array What is returned by the function getrusage. */
39
	protected $rusage_start = [];
40
41
	/**
42
	 * Bootstrap constructor.
43
	 *
44
	 * @param bool $standalone
45
	 *  - true to boot outside elkarte
46
	 *  - false to bootstrap the main elkarte site.
47
	 */
48
	public function __construct($standalone = true)
49
	{
50
		// Bootstrap only once.
51
		if (!defined('ELKBOOT'))
52
		{
53
			// We're going to set a few globals
54
			global $time_start, $ssi_error_reporting, $db_show_debug;
55
56
			// Your on the clock
57
			$time_start = microtime(true);
58
59
			// Unless settings.php tells us otherwise
60
			$db_show_debug = false;
61
62
			// Report errors but not depreciated ones
63
			$ssi_error_reporting = error_reporting(E_ALL & ~E_DEPRECATED);
64
65
			// Get the things needed for ALL modes
66
			$this->bringUpBasics();
67
68
			// Going to run from the side entrance and not directly from inside elkarte
69
			if ($standalone)
70
			{
71
				$this->ssi_main();
72
			}
73
		}
74
	}
75
76
	/**
77
	 * Calls the various initialization functions in the needed order
78
	 */
79
	public function bringUpBasics()
80
	{
81
		$this->setConstants();
82
		$this->setRusage();
83
		$this->clearGlobals();
84
		$this->loadSettingsFile();
85
		$this->validatePaths();
86
		$this->loadDependants();
87
		$this->loadAutoloader();
88
		$this->checkMaintance();
89
		$this->setDebug();
90
		$this->bringUp();
91
	}
92
93
	/**
94
	 * Set the core constants, you know the ones we often forget to
95
	 * update on new releases.
96
	 */
97
	private function setConstants()
98
	{
99
		// First things first, but not necessarily in that order.
100
		if (!defined('ELK'))
101
		{
102
			define('ELK', '1');
103
		}
104
105
		define('ELKBOOT', '1');
106
107
		// The software version
108
		define('FORUM_VERSION', 'ElkArte 2.0 dev');
109
110
		// Shortcut for the browser cache stale
111
		define('CACHE_STALE', '?20dev');
112
	}
113
114
	/**
115
	 * Get initial resource usage
116
	 */
117
	private function setRusage()
118
	{
119
		$this->rusage_start = getrusage();
120
	}
121
122
	/**
123
	 * If they glo, they need to be cleaned.
124
	 */
125
	private function clearGlobals()
126
	{
127
		// We don't need no globals. (a bug in "old" versions of PHP)
128
		foreach (['db_character_set', 'cachedir'] as $variable)
129
		{
130
			if (isset($GLOBALS[$variable]))
131
			{
132
				unset($GLOBALS[$variable], $GLOBALS[$variable]);
133
			}
134
		}
135
	}
136
137
	/**
138
	 * Loads the settings values into the global space
139
	 */
140
	private function loadSettingsFile()
141
	{
142
		// All those wonderful things found in settings
143
		global $maintenance, $mtitle, $msubject, $mmessage, $mbname, $language, $boardurl, $webmaster_email;
144
		global $cookiename, $db_type, $db_server, $db_port, $db_name, $db_user, $db_passwd;
145
		global $ssi_db_user, $ssi_db_passwd, $db_prefix, $db_persist, $db_error_send, $cache_accelerator;
146
		global $cache_uid, $cache_password, $cache_enable, $cache_memcached, $db_show_debug, $url_format;
147
		global $cachedir, $boarddir, $sourcedir, $extdir, $languagedir;
148
149
		// Where the Settings.php file is located
150
		$settings_loc = __DIR__ . '/Settings.php';
151
152
		// First thing: if the installation dir exists, just send anybody there
153
		// The IGNORE_INSTALL_DIR constant is for developers only. Do not add it on production sites
154
		if (file_exists('install') && (file_exists('install/install.php') || file_exists('install/upgrade.php')))
155
		{
156
			if (file_exists($settings_loc))
157
			{
158
				require_once($settings_loc);
159
			}
160
161
			if (!defined('IGNORE_INSTALL_DIR'))
162
			{
163
				$redirec_file = file_exists($settings_loc) && empty($_SESSION['installing']) ? 'upgrade.php' : 'install.php';
164
165
				// To early for constants or autoloader
166
				require_once($boarddir . '/sources/ElkArte/Server.php');
167
				$server = new Server($_SERVER);
168
169
				$version_running = str_replace('ElkArte ', '', FORUM_VERSION);
170
				$location = $server->supportsSSL() ? 'https://' : 'http://';
171
				$location .= $server->getHost();
172
				$temp = preg_replace('~/' . preg_quote(basename($boardurl . '/index.php'), '~') . '(/.+)?$~', '', str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])));
173
				$location .= ($temp !== '/') ? $temp : '';
174
175
				// Too early to use Headers class etc.
176
				header('Location:' . $location . '/install/' . $redirec_file . '?v=' . $version_running);
177
				die();
178
			}
179
		}
180
		else
181
		{
182
			require_once($settings_loc);
183
		}
184
	}
185
186
	/**
187
	 * Validate the paths set in Settings.php, correct as needed and move them to constants.
188
	 */
189
	private function validatePaths()
190
	{
191
		global $boarddir, $sourcedir, $cachedir, $extdir, $languagedir;
192
193
		// Make sure the paths are correct... at least try to fix them.
194
		if (!file_exists($boarddir) && file_exists(__DIR__ . '/bootstrap.php'))
195
		{
196
			$boarddir = __DIR__;
197
		}
198
199
		if (!file_exists($sourcedir . '/SiteDispatcher.class.php') && file_exists($boarddir . '/sources'))
200
		{
201
			$sourcedir = $boarddir . '/sources';
202
		}
203
204
		// Check that directories which didn't exist in past releases are initialized.
205
		if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/cache'))
206
		{
207
			$cachedir = $boarddir . '/cache';
208
		}
209
210
		if ((empty($extdir) || !file_exists($extdir)) && file_exists($sourcedir . '/ext'))
211
		{
212
			$extdir = $sourcedir . '/ext';
213
		}
214
215
		if ((empty($languagedir) || !file_exists($languagedir)) && file_exists($sourcedir . '/Languages/Index'))
216
		{
217
			$languagedir = $sourcedir . '/ElkArte/Languages';
218
		}
219
220
		// Time to forget about variables and go with constants!
221
		define('BOARDDIR', $boarddir);
222
		define('CACHEDIR', $cachedir);
223
		define('EXTDIR', $extdir);
224
		define('LANGUAGEDIR', $languagedir);
225
		define('SOURCEDIR', $sourcedir);
226
		define('ADMINDIR', $sourcedir . '/ElkArte/AdminController');
227
		define('CONTROLLERDIR', $sourcedir . '/ElkArte/Controller');
228
		define('SUBSDIR', $sourcedir . '/subs');
229
		define('ADDONSDIR', $boarddir . '/addons');
230
		unset($boarddir, $cachedir, $sourcedir, $languagedir, $extdir);
231
	}
232
233
	/**
234
	 * We require access to several important files, so load them upfront
235
	 */
236
	private function loadDependants()
237
	{
238
		// Files we cannot live without.
239
		require_once(SOURCEDIR . '/QueryString.php');
240
		require_once(SOURCEDIR . '/Session.php');
241
		require_once(SOURCEDIR . '/Subs.php');
242
		require_once(SOURCEDIR . '/Logging.php');
243
		require_once(SOURCEDIR . '/Load.php');
244
		require_once(SOURCEDIR . '/Security.php');
245
		require_once(SUBSDIR . '/Cache.subs.php');
246
	}
247
248
	/**
249
	 * The autoloader will take care most requests for files
250
	 */
251
	private function loadAutoloader()
252
	{
253
		require_once(EXTDIR . '/ClassLoader.php');
254
255
		$loader = new ClassLoader();
256
		$loader->setPsr4('ElkArte\\', SOURCEDIR . '/ElkArte');
257
		$loader->setPsr4('BBC\\', SOURCEDIR . '/ElkArte/BBC');
258
		$loader->register();
259
	}
260
261
	/**
262
	 * Check if we are in maintenance mode, if so end here.
263
	 */
264
	private function checkMaintance()
265
	{
266
		global $maintenance, $ssi_maintenance_off;
267
268
		// Don't do john didley if the forum's been shut down completely.
269
		if (empty($maintenance))
270
		{
271
			return;
272
		}
273
274
		if ((int) $maintenance !== 2)
275
		{
276
			return;
277
		}
278
279
		if (isset($ssi_maintenance_off) && $ssi_maintenance_off === true)
280
		{
281
			return;
282
		}
283
284
		Errors::instance()->display_maintenance_message();
285
	}
286
287
	/**
288
	 * If you like lots of debug information in error messages and below the footer
289
	 * then set $db_show_debug to true in settings.  Don't do this on a production site.
290
	 */
291
	private function setDebug()
292
	{
293
		global $db_show_debug, $ssi_error_reporting;
294
295
		// Show lots of debug information below the page, not for production sites
296
		if ($db_show_debug === true)
297
		{
298
			Debug::instance()->rusage('start', $this->rusage_start);
299
			$ssi_error_reporting = error_reporting(E_ALL | E_STRICT & ~8192);
300
		}
301
	}
302
303
	/**
304
	 * Time to see what has been requested, by whom and dispatch it to the proper handler
305
	 */
306
	private function bringUp()
307
	{
308
		global $context;
309
310
		// Initiate the database connection and define some database functions to use.
311
		loadDatabase();
312
313
		// Let's set up our shiny new hooks handler.
314
		Hooks::init(database(), Debug::instance());
315
316
		// It's time for settings loaded from the database.
317
		reloadSettings();
318
319
		// Clean the request.
320
		cleanRequest();
321
322
		// Make sure we have the list of members for populating it
323
		MembersList::init(database(), Cache::instance(), ParserWrapper::instance());
324
325
		// Our good ole' contextual array, which will hold everything
326
		if (empty($context))
327
		{
328
			$context = [];
329
		}
330
	}
331
332
	/**
333
	 * If you are running SSI standalone, you need to call this function after bootstrap is
334
	 * initialized.
335
	 */
336
	public function ssi_main()
337
	{
338
		global $ssi_layers, $ssi_theme, $ssi_gzip, $ssi_ban, $ssi_guest_access;
339
		global $modSettings, $context, $board, $topic, $txt;
340
341
		// Check on any hacking attempts.
342
		$this->_validRequestCheck();
343
344
		// Gzip output? (because it must be boolean and true, this can't be hacked.)
345
		if (isset($ssi_gzip) && $ssi_gzip === true && detectServer()->outPutCompressionEnabled())
346
		{
347
			ob_start('ob_gzhandler');
348
		}
349
		else
350
		{
351
			$modSettings['enableCompressedOutput'] = '0';
352
		}
353
354
		// Primarily, this is to fix the URLs...
355
		ob_start('ob_sessrewrite');
356
357
		// Start the session... known to scramble SSI includes in cases...
358
		if (!headers_sent())
359
		{
360
			loadSession();
361
		}
362
		else
363
		{
364
			if (isset($_COOKIE[session_name()]) || isset($_REQUEST[session_name()]))
365
			{
366
				// Make a stab at it, but ignore the E_WARNINGs generated because we can't send headers.
367
				$temp = error_reporting(error_reporting() & !E_WARNING);
368
				loadSession();
369
				error_reporting($temp);
370
			}
371
372
			if (!isset($_SESSION['session_value']))
373
			{
374
				$tokenizer = new TokenHash();
375
				$_SESSION['session_value'] = $tokenizer->generate_hash(32, session_id());
376
				$_SESSION['session_var'] = substr(preg_replace('~^\d+~', '', $tokenizer->generate_hash(16, session_id())), 0, rand(7, 12));
377
			}
378
379
			// This is here only to avoid session errors in PHP7
380
			// microtime effectively forces the replacing of the session in the db each
381
			// time the page is loaded
382
			$_SESSION['mictrotime'] = microtime();
383
		}
384
385
		// Get rid of $board and $topic... do stuff loadBoard would do.
386
		unset($board, $topic);
387
		$context['linktree'] = array();
388
389
		// Load the user and their cookie, as well as their settings.
390
		User::load(true);
391
		$context['user']['is_mod'] = User::$info->is_mod ?? false;
392
393
		// Load the current user's permissions....
394
		loadPermissions();
395
396
		// Load the current or SSI theme. (just use $ssi_theme = id_theme;)
397
		new ThemeLoader(isset($ssi_theme) ? (int) $ssi_theme : 0);
398
399
		// Load BadBehavior functions, but not when running from CLI
400
		if (!defined('STDIN') && runBadBehavior())
401
		{
402
			// 403 and gone
403
			Errors::instance()->display_403_error(true);
404
		}
405
406
		// Take care of any banning that needs to be done.
407
		if (isset($_REQUEST['ssi_ban']) || (isset($ssi_ban) && $ssi_ban === true))
408
		{
409
			is_not_banned();
410
		}
411
412
		// Do we allow guests in here?
413
		if (empty($ssi_guest_access) && empty($modSettings['allow_guestAccess']) && User::$info->is_guest && basename($_SERVER['PHP_SELF']) !== 'SSI.php')
414
		{
415
			$controller = new Auth(new EventManager());
416
			$controller->setUser(User::$info);
417
			$controller->action_kickguest();
418
			obExit(null, true);
419
		}
420
421
		if (!empty($modSettings['front_page']) && class_exists($modSettings['front_page'])
422
			&& in_array('frontPageHook', get_class_methods($modSettings['front_page'])))
423
		{
424
			$modSettings['default_forum_action'] = ['action' => 'forum'];
425
		}
426
		else
427
		{
428
			$modSettings['default_forum_action'] = [];
429
		}
430
431
		// Load the stuff like the menu bar, etc.
432
		if (isset($ssi_layers))
433
		{
434
			$template_layers = theme()->getLayers();
435
			$template_layers->removeAll();
436
			foreach ($ssi_layers as $layer)
437
			{
438
				$template_layers->addBegin($layer);
439
			}
440
441
			template_header();
442
		}
443
		else
444
		{
445
			setupThemeContext();
446
		}
447
448
		// We need to set up user agent, and make more checks on the request
449
		$req = request();
450
451
		// Make sure they didn't muss around with the settings... but only if it's not cli.
452
		if (isset($_SERVER['REMOTE_ADDR']) && session_id() === '')
453
		{
454
			trigger_error($txt['ssi_session_broken']);
455
		}
456
457
		// Without visiting the forum this session variable might not be set on submit.
458
		if (isset($_SESSION['USER_AGENT']))
459
		{
460
			return;
461
		}
462
463
		if (isset($_GET['ssi_function']) && $_GET['ssi_function'] === 'pollVote')
464
		{
465
			return;
466
		}
467
468
		$_SESSION['USER_AGENT'] = $req->user_agent();
469
	}
470
471
	/**
472
	 * Used to ensure SSI requests are valid and not a probing attempt
473
	 */
474
	private function _validRequestCheck()
475
	{
476
		global $ssi_theme, $ssi_layers;
477
478
		// Check on any hacking attempts.
479
		if (
480
			isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS'])
481
			|| isset($_REQUEST['ssi_theme']) && (int) $_REQUEST['ssi_theme'] === (int) $ssi_theme
482
			|| isset($_COOKIE['ssi_theme']) && (int) $_COOKIE['ssi_theme'] === (int) $ssi_theme
483
			|| isset($_REQUEST['ssi_layers'], $ssi_layers) && $_REQUEST['ssi_layers'] == $ssi_layers
484
			|| isset($_REQUEST['context']))
485
		{
486
			die('No access...');
0 ignored issues
show
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
487
		}
488
	}
489
}
490