Passed
Push — development ( 087131...3103ec )
by Spuds
01:20 queued 23s
created

bootstrap.php (3 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\Request;
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 various initialization functions in the necessary 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.php 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;
146
		global $cache_uid, $cache_password, $cache_enable, $cache_servers, $cache_accelerator;
147
		global $db_show_debug, $url_format, $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, consider sending users there
153
		// The IGNORE_INSTALL_DIR constant is intended for development, bootstrapcompleted.lock will be added
154
		// after a successful installation, so that the installer will not automatically be shown again.
155
		if (defined('IGNORE_INSTALL_DIR') || file_exists(__DIR__ . '/bootstrapcompleted.lock'))
156
		{
157
			require_once($settings_loc);
158
			return;
159
		}
160
161
		if (file_exists('install') &&
162
			(file_exists('install/install.php') || file_exists('install/upgrade.php')))
163
		{
164
			$hasSettings = file_exists($settings_loc);
165
			if ($hasSettings)
166
			{
167
				require_once($settings_loc);
168
			}
169
170
			$redirec_file = $hasSettings && empty($_SESSION['installing']) ? 'upgrade.php' : 'install.php';
171
172
			// Build a safe, relative redirect to avoid host header issues
173
			$version_running = defined('FORUM_VERSION') ? str_replace('ElkArte ', '', FORUM_VERSION) : '';
174
175
			// Too early to use Headers class etc.
176
			header('Location: install/' . $redirec_file . '?v=' . $version_running);
177
			die();
178
		}
179
	}
180
181
	/**
182
	 * Validate the paths set in Settings.php, correct as needed and move them to constants.
183
	 */
184
	private function validatePaths()
185
	{
186
		global $boarddir, $sourcedir, $cachedir, $extdir, $languagedir;
187
188
		// Make sure the paths are correct... at least try to fix them.
189
		if (!file_exists($boarddir) && file_exists(__DIR__ . '/bootstrap.php'))
190
		{
191
			$boarddir = __DIR__;
192
		}
193
194
		if (!file_exists($sourcedir . '/SiteDispatcher.class.php') && file_exists($boarddir . '/sources'))
195
		{
196
			$sourcedir = $boarddir . '/sources';
197
		}
198
199
		// Check that directories which didn't exist in past releases are initialized.
200
		if ((empty($cachedir) || !file_exists($cachedir)) && file_exists($boarddir . '/cache'))
201
		{
202
			$cachedir = $boarddir . '/cache';
203
		}
204
205
		if ((empty($extdir) || !file_exists($extdir)) && file_exists($sourcedir . '/ext'))
206
		{
207
			$extdir = $sourcedir . '/ext';
208
		}
209
210
		if ((empty($languagedir) || !file_exists($languagedir)) && file_exists($sourcedir . '/Languages/Index'))
211
		{
212
			$languagedir = $sourcedir . '/ElkArte/Languages';
213
		}
214
215
		// Time to forget about variables and go with constants!
216
		define('BOARDDIR', $boarddir);
217
		define('CACHEDIR', $cachedir);
218
		define('EXTDIR', $extdir);
219
		define('LANGUAGEDIR', $languagedir);
220
		define('SOURCEDIR', $sourcedir);
221
		define('ADMINDIR', $sourcedir . '/ElkArte/AdminController');
222
		define('CONTROLLERDIR', $sourcedir . '/ElkArte/Controller');
223
		define('SUBSDIR', $sourcedir . '/subs');
224
		define('ADDONSDIR', $boarddir . '/Addons');
225
		define('ELKARTEDIR', $sourcedir . '/ElkArte');
226
		unset($boarddir, $cachedir, $sourcedir, $languagedir, $extdir);
227
	}
228
229
	/**
230
	 * We require access to several important files, so load them upfront
231
	 */
232
	private function loadDependants()
233
	{
234
		// Files we cannot live without.
235
		require_once(SOURCEDIR . '/QueryString.php');
236
		require_once(SOURCEDIR . '/Session.php');
237
		require_once(SOURCEDIR . '/Subs.php');
238
		require_once(SOURCEDIR . '/Logging.php');
239
		require_once(SOURCEDIR . '/Load.php');
240
		require_once(SOURCEDIR . '/Security.php');
241
		require_once(SUBSDIR . '/Cache.subs.php');
242
	}
243
244
	/**
245
	 * The autoloader will take care of most requests for files
246
	 */
247
	private function loadAutoloader()
