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