248
	{
249
		require_once(EXTDIR . '/ClassLoader.php');
250
251
		$loader = new ClassLoader();
252
		$loader->setPsr4('ElkArte\\', SOURCEDIR . '/ElkArte');
0 ignored issues
show
SOURCEDIR . '/ElkArte' of type string is incompatible with the type ElkArte\ext\Composer\Autoload\list expected by parameter $paths of ElkArte\ext\Composer\Aut...\ClassLoader::setPsr4(). ( Ignorable by Annotation )

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

252
		$loader->setPsr4('ElkArte\\', /** @scrutinizer ignore-type */ SOURCEDIR . '/ElkArte');
Loading history...
253
		$loader->setPsr4('BBC\\', SOURCEDIR . '/ElkArte/BBC');
254
		$loader->setPsr4('Addons\\', BOARDDIR . '/Addons');
255
		$loader->register();
256
	}
257
258
	/**
259
	 * Check if we are in maintenance mode, if so end here.
260
	 */
261
	private function checkMaintance()
262
	{
263
		global $maintenance, $ssi_maintenance_off;
264
265
		// Don't do john didley if the forum's been shut down completely.
266
		if (empty($maintenance))
267
		{
268
			return;
269
		}
270
271
		if ((int) $maintenance !== 2)
272
		{
273
			return;
274
		}
275
276
		if (isset($ssi_maintenance_off) && $ssi_maintenance_off === true)
277
		{
278
			return;
279
		}
280
281
		Errors::instance()->display_maintenance_message();
282
	}
283
284
	/**
285
	 * If you like lots of debug information in error messages and below the footer
286
	 * then set $db_show_debug to true in settings.  Don't do this on a production site.
287
	 */
288
	private function setDebug()
289
	{
290
		global $db_show_debug, $ssi_error_reporting;
291
292
		// Show lots of debug information below the page, not for production sites
293
		if ($db_show_debug === true)
294
		{
295
			Debug::instance()->rusage('start', $this->rusage_start);
296
			$ssi_error_reporting = error_reporting(E_ALL | E_STRICT & ~8192);
297
		}
298
	}
299
300
	/**
301
	 * Time to see what has been requested, by whom and dispatch it to the proper handler
302
	 */
303
	private function bringUp()
304
	{
305
		global $context;
306
307
		// Initiate the database connection and define some database functions to use.
308
		loadDatabase();
309
310
		// Let's set up our shiny new hooks handler.
311
		Hooks::init(database(), Debug::instance());
312
313
		// It's time for settings loaded from the database.
314
		reloadSettings();
315
316
		// Clean the request.
317
		cleanRequest();
318
319
		// Make sure we have the list of members for populating it
320
		MembersList::init(database(), Cache::instance(), ParserWrapper::instance());
321
322
		// Our good ole' contextual array, which will hold everything
323
		if (empty($context))
324
		{
325
			$context = [];
326
		}
327
	}
328
329
	/**
330
	 * If you are running SSI standalone, you need to call this function after bootstrap is
331
	 * initialized.
332
	 */
333
	public function ssi_main()
334
	{
335
		global $ssi_layers, $ssi_theme, $ssi_gzip, $ssi_ban, $ssi_guest_access;
336
		global $modSettings, $context, $board, $topic, $txt;
337
338
		// Check on any hacking attempts.
339
		$this->_validRequestCheck();
340
341
		// Gzip output? (because it must be boolean and true, this can't be hacked.)
342
		if (isset($ssi_gzip) && $ssi_gzip === true && detectServer()->outPutCompressionEnabled())
343
		{
344
			ob_start('ob_gzhandler');
345
		}
346
		else
347
		{
348
			$modSettings['enableCompressedOutput'] = '0';
349
		}
350
351
		// Primarily, this is to fix the URLs...
352
		ob_start('ob_sessrewrite');
353
354
		// Start the session... known to scramble SSI includes in cases...
355
		if (!headers_sent())
356
		{
357
			loadSession();
358
		}
359
		else
360
		{
361
			if (isset($_COOKIE[session_name()]) || isset($_REQUEST[session_name()]))
362
			{
363
				// Make a stab at it, but ignore the E_WARNINGs generated because we can't send headers.
364
				$temp = error_reporting(error_reporting() & !E_WARNING);
365
				loadSession();
366
				error_reporting($temp);
367
			}
368
369
			if (!isset($_SESSION['session_value']))
370
			{
371
				$tokenizer = new TokenHash();
372
				$_SESSION['session_value'] = $tokenizer->generate_hash(32, session_id());
373
				$_SESSION['session_var'] = substr(preg_replace('~^\d+~', '', $tokenizer->generate_hash(16, session_id())), 0, rand(7, 12));
374
			}
375
376
			// This is here only to avoid session errors in PHP7
377
			// microtime effectively forces the replacing of the session in the db each
378
			// time the page is loaded
379
			$_SESSION['mictrotime'] = microtime();
380
		}
381
382
		// Get rid of $board and $topic... do stuff loadBoard would do.
383
		unset($board, $topic);
384
		$context['breadcrumbs'] = [];
385
386
		// Load the user and their cookie, as well as their settings.
387
		User::load(true);
388
		$context['user']['is_mod'] = User::$info->is_mod ?? false;
389
390
		// Load the current user's permissions....
391
		loadPermissions();
392
393
		// Load the current or SSI theme. (just use $ssi_theme = id_theme;)
394
		new ThemeLoader(isset($ssi_theme) ? (int) $ssi_theme : 0);
395
396
		// Load BadBehavior functions, but not when running from CLI
397
		if (!defined('STDIN') && runBadBehavior())
398
		{
399
			// 403 and gone
400
			Errors::instance()->display_403_error(true);
401
		}
402
403
		// Take care of any banning that needs to be done.
404
		if (isset($_REQUEST['ssi_ban']) || (isset($ssi_ban) && $ssi_ban === true))
405
		{
406
			is_not_banned();
407
		}
408
409
		// Do we allow guests in here?
410
		if (empty($ssi_guest_access) && empty($modSettings['allow_guestAccess']) && User::$info->is_guest && basename($_SERVER['PHP_SELF']) !== 'SSI.php')
411
		{
412
			$controller = new Auth(new EventManager());
413
			$controller->setUser(User::$info);
414
			$controller->action_kickguest();
415
			obExit(null, true);
416
		}
417
418
		if (!empty($modSettings['front_page']) && class_exists($modSettings['front_page'])
419
			&& in_array('frontPageHook', get_class_methods($modSettings['front_page'])))
420
		{
421
			$modSettings['default_forum_action'] = ['action' => 'forum'];
422
		}
423
		else
424
		{
425
			$modSettings['default_forum_action'] = [];
426
		}
427
428
		// Load the stuff like the menu bar, etc.
429
		if (isset($ssi_layers))
430
		{
431
			$template_layers = theme()->getLayers();
432
			$template_layers->removeAll();
433
			foreach ($ssi_layers as $layer)
434
			{
435
				$template_layers->addBegin($layer);
436
			}
437
438
			template_header();
439
		}
440
		else
441
		{
442
			setupThemeContext();
443
		}
444
445
		// We need to set up user agent, and make more checks on the request
446
		$req = Request::instance();
447
448
		// Make sure they didn't muss around with the settings... but only if it's not cli.
449
		if (isset($_SERVER['REMOTE_ADDR']) && session_id() === '')
450
		{
451
			trigger_error($txt['ssi_session_broken']);
452
		}
453
454
		// Without visiting the forum this session variable might not be set on submit.
455
		if (isset($_SESSION['USER_AGENT']))
456
		{
457
			return;
458
		}
459
460
		if (isset($_GET['ssi_function']) && $_GET['ssi_function'] === 'pollVote')
461
		{
462
			return;
463
		}
464
465
		$_SESSION['USER_AGENT'] = $req->user_agent();
466
	}
467
468
	/**
469
	 * Used to ensure SSI requests are valid and not a probing attempt
470
	 */
471
	private function _validRequestCheck()
472
	{
473
		global $ssi_theme, $ssi_layers;
474
475
		// Check on any hacking attempts.
476
		if (
477
			isset($_REQUEST['GLOBALS']) || isset($_COOKIE['GLOBALS'])
478
			|| isset($_REQUEST['ssi_theme']) && (int) $_REQUEST['ssi_theme'] === (int) $ssi_theme
479
			|| isset($_COOKIE['ssi_theme']) && (int) $_COOKIE['ssi_theme'] === (int) $ssi_theme
480
			|| isset($_REQUEST['ssi_layers'], $ssi_layers) && $_REQUEST['ssi_layers'] == $ssi_layers
481
			|| isset($_REQUEST['context']))
482
		{
483
			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...
484
		}
485
	}
486
}
487