Issues (1061)

other/install.php (7 issues)

1
<?php
2
3
/**
4
 * Simple Machines Forum (SMF)
5
 *
6
 * @package SMF
7
 * @author Simple Machines https://www.simplemachines.org
8
 * @copyright 2020 Simple Machines and individual contributors
9
 * @license https://www.simplemachines.org/about/smf/license.php BSD
10
 *
11
 * @version 2.1 RC2
12
 */
13
14
define('SMF_VERSION', '2.1 RC2');
15
define('SMF_FULL_VERSION', 'SMF ' . SMF_VERSION);
16
define('SMF_SOFTWARE_YEAR', '2020');
17
define('DB_SCRIPT_VERSION', '2-1');
18
define('SMF_INSTALLING', 1);
19
20
define('JQUERY_VERSION', '3.4.1');
21
define('POSTGRE_TITLE', 'PostgreSQL');
22
define('MYSQL_TITLE', 'MySQL');
23
define('SMF_USER_AGENT', 'Mozilla/5.0 (' . php_uname('s') . ' ' . php_uname('m') . ') AppleWebKit/605.1.15 (KHTML, like Gecko)  SMF/' . strtr(SMF_VERSION, ' ', '.'));
24
if (!defined('TIME_START'))
25
	define('TIME_START', microtime(true));
26
27
$GLOBALS['required_php_version'] = '5.4.0';
28
29
// Don't have PHP support, do you?
30
// ><html dir="ltr"><head><title>Error!</title></head><body>Sorry, this installer requires PHP!<div style="display: none;">
31
32
// Let's pull in useful classes
33
if (!defined('SMF'))
34
	define('SMF', 1);
35
36
require_once('Sources/Class-Package.php');
37
38
// Database info.
39
$databases = array(
40
	'mysql' => array(
41
		'name' => 'MySQL',
42
		'version' => '5.0.22',
43
		'version_check' => 'return min(mysqli_get_server_info($db_connection), mysqli_get_client_info());',
44
		'supported' => function_exists('mysqli_connect'),
45
		'default_user' => 'mysql.default_user',
46
		'default_password' => 'mysql.default_password',
47
		'default_host' => 'mysql.default_host',
48
		'default_port' => 'mysql.default_port',
49
		'utf8_support' => function()
50
		{
51
			return true;
52
		},
53
		'utf8_version' => '5.0.22',
54
		'utf8_version_check' => 'return mysqli_get_server_info($db_connection);',
55
		'utf8_default' => true,
56
		'utf8_required' => true,
57
		'alter_support' => true,
58
		'validate_prefix' => function(&$value)
59
		{
60
			$value = preg_replace('~[^A-Za-z0-9_\$]~', '', $value);
61
			return true;
62
		},
63
	),
64
	'postgresql' => array(
65
		'name' => 'PostgreSQL',
66
		'version' => '9.4',
67
		'function_check' => 'pg_connect',
68
		'version_check' => '$request = pg_query(\'SELECT version()\'); list ($version) = pg_fetch_row($request); list($pgl, $version) = explode(" ", $version); return $version;',
69
		'supported' => function_exists('pg_connect'),
70
		'always_has_db' => true,
71
		'utf8_default' => true,
72
		'utf8_required' => true,
73
		'utf8_support' => function()
74
		{
75
			$request = pg_query('SHOW SERVER_ENCODING');
0 ignored issues
show
The call to pg_query() has too few arguments starting with query. ( Ignorable by Annotation )

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

75
			$request = /** @scrutinizer ignore-call */ pg_query('SHOW SERVER_ENCODING');

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
'SHOW SERVER_ENCODING' of type string is incompatible with the type resource expected by parameter $connection of pg_query(). ( Ignorable by Annotation )

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

75
			$request = pg_query(/** @scrutinizer ignore-type */ 'SHOW SERVER_ENCODING');
Loading history...
76
77
			list ($charcode) = pg_fetch_row($request);
78
79
			if ($charcode == 'UTF8')
80
				return true;
81
			else
82
				return false;
83
		},
84
		'utf8_version' => '8.0',
85
		'utf8_version_check' => '$request = pg_query(\'SELECT version()\'); list ($version) = pg_fetch_row($request); list($pgl, $version) = explode(" ", $version); return $version;',
86
		'validate_prefix' => function(&$value)
87
		{
88
			global $txt;
89
90
			$value = preg_replace('~[^A-Za-z0-9_\$]~', '', $value);
91
92
			// Is it reserved?
93
			if ($value == 'pg_')
94
				return $txt['error_db_prefix_reserved'];
95
96
			// Is the prefix numeric?
97
			if (preg_match('~^\d~', $value))
98
				return $txt['error_db_prefix_numeric'];
99
100
			return true;
101
		},
102
	),
103
);
104
105
global $txt;
106
107
// Initialize everything and load the language files.
108
initialize_inputs();
109
load_lang_file();
110
111
// This is what we are.
112
$installurl = $_SERVER['PHP_SELF'];
113
114
// All the steps in detail.
115
// Number,Name,Function,Progress Weight.
116
$incontext['steps'] = array(
117
	0 => array(1, $txt['install_step_welcome'], 'Welcome', 0),
118
	1 => array(2, $txt['install_step_writable'], 'CheckFilesWritable', 10),
119
	2 => array(3, $txt['install_step_databaseset'], 'DatabaseSettings', 15),
120
	3 => array(4, $txt['install_step_forum'], 'ForumSettings', 40),
121
	4 => array(5, $txt['install_step_databasechange'], 'DatabasePopulation', 15),
122
	5 => array(6, $txt['install_step_admin'], 'AdminAccount', 20),
123
	6 => array(7, $txt['install_step_delete'], 'DeleteInstall', 0),
124
);
125
126
// Default title...
127
$incontext['page_title'] = $txt['smf_installer'];
128
129
// What step are we on?
130
$incontext['current_step'] = isset($_GET['step']) ? (int) $_GET['step'] : 0;
131
132
// Loop through all the steps doing each one as required.
133
$incontext['overall_percent'] = 0;
134
135
foreach ($incontext['steps'] as $num => $step)
136
{
137
	if ($num >= $incontext['current_step'])
138
	{
139
		// The current weight of this step in terms of overall progress.
140
		$incontext['step_weight'] = $step[3];
141
		// Make sure we reset the skip button.
142
		$incontext['skip'] = false;
143
144
		// Call the step and if it returns false that means pause!
145
		if (function_exists($step[2]) && $step[2]() === false)
146
			break;
147
		elseif (function_exists($step[2]))
148
			$incontext['current_step']++;
149
150
		// No warnings pass on.
151
		$incontext['warning'] = '';
152
	}
153
	$incontext['overall_percent'] += $step[3];
154
}
155
156
// Actually do the template stuff.
157
installExit();
158
159
function initialize_inputs()
160
{
161
	global $databases;
162
163
	// Just so people using older versions of PHP aren't left in the cold.
164
	if (!isset($_SERVER['PHP_SELF']))
165
		$_SERVER['PHP_SELF'] = isset($GLOBALS['HTTP_SERVER_VARS']['PHP_SELF']) ? $GLOBALS['HTTP_SERVER_VARS']['PHP_SELF'] : 'install.php';
166
167
	// In pre-release versions, report all errors.
168
	if (strspn(SMF_VERSION, '1234567890.') !== strlen(SMF_VERSION))
169
		error_reporting(E_ALL);
170
	// Otherwise, report all errors except for deprecation notices.
171
	else
172
		error_reporting(E_ALL & ~E_DEPRECATED);
173
174
	// Fun.  Low PHP version...
175
	if (!isset($_GET))
176
	{
177
		$GLOBALS['_GET']['step'] = 0;
178
		return;
179
	}
180
181
	if (!isset($_GET['obgz']))
182
	{
183
		ob_start();
184
185
		if (ini_get('session.save_handler') == 'user')
186
			@ini_set('session.save_handler', 'files');
187
		if (function_exists('session_start'))
188
			@session_start();
189
	}
190
	else
191
	{
192
		ob_start('ob_gzhandler');
193
194
		if (ini_get('session.save_handler') == 'user')
195
			@ini_set('session.save_handler', 'files');
196
		session_start();
197
198
		if (!headers_sent())
199
			echo '<!DOCTYPE html>
200
<html>
201
	<head>
202
		<title>', htmlspecialchars($_GET['pass_string']), '</title>
203
	</head>
204
	<body style="background-color: #d4d4d4; margin-top: 16%; text-align: center; font-size: 16pt;">
205
		<strong>', htmlspecialchars($_GET['pass_string']), '</strong>
206
	</body>
207
</html>';
208
		exit;
209
	}
210
211
	// This is really quite simple; if ?delete is on the URL, delete the installer...
212
	if (isset($_GET['delete']))
213
	{
214
		if (isset($_SESSION['installer_temp_ftp']))
215
		{
216
			$ftp = new ftp_connection($_SESSION['installer_temp_ftp']['server'], $_SESSION['installer_temp_ftp']['port'], $_SESSION['installer_temp_ftp']['username'], $_SESSION['installer_temp_ftp']['password']);
217
			$ftp->chdir($_SESSION['installer_temp_ftp']['path']);
218
219
			$ftp->unlink('install.php');
220
221
			foreach ($databases as $key => $dummy)
222
			{
223
				$type = ($key == 'mysqli') ? 'mysql' : $key;
224
				$ftp->unlink('install_' . DB_SCRIPT_VERSION . '_' . $type . '.sql');
225
			}
226
227
			$ftp->close();
228
229
			unset($_SESSION['installer_temp_ftp']);
230
		}
231
		else
232
		{
233
			@unlink(__FILE__);
234
235
			foreach ($databases as $key => $dummy)
236
			{
237
				$type = ($key == 'mysqli') ? 'mysql' : $key;
238
				@unlink(dirname(__FILE__) . '/install_' . DB_SCRIPT_VERSION . '_' . $type . '.sql');
239
			}
240
		}
241
242
		// Now just redirect to a blank.png...
243
		$secure = false;
244
245
		if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
246
			$secure = true;
247
		elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on')
248
			$secure = true;
249
250
		header('location: http' . ($secure ? 's' : '') . '://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT']) . dirname($_SERVER['PHP_SELF']) . '/Themes/default/images/blank.png');
251
		exit;
252
	}
253
254
	// PHP 5 might cry if we don't do this now.
255
	if (function_exists('date_default_timezone_set'))
256
	{
257
		// Get PHP's default timezone, if set
258
		$ini_tz = ini_get('date.timezone');
259
		if (!empty($ini_tz))
260
			$timezone_id = $ini_tz;
261
		else
262
			$timezone_id = '';
263
264
		// If date.timezone is unset, invalid, or just plain weird, make a best guess
265
		if (!in_array($timezone_id, timezone_identifiers_list()))
0 ignored issues
show
It seems like timezone_identifiers_list() can also be of type false; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

265
		if (!in_array($timezone_id, /** @scrutinizer ignore-type */ timezone_identifiers_list()))
Loading history...
266
		{
267
			$server_offset = @mktime(0, 0, 0, 1, 1, 1970);
268
			$timezone_id = timezone_name_from_abbr('', $server_offset, 0);
269
		}
270
271
		date_default_timezone_set($timezone_id);
272
	}
273
	header('X-Frame-Options: SAMEORIGIN');
274
	header('X-XSS-Protection: 1');
275
	header('X-Content-Type-Options: nosniff');
276
277
	// Force an integer step, defaulting to 0.
278
	$_GET['step'] = (int) @$_GET['step'];
279
}
280
281
// Load the list of language files, and the current language file.
282
function load_lang_file()
283
{
284
	global $incontext, $user_info, $txt;
285
286
	$incontext['detected_languages'] = array();
287
288
	// Make sure the languages directory actually exists.
289
	if (file_exists(dirname(__FILE__) . '/Themes/default/languages'))
290
	{
291
		// Find all the "Install" language files in the directory.
292
		$dir = dir(dirname(__FILE__) . '/Themes/default/languages');
293
		while ($entry = $dir->read())
294
		{
295
			if (substr($entry, 0, 8) == 'Install.' && substr($entry, -4) == '.php')
296
				$incontext['detected_languages'][$entry] = ucfirst(substr($entry, 8, strlen($entry) - 12));
297
		}
298
		$dir->close();
299
	}
300
301
	// Didn't find any, show an error message!
302
	if (empty($incontext['detected_languages']))
303
	{
304
		// Let's not cache this message, eh?
305
		header('expires: Mon, 26 Jul 1997 05:00:00 GMT');
306
		header('last-modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
307
		header('cache-control: no-cache');
308
309
		echo '<!DOCTYPE html>
310
<html>
311
	<head>
312
		<title>SMF Installer: Error!</title>
313
		<style>
314
			body {
315
				font-family: sans-serif;
316
				max-width: 700px; }
317
318
			h1 {
319
				font-size: 14pt; }
320
321
			.directory {
322
				margin: 0.3em;
323
				font-family: monospace;
324
				font-weight: bold; }
325
		</style>
326
	</head>
327
	<body>
328
		<h1>A critical error has occurred.</h1>
329
330
		<p>This installer was unable to find the installer\'s language file or files. They should be found under:</p>
331
332
		<div class="directory">', dirname($_SERVER['PHP_SELF']) != '/' ? dirname($_SERVER['PHP_SELF']) : '', '/Themes/default/languages</div>
333
334
		<p>In some cases, FTP clients do not properly upload files with this many folders. Please double check to make sure you <strong>have uploaded all the files in the distribution</strong>.</p>
335
		<p>If that doesn\'t help, please make sure this install.php file is in the same place as the Themes folder.</p>
336
		<p>If you continue to get this error message, feel free to <a href="https://support.simplemachines.org/">look to us for support</a>.</p>
337
	</div></body>
338
</html>';
339
		die;
340
	}
341
342
	// Override the language file?
343
	if (isset($_GET['lang_file']))
344
		$_SESSION['installer_temp_lang'] = $_GET['lang_file'];
345
	elseif (isset($GLOBALS['HTTP_GET_VARS']['lang_file']))
346
		$_SESSION['installer_temp_lang'] = $GLOBALS['HTTP_GET_VARS']['lang_file'];
347
348
	// Make sure it exists, if it doesn't reset it.
349
	if (!isset($_SESSION['installer_temp_lang']) || preg_match('~[^\\w_\\-.]~', $_SESSION['installer_temp_lang']) === 1 || !file_exists(dirname(__FILE__) . '/Themes/default/languages/' . $_SESSION['installer_temp_lang']))
350
	{
351
		// Use the first one...
352
		list ($_SESSION['installer_temp_lang']) = array_keys($incontext['detected_languages']);
353
354
		// If we have english and some other language, use the other language.  We Americans hate english :P.
355
		if ($_SESSION['installer_temp_lang'] == 'Install.english.php' && count($incontext['detected_languages']) > 1)
356
			list (, $_SESSION['installer_temp_lang']) = array_keys($incontext['detected_languages']);
357
	}
358
359
	// And now include the actual language file itself.
360
	require_once(dirname(__FILE__) . '/Themes/default/languages/' . $_SESSION['installer_temp_lang']);
361
362
	// Which language did we load? Assume that he likes his language.
363
	preg_match('~^Install\.(.+[^-utf8])\.php$~', $_SESSION['installer_temp_lang'], $matches);
364
	$user_info['language'] = $matches[1];
365
}
366
367
// This handy function loads some settings and the like.
368
function load_database()
369
{
370
	global $db_prefix, $db_connection, $sourcedir, $smcFunc, $modSettings, $db_port;
371
	global $db_server, $db_passwd, $db_type, $db_name, $db_user, $db_persist, $db_mb4;
372
373
	if (empty($sourcedir))
374
		$sourcedir = dirname(__FILE__) . '/Sources';
375
376
	// Need this to check whether we need the database password.
377
	require(dirname(__FILE__) . '/Settings.php');
378
	if (!defined('SMF'))
379
		define('SMF', 1);
380
	if (empty($smcFunc))
381
		$smcFunc = array();
382
383
	$modSettings['disableQueryCheck'] = true;
384
385
	// Connect the database.
386
	if (!$db_connection)
387
	{
388
		require_once($sourcedir . '/Subs-Db-' . $db_type . '.php');
389
390
		$options = array('persist' => $db_persist);
391
392
		if (!empty($db_port))
393
			$options['port'] = $db_port;
394
395
		if (!empty($db_mb4))
396
			$options['db_mb4'] = $db_mb4;
397
398
		if (!$db_connection)
399
			$db_connection = smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, $options);
400
	}
401
}
402
403
// This is called upon exiting the installer, for template etc.
404
function installExit($fallThrough = false)
405
{
406
	global $incontext, $installurl, $txt;
407
408
	// Send character set.
409
	header('content-type: text/html; charset=' . (isset($txt['lang_character_set']) ? $txt['lang_character_set'] : 'UTF-8'));
410
411
	// We usually dump our templates out.
412
	if (!$fallThrough)
413
	{
414
		// The top install bit.
415
		template_install_above();
416
417
		// Call the template.
418
		if (isset($incontext['sub_template']))
419
		{
420
			$incontext['form_url'] = $installurl . '?step=' . $incontext['current_step'];
421
422
			call_user_func('template_' . $incontext['sub_template']);
423
		}
424
		// @todo REMOVE THIS!!
425
		else
426
		{
427
			if (function_exists('doStep' . $_GET['step']))
428
				call_user_func('doStep' . $_GET['step']);
429
		}
430
		// Show the footer.
431
		template_install_below();
432
	}
433
434
	// Bang - gone!
435
	die();
436
}
437
438
function Welcome()
439
{
440
	global $incontext, $txt, $databases, $installurl;
441
442
	$incontext['page_title'] = $txt['install_welcome'];
443
	$incontext['sub_template'] = 'welcome_message';
444
445
	// Done the submission?
446
	if (isset($_POST['contbutt']))
447
		return true;
448
449
	// See if we think they have already installed it?
450
	if (is_readable(dirname(__FILE__) . '/Settings.php'))
451
	{
452
		$probably_installed = 0;
453
		foreach (file(dirname(__FILE__) . '/Settings.php') as $line)
454
		{
455
			if (preg_match('~^\$db_passwd\s=\s\'([^\']+)\';$~', $line))
456
				$probably_installed++;
457
			if (preg_match('~^\$boardurl\s=\s\'([^\']+)\';~', $line) && !preg_match('~^\$boardurl\s=\s\'http://127\.0\.0\.1/smf\';~', $line))
458
				$probably_installed++;
459
		}
460
461
		if ($probably_installed == 2)
462
			$incontext['warning'] = $txt['error_already_installed'];
463
	}
464
465
	// Is some database support even compiled in?
466
	$incontext['supported_databases'] = array();
467
	foreach ($databases as $key => $db)
468
	{
469
		if ($db['supported'])
470
		{
471
			$type = ($key == 'mysqli') ? 'mysql' : $key;
472
			if (!file_exists(dirname(__FILE__) . '/install_' . DB_SCRIPT_VERSION . '_' . $type . '.sql'))
473
			{
474
				$databases[$key]['supported'] = false;
475
				$notFoundSQLFile = true;
476
				$txt['error_db_script_missing'] = sprintf($txt['error_db_script_missing'], 'install_' . DB_SCRIPT_VERSION . '_' . $type . '.sql');
477
			}
478
			else
479
				$incontext['supported_databases'][] = $db;
480
		}
481
	}
482
483
	// Check the PHP version.
484
	if ((!function_exists('version_compare') || version_compare($GLOBALS['required_php_version'], PHP_VERSION, '>=')))
485
		$error = 'error_php_too_low';
486
	// Make sure we have a supported database
487
	elseif (empty($incontext['supported_databases']))
488
		$error = empty($notFoundSQLFile) ? 'error_db_missing' : 'error_db_script_missing';
489
	// How about session support?  Some crazy sysadmin remove it?
490
	elseif (!function_exists('session_start'))
491
		$error = 'error_session_missing';
492
	// Make sure they uploaded all the files.
493
	elseif (!file_exists(dirname(__FILE__) . '/index.php'))
494
		$error = 'error_missing_files';
495
	// Very simple check on the session.save_path for Windows.
496
	// @todo Move this down later if they don't use database-driven sessions?
497
	elseif (@ini_get('session.save_path') == '/tmp' && substr(__FILE__, 1, 2) == ':\\')
498
		$error = 'error_session_save_path';
499
500
	// Since each of the three messages would look the same, anyway...
501
	if (isset($error))
502
		$incontext['error'] = $txt[$error];
503
504
	// Mod_security blocks everything that smells funny. Let SMF handle security.
505
	if (!fixModSecurity() && !isset($_GET['overmodsecurity']))
506
		$incontext['error'] = $txt['error_mod_security'] . '<br><br><a href="' . $installurl . '?overmodsecurity=true">' . $txt['error_message_click'] . '</a> ' . $txt['error_message_bad_try_again'];
507
508
	// Confirm mbstring is loaded...
509
	if (!extension_loaded('mbstring'))
510
		$incontext['error'] = $txt['install_no_mbstring'];
511
512
	// Check for https stream support.
513
	$supported_streams = stream_get_wrappers();
514
	if (!in_array('https', $supported_streams))
515
		$incontext['warning'] = $txt['install_no_https'];
516
517
	return false;
518
}
519
520
function CheckFilesWritable()
521
{
522
	global $txt, $incontext;
523
524
	$incontext['page_title'] = $txt['ftp_checking_writable'];
525
	$incontext['sub_template'] = 'chmod_files';
526
527
	$writable_files = array(
528
		'attachments',
529
		'avatars',
530
		'custom_avatar',
531
		'cache',
532
		'Packages',
533
		'Smileys',
534
		'Themes',
535
		'agreement.txt',
536
		'Settings.php',
537
		'Settings_bak.php',
538
		'cache/db_last_error.php',
539
	);
540
541
	foreach ($incontext['detected_languages'] as $lang => $temp)
542
		$extra_files[] = 'Themes/default/languages/' . $lang;
543
544
	// With mod_security installed, we could attempt to fix it with .htaccess.
545
	if (function_exists('apache_get_modules') && in_array('mod_security', apache_get_modules()))
546
		$writable_files[] = file_exists(dirname(__FILE__) . '/.htaccess') ? '.htaccess' : '.';
547
548
	$failed_files = array();
549
550
	// On linux, it's easy - just use is_writable!
551
	if (substr(__FILE__, 1, 2) != ':\\')
552
	{
553
		$incontext['systemos'] = 'linux';
554
555
		foreach ($writable_files as $file)
556
		{
557
			// Some files won't exist, try to address up front
558
			if (!file_exists(dirname(__FILE__) . '/' . $file))
559
				@touch(dirname(__FILE__) . '/' . $file);
560
			// NOW do the writable check...
561
			if (!is_writable(dirname(__FILE__) . '/' . $file))
562
			{
563
				@chmod(dirname(__FILE__) . '/' . $file, 0755);
564
565
				// Well, 755 hopefully worked... if not, try 777.
566
				if (!is_writable(dirname(__FILE__) . '/' . $file) && !@chmod(dirname(__FILE__) . '/' . $file, 0777))
567
					$failed_files[] = $file;
568
			}
569
		}
570
		foreach ($extra_files as $file)
571
			@chmod(dirname(__FILE__) . (empty($file) ? '' : '/' . $file), 0777);
572
	}
573
	// Windows is trickier.  Let's try opening for r+...
574
	else
575
	{
576
		$incontext['systemos'] = 'windows';
577
578
		foreach ($writable_files as $file)
579
		{
580
			// Folders can't be opened for write... but the index.php in them can ;)
581
			if (is_dir(dirname(__FILE__) . '/' . $file))
582
				$file .= '/index.php';
583
584
			// Funny enough, chmod actually does do something on windows - it removes the read only attribute.
585
			@chmod(dirname(__FILE__) . '/' . $file, 0777);
586
			$fp = @fopen(dirname(__FILE__) . '/' . $file, 'r+');
587
588
			// Hmm, okay, try just for write in that case...
589
			if (!is_resource($fp))
590
				$fp = @fopen(dirname(__FILE__) . '/' . $file, 'w');
591
592
			if (!is_resource($fp))
593
				$failed_files[] = $file;
594
595
			@fclose($fp);
0 ignored issues
show
It seems like $fp can also be of type false; however, parameter $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

595
			@fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
596
		}
597
		foreach ($extra_files as $file)
598
			@chmod(dirname(__FILE__) . (empty($file) ? '' : '/' . $file), 0777);
599
	}
600
601
	$failure = count($failed_files) >= 1;
602
603
	if (!isset($_SERVER))
604
		return !$failure;
605
606
	// Put the list into context.
607
	$incontext['failed_files'] = $failed_files;
608
609
	// It's not going to be possible to use FTP on windows to solve the problem...
610
	if ($failure && substr(__FILE__, 1, 2) == ':\\')
611
	{
612
		$incontext['error'] = $txt['error_windows_chmod'] . '
613
					<ul class="error_content">
614
						<li>' . implode('</li>
615
						<li>', $failed_files) . '</li>
616
					</ul>';
617
618
		return false;
619
	}
620
	// We're going to have to use... FTP!
621
	elseif ($failure)
622
	{
623
		// Load any session data we might have...
624
		if (!isset($_POST['ftp_username']) && isset($_SESSION['installer_temp_ftp']))
625
		{
626
			$_POST['ftp_server'] = $_SESSION['installer_temp_ftp']['server'];
627
			$_POST['ftp_port'] = $_SESSION['installer_temp_ftp']['port'];
628
			$_POST['ftp_username'] = $_SESSION['installer_temp_ftp']['username'];
629
			$_POST['ftp_password'] = $_SESSION['installer_temp_ftp']['password'];
630
			$_POST['ftp_path'] = $_SESSION['installer_temp_ftp']['path'];
631
		}
632
633
		$incontext['ftp_errors'] = array();
634
		require_once('Sources/Class-Package.php');
635
		if (isset($_POST['ftp_username']))
636
		{
637
			$ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
638
639
			if ($ftp->error === false)
640
			{
641
				// Try it without /home/abc just in case they messed up.
642
				if (!$ftp->chdir($_POST['ftp_path']))
643
				{
644
					$incontext['ftp_errors'][] = $ftp->last_message;
645
					$ftp->chdir(preg_replace('~^/home[2]?/[^/]+?~', '', $_POST['ftp_path']));
646
				}
647
			}
648
		}
649
650
		if (!isset($ftp) || $ftp->error !== false)
651
		{
652
			if (!isset($ftp))
653
				$ftp = new ftp_connection(null);
654
			// Save the error so we can mess with listing...
655
			elseif ($ftp->error !== false && empty($incontext['ftp_errors']) && !empty($ftp->last_message))
656
				$incontext['ftp_errors'][] = $ftp->last_message;
657
658
			list ($username, $detect_path, $found_path) = $ftp->detect_path(dirname(__FILE__));
659
660
			if (empty($_POST['ftp_path']) && $found_path)
661
				$_POST['ftp_path'] = $detect_path;
662
663
			if (!isset($_POST['ftp_username']))
664
				$_POST['ftp_username'] = $username;
665
666
			// Set the username etc, into context.
667
			$incontext['ftp'] = array(
668
				'server' => isset($_POST['ftp_server']) ? $_POST['ftp_server'] : 'localhost',
669
				'port' => isset($_POST['ftp_port']) ? $_POST['ftp_port'] : '21',
670
				'username' => isset($_POST['ftp_username']) ? $_POST['ftp_username'] : '',
671
				'path' => isset($_POST['ftp_path']) ? $_POST['ftp_path'] : '/',
672
				'path_msg' => !empty($found_path) ? $txt['ftp_path_found_info'] : $txt['ftp_path_info'],
673
			);
674
675
			return false;
676
		}
677
		else
678
		{
679
			$_SESSION['installer_temp_ftp'] = array(
680
				'server' => $_POST['ftp_server'],
681
				'port' => $_POST['ftp_port'],
682
				'username' => $_POST['ftp_username'],
683
				'password' => $_POST['ftp_password'],
684
				'path' => $_POST['ftp_path']
685
			);
686
687
			$failed_files_updated = array();
688
689
			foreach ($failed_files as $file)
690
			{
691
				if (!is_writable(dirname(__FILE__) . '/' . $file))
692
					$ftp->chmod($file, 0755);
693
				if (!is_writable(dirname(__FILE__) . '/' . $file))
694
					$ftp->chmod($file, 0777);
695
				if (!is_writable(dirname(__FILE__) . '/' . $file))
696
				{
697
					$failed_files_updated[] = $file;
698
					$incontext['ftp_errors'][] = rtrim($ftp->last_message) . ' -> ' . $file . "\n";
699
				}
700
			}
701
702
			$ftp->close();
703
704
			// Are there any errors left?
705
			if (count($failed_files_updated) >= 1)
706
			{
707
				// Guess there are...
708
				$incontext['failed_files'] = $failed_files_updated;
709
710
				// Set the username etc, into context.
711
				$incontext['ftp'] = $_SESSION['installer_temp_ftp'] += array(
712
					'path_msg' => $txt['ftp_path_info'],
713
				);
714
715
				return false;
716
			}
717
		}
718
	}
719
720
	return true;
721
}
722
723
function DatabaseSettings()
724
{
725
	global $txt, $databases, $incontext, $smcFunc, $sourcedir;
726
	global $db_server, $db_name, $db_user, $db_passwd, $db_port, $db_mb4;
727
728
	$incontext['sub_template'] = 'database_settings';
729
	$incontext['page_title'] = $txt['db_settings'];
730
	$incontext['continue'] = 1;
731
732
	// Set up the defaults.
733
	$incontext['db']['server'] = 'localhost';
734
	$incontext['db']['user'] = '';
735
	$incontext['db']['name'] = '';
736
	$incontext['db']['pass'] = '';
737
	$incontext['db']['type'] = '';
738
	$incontext['supported_databases'] = array();
739
740
	$foundOne = false;
741
	foreach ($databases as $key => $db)
742
	{
743
		// Override with the defaults for this DB if appropriate.
744
		if ($db['supported'])
745
		{
746
			$incontext['supported_databases'][$key] = $db;
747
748
			if (!$foundOne)
749
			{
750
				if (isset($db['default_host']))
751
					$incontext['db']['server'] = ini_get($db['default_host']) or $incontext['db']['server'] = 'localhost';
752
				if (isset($db['default_user']))
753
				{
754
					$incontext['db']['user'] = ini_get($db['default_user']);
755
					$incontext['db']['name'] = ini_get($db['default_user']);
756
				}
757
				if (isset($db['default_password']))
758
					$incontext['db']['pass'] = ini_get($db['default_password']);
759
760
				// For simplicity and less confusion, leave the port blank by default
761
				$incontext['db']['port'] = '';
762
763
				$incontext['db']['type'] = $key;
764
				$foundOne = true;
765
			}
766
		}
767
	}
768
769
	// Override for repost.
770
	if (isset($_POST['db_user']))
771
	{
772
		$incontext['db']['user'] = $_POST['db_user'];
773
		$incontext['db']['name'] = $_POST['db_name'];
774
		$incontext['db']['server'] = $_POST['db_server'];
775
		$incontext['db']['prefix'] = $_POST['db_prefix'];
776
777
		if (!empty($_POST['db_port']))
778
			$incontext['db']['port'] = $_POST['db_port'];
779
	}
780
	else
781
	{
782
		$incontext['db']['prefix'] = 'smf_';
783
	}
784
785
	// Are we submitting?
786
	if (isset($_POST['db_type']))
787
	{
788
		// What type are they trying?
789
		$db_type = preg_replace('~[^A-Za-z0-9]~', '', $_POST['db_type']);
790
		$db_prefix = $_POST['db_prefix'];
791
		// Validate the prefix.
792
		$valid_prefix = $databases[$db_type]['validate_prefix']($db_prefix);
793
794
		if ($valid_prefix !== true)
795
		{
796
			$incontext['error'] = $valid_prefix;
797
			return false;
798
		}
799
800
		// Take care of these variables...
801
		$vars = array(
802
			'db_type' => $db_type,
803
			'db_name' => $_POST['db_name'],
804
			'db_user' => $_POST['db_user'],
805
			'db_passwd' => isset($_POST['db_passwd']) ? $_POST['db_passwd'] : '',
806
			'db_server' => $_POST['db_server'],
807
			'db_prefix' => $db_prefix,
808
			// The cookiename is special; we want it to be the same if it ever needs to be reinstalled with the same info.
809
			'cookiename' => 'SMFCookie' . abs(crc32($_POST['db_name'] . preg_replace('~[^A-Za-z0-9_$]~', '', $_POST['db_prefix'])) % 1000),
810
		);
811
812
		// Only set the port if we're not using the default
813
		if (!empty($_POST['db_port']))
814
		{
815
			// For MySQL, we can get the "default port" from PHP. PostgreSQL has no such option though.
816
			if (($db_type == 'mysql' || $db_type == 'mysqli') && $_POST['db_port'] != ini_get($db_type . '.default_port'))
817
				$vars['db_port'] = (int) $_POST['db_port'];
818
			elseif ($db_type == 'postgresql' && $_POST['db_port'] != 5432)
819
				$vars['db_port'] = (int) $_POST['db_port'];
820
		}
821
822
		// God I hope it saved!
823
		if (!installer_updateSettingsFile($vars))
824
		{
825
			$incontext['error'] = $txt['settings_error'];
826
			return false;
827
		}
828
829
		// Make sure it works.
830
		require(dirname(__FILE__) . '/Settings.php');
831
832
		if (empty($sourcedir))
833
			$sourcedir = dirname(__FILE__) . '/Sources';
834
835
		// Better find the database file!
836
		if (!file_exists($sourcedir . '/Subs-Db-' . $db_type . '.php'))
837
		{
838
			$incontext['error'] = sprintf($txt['error_db_file'], 'Subs-Db-' . $db_type . '.php');
839
			return false;
840
		}
841
842
		// Now include it for database functions!
843
		if (!defined('SMF'))
844
			define('SMF', 1);
845
846
		$modSettings['disableQueryCheck'] = true;
847
		if (empty($smcFunc))
848
			$smcFunc = array();
849
850
		require_once($sourcedir . '/Subs-Db-' . $db_type . '.php');
851
852
		// Attempt a connection.
853
		$needsDB = !empty($databases[$db_type]['always_has_db']);
854
855
		$options = array('non_fatal' => true, 'dont_select_db' => !$needsDB);
856
		// Add in the port if needed
857
		if (!empty($db_port))
858
			$options['port'] = $db_port;
859
860
		if (!empty($db_mb4))
861
			$options['db_mb4'] = $db_mb4;
862
863
		$db_connection = smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, $options);
864
865
		// No dice?  Let's try adding the prefix they specified, just in case they misread the instructions ;)
866
		if ($db_connection == null)
867
		{
868
			$db_error = @$smcFunc['db_error']();
869
870
			$db_connection = smf_db_initiate($db_server, $db_name, $_POST['db_prefix'] . $db_user, $db_passwd, $db_prefix, $options);
871
			if ($db_connection != null)
872
			{
873
				$db_user = $_POST['db_prefix'] . $db_user;
874
				installer_updateSettingsFile(array('db_user' => $db_user));
875
			}
876
		}
877
878
		// Still no connection?  Big fat error message :P.
879
		if (!$db_connection)
880
		{
881
			$incontext['error'] = $txt['error_db_connect'] . '<div class="error_content"><strong>' . $db_error . '</strong></div>';
882
			return false;
883
		}
884
885
		// Do they meet the install requirements?
886
		// @todo Old client, new server?
887
		if (version_compare($databases[$db_type]['version'], preg_replace('~^\D*|\-.+?$~', '', eval($databases[$db_type]['version_check']))) > 0)
888
		{
889
			$incontext['error'] = $txt['error_db_too_low'];
890
			return false;
891
		}
892
893
		// Let's try that database on for size... assuming we haven't already lost the opportunity.
894
		if ($db_name != '' && !$needsDB)
895
		{
896
			$smcFunc['db_query']('', "
897
				CREATE DATABASE IF NOT EXISTS `$db_name`",
898
				array(
899
					'security_override' => true,
900
					'db_error_skip' => true,
901
				),
902
				$db_connection
903
			);
904
905
			// Okay, let's try the prefix if it didn't work...
906
			if (!$smcFunc['db_select_db']($db_name, $db_connection) && $db_name != '')
907
			{
908
				$smcFunc['db_query']('', "
909
					CREATE DATABASE IF NOT EXISTS `$_POST[db_prefix]$db_name`",
910
					array(
911
						'security_override' => true,
912
						'db_error_skip' => true,
913
					),
914
					$db_connection
915
				);
916
917
				if ($smcFunc['db_select_db']($_POST['db_prefix'] . $db_name, $db_connection))
918
				{
919
					$db_name = $_POST['db_prefix'] . $db_name;
920
					installer_updateSettingsFile(array('db_name' => $db_name));
921
				}
922
			}
923
924
			// Okay, now let's try to connect...
925
			if (!$smcFunc['db_select_db']($db_name, $db_connection))
926
			{
927
				$incontext['error'] = sprintf($txt['error_db_database'], $db_name);
928
				return false;
929
			}
930
		}
931
932
		return true;
933
	}
934
935
	return false;
936
}
937
938
// Let's start with basic forum type settings.
939
function ForumSettings()
940
{
941
	global $txt, $incontext, $databases, $db_type, $db_connection, $smcFunc;
942
943
	$incontext['sub_template'] = 'forum_settings';
944
	$incontext['page_title'] = $txt['install_settings'];
945
946
	// Let's see if we got the database type correct.
947
	if (isset($_POST['db_type'], $databases[$_POST['db_type']]))
948
		$db_type = $_POST['db_type'];
949
950
	// Else we'd better be able to get the connection.
951
	else
952
		load_database();
953
954
	$db_type = isset($_POST['db_type']) ? $_POST['db_type'] : $db_type;
955
956
	// What host and port are we on?
957
	$host = empty($_SERVER['HTTP_HOST']) ? $_SERVER['SERVER_NAME'] . (empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT']) : $_SERVER['HTTP_HOST'];
958
959
	$secure = false;
960
961
	if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
962
		$secure = true;
963
	elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on')
964
		$secure = true;
965
966
	// Now, to put what we've learned together... and add a path.
967
	$incontext['detected_url'] = 'http' . ($secure ? 's' : '') . '://' . $host . substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));
968
969
	// Check if the database sessions will even work.
970
	$incontext['test_dbsession'] = (ini_get('session.auto_start') != 1);
971
	$incontext['utf8_default'] = $databases[$db_type]['utf8_default'];
972
	$incontext['utf8_required'] = $databases[$db_type]['utf8_required'];
973
974
	$incontext['continue'] = 1;
975
976
	// Check Postgres setting
977
	if ( $db_type === 'postgresql')
978
	{
979
		load_database();
980
		$result = $smcFunc['db_query']('', '
981
			show standard_conforming_strings',
982
			array(
983
				'db_error_skip' => true,
984
			)
985
		);
986
987
		if ($result !== false)
988
		{
989
			$row = $smcFunc['db_fetch_assoc']($result);
990
			if ($row['standard_conforming_strings'] !== 'on')
991
				{
992
					$incontext['continue'] = 0;
993
					$incontext['error'] = $txt['error_pg_scs'];
994
				}
995
			$smcFunc['db_free_result']($result);
996
		}
997
	}
998
999
	// Setup the SSL checkbox...
1000
	$incontext['ssl_chkbx_protected'] = false;
1001
	$incontext['ssl_chkbx_checked'] = false;
1002
1003
	// If redirect in effect, force ssl ON
1004
	require_once(dirname(__FILE__) . '/Sources/Subs.php');
1005
	if (https_redirect_active($incontext['detected_url']))
1006
	{
1007
		$incontext['ssl_chkbx_protected'] = true;
1008
		$incontext['ssl_chkbx_checked'] = true;
1009
		$_POST['force_ssl'] = true;
1010
	}
1011
	// If no cert, make sure ssl stays OFF
1012
	if (!ssl_cert_found($incontext['detected_url']))
1013
	{
1014
		$incontext['ssl_chkbx_protected'] = true;
1015
		$incontext['ssl_chkbx_checked'] = false;
1016
	}
1017
1018
	// Submitting?
1019
	if (isset($_POST['boardurl']))
1020
	{
1021
		if (substr($_POST['boardurl'], -10) == '/index.php')
1022
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -10);
1023
		elseif (substr($_POST['boardurl'], -1) == '/')
1024
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -1);
1025
		if (substr($_POST['boardurl'], 0, 7) != 'http://' && substr($_POST['boardurl'], 0, 7) != 'file://' && substr($_POST['boardurl'], 0, 8) != 'https://')
1026
			$_POST['boardurl'] = 'http://' . $_POST['boardurl'];
1027
1028
		// Make sure boardurl is aligned with ssl setting
1029
		if (empty($_POST['force_ssl']))
1030
			$_POST['boardurl'] = strtr($_POST['boardurl'], array('https://' => 'http://'));
1031
		else
1032
			$_POST['boardurl'] = strtr($_POST['boardurl'], array('http://' => 'https://'));
1033
1034
		// Deal with different operating systems' directory structure...
1035
		$path = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', __DIR__), '/');
1036
1037
		// Load the compatibility library if necessary.
1038
		if (!is_callable('random_bytes'))
1039
			require_once('Sources/random_compat/random.php');
1040
1041
		// Save these variables.
1042
		$vars = array(
1043
			'boardurl' => $_POST['boardurl'],
1044
			'boarddir' => $path,
1045
			'sourcedir' => $path . '/Sources',
1046
			'cachedir' => $path . '/cache',
1047
			'packagesdir' => $path . '/Packages',
1048
			'tasksdir' => $path . '/Sources/tasks',
1049
			'mbname' => strtr($_POST['mbname'], array('\"' => '"')),
1050
			'language' => substr($_SESSION['installer_temp_lang'], 8, -4),
1051
			'image_proxy_secret' => bin2hex(random_bytes(10)),
1052
			'image_proxy_enabled' => !empty($_POST['force_ssl']),
1053
			'auth_secret' => bin2hex(random_bytes(32)),
1054
		);
1055
1056
		// Must save!
1057
		if (!installer_updateSettingsFile($vars))
1058
		{
1059
			$incontext['error'] = $txt['settings_error'];
1060
			return false;
1061
		}
1062
1063
		// Make sure it works.
1064
		require(dirname(__FILE__) . '/Settings.php');
1065
1066
		// UTF-8 requires a setting to override the language charset.
1067
		if ((!empty($databases[$db_type]['utf8_support']) && !empty($databases[$db_type]['utf8_required'])) || (empty($databases[$db_type]['utf8_required']) && !empty($databases[$db_type]['utf8_support']) && isset($_POST['utf8'])))
1068
		{
1069
			if (!$databases[$db_type]['utf8_support']())
1070
			{
1071
				$incontext['error'] = sprintf($txt['error_utf8_support']);
1072
				return false;
1073
			}
1074
1075
			if (!empty($databases[$db_type]['utf8_version_check']) && version_compare($databases[$db_type]['utf8_version'], preg_replace('~\-.+?$~', '', eval($databases[$db_type]['utf8_version_check'])), '>'))
1076
			{
1077
				$incontext['error'] = sprintf($txt['error_utf8_version'], $databases[$db_type]['utf8_version']);
1078
				return false;
1079
			}
1080
			else
1081
				// Set the character set here.
1082
				installer_updateSettingsFile(array('db_character_set' => 'utf8'));
1083
		}
1084
1085
		// Good, skip on.
1086
		return true;
1087
	}
1088
1089
	return false;
1090
}
1091
1092
// Step one: Do the SQL thang.
1093
function DatabasePopulation()
1094
{
1095
	global $db_character_set, $txt, $db_connection, $smcFunc, $databases, $modSettings, $db_type, $db_prefix, $incontext, $db_name, $boardurl;
1096
1097
	$incontext['sub_template'] = 'populate_database';
1098
	$incontext['page_title'] = $txt['db_populate'];
1099
	$incontext['continue'] = 1;
1100
1101
	// Already done?
1102
	if (isset($_POST['pop_done']))
1103
		return true;
1104
1105
	// Reload settings.
1106
	require(dirname(__FILE__) . '/Settings.php');
1107
	load_database();
1108
1109
	// Before running any of the queries, let's make sure another version isn't already installed.
1110
	$result = $smcFunc['db_query']('', '
1111
		SELECT variable, value
1112
		FROM {db_prefix}settings',
1113
		array(
1114
			'db_error_skip' => true,
1115
		)
1116
	);
1117
	$newSettings = array();
1118
	$modSettings = array();
1119
	if ($result !== false)
1120
	{
1121
		while ($row = $smcFunc['db_fetch_assoc']($result))
1122
			$modSettings[$row['variable']] = $row['value'];
1123
		$smcFunc['db_free_result']($result);
1124
1125
		// Do they match?  If so, this is just a refresh so charge on!
1126
		if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] != SMF_VERSION)
1127
		{
1128
			$incontext['error'] = $txt['error_versions_do_not_match'];
1129
			return false;
1130
		}
1131
	}
1132
	$modSettings['disableQueryCheck'] = true;
1133
1134
	// If doing UTF8, select it. PostgreSQL requires passing it as a string...
1135
	if (!empty($db_character_set) && $db_character_set == 'utf8' && !empty($databases[$db_type]['utf8_support']))
1136
		$smcFunc['db_query']('', '
1137
			SET NAMES {string:utf8}',
1138
			array(
1139
				'db_error_skip' => true,
1140
				'utf8' => 'utf8',
1141
			)
1142
		);
1143
1144
	// Windows likes to leave the trailing slash, which yields to C:\path\to\SMF\/attachments...
1145
	if (substr(__DIR__, -1) == '\\')
1146
		$attachdir = __DIR__ . 'attachments';
1147
	else
1148
		$attachdir = __DIR__ . '/attachments';
1149
1150
	$replaces = array(
1151
		'{$db_prefix}' => $db_prefix,
1152
		'{$attachdir}' => json_encode(array(1 => $smcFunc['db_escape_string']($attachdir))),
1153
		'{$boarddir}' => $smcFunc['db_escape_string'](dirname(__FILE__)),
1154
		'{$boardurl}' => $boardurl,
1155
		'{$enableCompressedOutput}' => isset($_POST['compress']) ? '1' : '0',
1156
		'{$databaseSession_enable}' => isset($_POST['dbsession']) ? '1' : '0',
1157
		'{$smf_version}' => SMF_VERSION,
1158
		'{$current_time}' => time(),
1159
		'{$sched_task_offset}' => 82800 + mt_rand(0, 86399),
1160
		'{$registration_method}' => isset($_POST['reg_mode']) ? $_POST['reg_mode'] : 0,
1161
	);
1162
1163
	foreach ($txt as $key => $value)
1164
	{
1165
		if (substr($key, 0, 8) == 'default_')
1166
			$replaces['{$' . $key . '}'] = $smcFunc['db_escape_string']($value);
1167
	}
1168
	$replaces['{$default_reserved_names}'] = strtr($replaces['{$default_reserved_names}'], array('\\\\n' => '\\n'));
1169
1170
	// MySQL-specific stuff - storage engine and UTF8 handling
1171
	if (substr($db_type, 0, 5) == 'mysql')
1172
	{
1173
		// Just in case the query fails for some reason...
1174
		$engines = array();
1175
1176
		// Figure out storage engines - what do we have, etc.
1177
		$get_engines = $smcFunc['db_query']('', 'SHOW ENGINES', array());
1178
1179
		while ($row = $smcFunc['db_fetch_assoc']($get_engines))
1180
		{
1181
			if ($row['Support'] == 'YES' || $row['Support'] == 'DEFAULT')
1182
				$engines[] = $row['Engine'];
1183
		}
1184
1185
		// Done with this now
1186
		$smcFunc['db_free_result']($get_engines);
1187
1188
		// InnoDB is better, so use it if possible...
1189
		$has_innodb = in_array('InnoDB', $engines);
1190
		$replaces['{$engine}'] = $has_innodb ? 'InnoDB' : 'MyISAM';
1191
		$replaces['{$memory}'] = (!$has_innodb && in_array('MEMORY', $engines)) ? 'MEMORY' : $replaces['{$engine}'];
1192
1193
		// If the UTF-8 setting was enabled, add it to the table definitions.
1194
		if (!empty($databases[$db_type]['utf8_support']) && (!empty($databases[$db_type]['utf8_required']) || isset($_POST['utf8'])))
1195
		{
1196
			$replaces['{$engine}'] .= ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
1197
			$replaces['{$memory}'] .= ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
1198
		}
1199
1200
		// One last thing - if we don't have InnoDB, we can't do transactions...
1201
		if (!$has_innodb)
1202
		{
1203
			$replaces['START TRANSACTION;'] = '';
1204
			$replaces['COMMIT;'] = '';
1205
		}
1206
	}
1207
	else
1208
	{
1209
		$has_innodb = false;
1210
	}
1211
1212
	// Read in the SQL.  Turn this on and that off... internationalize... etc.
1213
	$type = ($db_type == 'mysqli' ? 'mysql' : $db_type);
1214
	$sql_lines = explode("\n", strtr(implode(' ', file(dirname(__FILE__) . '/install_' . DB_SCRIPT_VERSION . '_' . $type . '.sql')), $replaces));
0 ignored issues
show
It seems like file(dirname(__FILE__) ..... '_' . $type . '.sql') can also be of type false; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

1214
	$sql_lines = explode("\n", strtr(implode(' ', /** @scrutinizer ignore-type */ file(dirname(__FILE__) . '/install_' . DB_SCRIPT_VERSION . '_' . $type . '.sql')), $replaces));
Loading history...
1215
1216
	// Execute the SQL.
1217
	$current_statement = '';
1218
	$exists = array();
1219
	$incontext['failures'] = array();
1220
	$incontext['sql_results'] = array(
1221
		'tables' => 0,
1222
		'inserts' => 0,
1223
		'table_dups' => 0,
1224
		'insert_dups' => 0,
1225
	);
1226
	foreach ($sql_lines as $count => $line)
1227
	{
1228
		// No comments allowed!
1229
		if (substr(trim($line), 0, 1) != '#')
1230
			$current_statement .= "\n" . rtrim($line);
1231
1232
		// Is this the end of the query string?
1233
		if (empty($current_statement) || (preg_match('~;[\s]*$~s', $line) == 0 && $count != count($sql_lines)))
1234
			continue;
1235
1236
		// Does this table already exist?  If so, don't insert more data into it!
1237
		if (preg_match('~^\s*INSERT INTO ([^\s\n\r]+?)~', $current_statement, $match) != 0 && in_array($match[1], $exists))
1238
		{
1239
			preg_match_all('~\)[,;]~', $current_statement, $matches);
1240
			if (!empty($matches[0]))
1241
				$incontext['sql_results']['insert_dups'] += count($matches[0]);
1242
			else
1243
				$incontext['sql_results']['insert_dups']++;
1244
1245
			$current_statement = '';
1246
			continue;
1247
		}
1248
1249
		if ($smcFunc['db_query']('', $current_statement, array('security_override' => true, 'db_error_skip' => true), $db_connection) === false)
1250
		{
1251
			// Error 1050: Table already exists!
1252
			// @todo Needs to be made better!
1253
			if ((($db_type != 'mysql' && $db_type != 'mysqli') || mysqli_errno($db_connection) == 1050) && preg_match('~^\s*CREATE TABLE ([^\s\n\r]+?)~', $current_statement, $match) == 1)
1254
			{
1255
				$exists[] = $match[1];
1256
				$incontext['sql_results']['table_dups']++;
1257
			}
1258
			// Don't error on duplicate indexes (or duplicate operators in PostgreSQL.)
1259
			elseif (!preg_match('~^\s*CREATE( UNIQUE)? INDEX ([^\n\r]+?)~', $current_statement, $match) && !($db_type == 'postgresql' && preg_match('~^\s*CREATE OPERATOR (^\n\r]+?)~', $current_statement, $match)))
1260
			{
1261
				// MySQLi requires a connection object. It's optional with MySQL and Postgres
1262
				$incontext['failures'][$count] = $smcFunc['db_error']($db_connection);
1263
			}
1264
		}
1265
		else
1266
		{
1267
			if (preg_match('~^\s*CREATE TABLE ([^\s\n\r]+?)~', $current_statement, $match) == 1)
1268
				$incontext['sql_results']['tables']++;
1269
			elseif (preg_match('~^\s*INSERT INTO ([^\s\n\r]+?)~', $current_statement, $match) == 1)
1270
			{
1271
				preg_match_all('~\)[,;]~', $current_statement, $matches);
1272
				if (!empty($matches[0]))
1273
					$incontext['sql_results']['inserts'] += count($matches[0]);
1274
				else
1275
					$incontext['sql_results']['inserts']++;
1276
			}
1277
		}
1278
1279
		$current_statement = '';
1280
1281
		// Wait, wait, I'm still working here!
1282
		set_time_limit(60);
1283
	}
1284
1285
	// Sort out the context for the SQL.
1286
	foreach ($incontext['sql_results'] as $key => $number)
1287
	{
1288
		if ($number == 0)
1289
			unset($incontext['sql_results'][$key]);
1290
		else
1291
			$incontext['sql_results'][$key] = sprintf($txt['db_populate_' . $key], $number);
1292
	}
1293
1294
	// Make sure UTF will be used globally.
1295
	if ((!empty($databases[$db_type]['utf8_support']) && !empty($databases[$db_type]['utf8_required'])) || (empty($databases[$db_type]['utf8_required']) && !empty($databases[$db_type]['utf8_support']) && isset($_POST['utf8'])))
1296
		$newSettings[] = array('global_character_set', 'UTF-8');
1297
1298
	// Auto-detect local & global cookie settings
1299
	$url_parts = parse_url($boardurl);
1300
	if ($url_parts !== false)
1301
	{
1302
		unset($globalCookies, $globalCookiesDomain, $localCookies);
1303
1304
		// Look for subdomain, if found, set globalCookie settings
1305
		// Don't bother looking if you have an ip address for host
1306
		if (!empty($url_parts['host']) && (filter_var($url_parts['host'], FILTER_VALIDATE_IP) === false))
1307
		{
1308
			// www isn't really a subdomain in this sense, so strip it out
1309
			$url_parts['host'] = str_ireplace('www.', '', $url_parts['host']);
1310
			$pos1 = strrpos($url_parts['host'], '.');
1311
			if ($pos1 !== false)
1312
			{
1313
				// 2nd period from the right indicates you have a subdomain
1314
				$pos2 = strrpos(substr($url_parts['host'], 0, $pos1 - 1), '.');
1315
				if ($pos2 !== false)
1316
				{
1317
					$globalCookies = '1';
1318
					$globalCookiesDomain = substr($url_parts['host'], $pos2 + 1);
1319
				}
1320
			}
1321
		}
1322
1323
		// Look for subfolder, if found, set localCookie
1324
		// Checking for len > 1 ensures you don't have just a slash...
1325
		if (!empty($url_parts['path']) && strlen($url_parts['path']) > 1)
1326
			$localCookies = '1';
1327
1328
		if (isset($globalCookies))
1329
			$newSettings[] = array('globalCookies', $globalCookies);
1330
		if (isset($globalCookiesDomain))
1331
			$newSettings[] = array('globalCookiesDomain', $globalCookiesDomain);
1332
		if (isset($localCookies))
1333
			$newSettings[] = array('localCookies', $localCookies);
1334
	}
1335
1336
	// Are we allowing stat collection?
1337
	if (!empty($_POST['stats']) && substr($boardurl, 0, 16) != 'http://localhost' && empty($modSettings['allow_sm_stats']) && empty($modSettings['enable_sm_stats']))
1338
	{
1339
		$incontext['allow_sm_stats'] = true;
1340
1341
		// Attempt to register the site etc.
1342
		$fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
1343
		if ($fp)
1344
		{
1345
			$out = 'GET /smf/stats/register_stats.php?site=' . base64_encode($boardurl) . ' HTTP/1.1' . "\r\n";
1346
			$out .= 'Host: www.simplemachines.org' . "\r\n";
1347
			$out .= 'Connection: Close' . "\r\n\r\n";
1348
			fwrite($fp, $out);
1349
1350
			$return_data = '';
1351
			while (!feof($fp))
1352
				$return_data .= fgets($fp, 128);
1353
1354
			fclose($fp);
1355
1356
			// Get the unique site ID.
1357
			preg_match('~SITE-ID:\s(\w{10})~', $return_data, $ID);
1358
1359
			if (!empty($ID[1]))
1360
				$smcFunc['db_insert']('replace',
1361
					$db_prefix . 'settings',
1362
					array('variable' => 'string', 'value' => 'string'),
1363
					array(
1364
						array('sm_stats_key', $ID[1]),
1365
						array('enable_sm_stats', 1),
1366
					),
1367
					array('variable')
1368
				);
1369
		}
1370
	}
1371
	// Don't remove stat collection unless we unchecked the box for real, not from the loop.
1372
	elseif (empty($_POST['stats']) && empty($incontext['allow_sm_stats']))
1373
		$smcFunc['db_query']('', '
1374
			DELETE FROM {db_prefix}settings
1375
			WHERE variable = {string:enable_sm_stats}',
1376
			array(
1377
				'enable_sm_stats' => 'enable_sm_stats',
1378
				'db_error_skip' => true,
1379
			)
1380
		);
1381
1382
	// Are we enabling SSL?
1383
	if (!empty($_POST['force_ssl']))
1384
		$newSettings[] = array('force_ssl', 1);
1385
1386
	// Setting a timezone is required.
1387
	if (!isset($modSettings['default_timezone']) && function_exists('date_default_timezone_set'))
1388
	{
1389
		// Get PHP's default timezone, if set
1390
		$ini_tz = ini_get('date.timezone');
1391
		if (!empty($ini_tz))
1392
			$timezone_id = $ini_tz;
1393
		else
1394
			$timezone_id = '';
1395
1396
		// If date.timezone is unset, invalid, or just plain weird, make a best guess
1397
		if (!in_array($timezone_id, timezone_identifiers_list()))
0 ignored issues
show
It seems like timezone_identifiers_list() can also be of type false; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

1397
		if (!in_array($timezone_id, /** @scrutinizer ignore-type */ timezone_identifiers_list()))
Loading history...
1398
		{
1399
			$server_offset = @mktime(0, 0, 0, 1, 1, 1970);
1400
			$timezone_id = timezone_name_from_abbr('', $server_offset, 0);
1401
		}
1402
1403
		if (date_default_timezone_set($timezone_id))
1404
			$newSettings[] = array('default_timezone', $timezone_id);
1405
	}
1406
1407
	if (!empty($newSettings))
1408
	{
1409
		$smcFunc['db_insert']('replace',
1410
			'{db_prefix}settings',
1411
			array('variable' => 'string-255', 'value' => 'string-65534'),
1412
			$newSettings,
1413
			array('variable')
1414
		);
1415
	}
1416
1417
	// Populate the smiley_files table.
1418
	// Can't just dump this data in the SQL file because we need to know the id for each smiley.
1419
	$smiley_filenames = array(
1420
		':)' => 'smiley',
1421
		';)' => 'wink',
1422
		':D' => 'cheesy',
1423
		';D' => 'grin',
1424
		'>:(' => 'angry',
1425
		':(' => 'sad',
1426
		':o' => 'shocked',
1427
		'8)' => 'cool',
1428
		'???' => 'huh',
1429
		'::)' => 'rolleyes',
1430
		':P' => 'tongue',
1431
		':-[' => 'embarrassed',
1432
		':-X' => 'lipsrsealed',
1433
		':-\\' => 'undecided',
1434
		':-*' => 'kiss',
1435
		':\'(' => 'cry',
1436
		'>:D' => 'evil',
1437
		'^-^' => 'azn',
1438
		'O0' => 'afro',
1439
		':))' => 'laugh',
1440
		'C:-)' => 'police',
1441
		'O:-)' => 'angel'
1442
	);
1443
	$smiley_set_extensions = array('fugue' => '.png', 'alienine' => '.png');
1444
1445
	$smiley_inserts = array();
1446
	$request = $smcFunc['db_query']('', '
1447
		SELECT id_smiley, code
1448
		FROM {db_prefix}smileys',
1449
		array()
1450
	);
1451
	while ($row = $smcFunc['db_fetch_assoc']($request))
1452
	{
1453
		foreach ($smiley_set_extensions as $set => $ext)
1454
			$smiley_inserts[] = array($row['id_smiley'], $set, $smiley_filenames[$row['code']] . $ext);
1455
	}
1456
	$smcFunc['db_free_result']($request);
1457
1458
	$smcFunc['db_insert']('ignore',
1459
		'{db_prefix}smiley_files',
1460
		array('id_smiley' => 'int', 'smiley_set' => 'string-48', 'filename' => 'string-48'),
1461
		$smiley_inserts,
1462
		array('id_smiley', 'smiley_set')
1463
	);
1464
1465
	// Let's optimize those new tables, but not on InnoDB, ok?
1466
	if (!$has_innodb)
1467
	{
1468
		db_extend();
1469
		$tables = $smcFunc['db_list_tables']($db_name, $db_prefix . '%');
1470
		foreach ($tables as $table)
1471
		{
1472
			$smcFunc['db_optimize_table']($table) != -1 or $db_messed = true;
1473
1474
			if (!empty($db_messed))
1475
			{
1476
				$incontext['failures'][-1] = $smcFunc['db_error']();
1477
				break;
1478
			}
1479
		}
1480
	}
1481
1482
	// MySQL specific stuff
1483
	if (substr($db_type, 0, 5) != 'mysql')
1484
		return false;
1485
1486
	// Find database user privileges.
1487
	$privs = array();
1488
	$get_privs = $smcFunc['db_query']('', 'SHOW PRIVILEGES', array());
1489
	while ($row = $smcFunc['db_fetch_assoc']($get_privs))
1490
	{
1491
		if ($row['Privilege'] == 'Alter')
1492
			$privs[] = $row['Privilege'];
1493
	}
1494
	$smcFunc['db_free_result']($get_privs);
1495
1496
	// Check for the ALTER privilege.
1497
	if (!empty($databases[$db_type]['alter_support']) && !in_array('Alter', $privs))
1498
	{
1499
		$incontext['error'] = $txt['error_db_alter_priv'];
1500
		return false;
1501
	}
1502
1503
	if (!empty($exists))
1504
	{
1505
		$incontext['page_title'] = $txt['user_refresh_install'];
1506
		$incontext['was_refresh'] = true;
1507
	}
1508
1509
	return false;
1510
}
1511
1512
// Ask for the administrator login information.
1513
function AdminAccount()
1514
{
1515
	global $txt, $db_type, $smcFunc, $incontext, $db_prefix, $db_passwd, $sourcedir, $db_character_set;
1516
1517
	$incontext['sub_template'] = 'admin_account';
1518
	$incontext['page_title'] = $txt['user_settings'];
1519
	$incontext['continue'] = 1;
1520
1521
	// Skipping?
1522
	if (!empty($_POST['skip']))
1523
		return true;
1524
1525
	// Need this to check whether we need the database password.
1526
	require(dirname(__FILE__) . '/Settings.php');
1527
	load_database();
1528
1529
	require_once($sourcedir . '/Subs-Auth.php');
1530
1531
	require_once($sourcedir . '/Subs.php');
1532
1533
	// Reload settings & set some global funcs
1534
	require_once($sourcedir . '/Load.php');
1535
	reloadSettings();
1536
1537
	// We need this to properly hash the password for Admin
1538
	$smcFunc['strtolower'] = $db_character_set != 'utf8' && $txt['lang_character_set'] != 'UTF-8' ? 'strtolower' : function($string)
1539
	{
1540
		global $sourcedir;
1541
		if (function_exists('mb_strtolower'))
1542
			return mb_strtolower($string, 'UTF-8');
1543
		require_once($sourcedir . '/Subs-Charset.php');
1544
		return utf8_strtolower($string);
1545
	};
1546
1547
	if (!isset($_POST['username']))
1548
		$_POST['username'] = '';
1549
	if (!isset($_POST['email']))
1550
		$_POST['email'] = '';
1551
	if (!isset($_POST['server_email']))
1552
		$_POST['server_email'] = '';
1553
1554
	$incontext['username'] = htmlspecialchars($_POST['username']);
1555
	$incontext['email'] = htmlspecialchars($_POST['email']);
1556
	$incontext['server_email'] = htmlspecialchars($_POST['server_email']);
1557
1558
	$incontext['require_db_confirm'] = empty($db_type);
1559
1560
	// Only allow skipping if we think they already have an account setup.
1561
	$request = $smcFunc['db_query']('', '
1562
		SELECT id_member
1563
		FROM {db_prefix}members
1564
		WHERE id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0
1565
		LIMIT 1',
1566
		array(
1567
			'db_error_skip' => true,
1568
			'admin_group' => 1,
1569
		)
1570
	);
1571
	if ($smcFunc['db_num_rows']($request) != 0)
1572
		$incontext['skip'] = 1;
1573
	$smcFunc['db_free_result']($request);
1574
1575
	// Trying to create an account?
1576
	if (isset($_POST['password1']) && !empty($_POST['contbutt']))
1577
	{
1578
		// Wrong password?
1579
		if ($incontext['require_db_confirm'] && $_POST['password3'] != $db_passwd)
1580
		{
1581
			$incontext['error'] = $txt['error_db_connect'];
1582
			return false;
1583
		}
1584
		// Not matching passwords?
1585
		if ($_POST['password1'] != $_POST['password2'])
1586
		{
1587
			$incontext['error'] = $txt['error_user_settings_again_match'];
1588
			return false;
1589
		}
1590
		// No password?
1591
		if (strlen($_POST['password1']) < 4)
1592
		{
1593
			$incontext['error'] = $txt['error_user_settings_no_password'];
1594
			return false;
1595
		}
1596
		if (!file_exists($sourcedir . '/Subs.php'))
1597
		{
1598
			$incontext['error'] = sprintf($txt['error_sourcefile_missing'], 'Subs.php');
1599
			return false;
1600
		}
1601
1602
		// Update the webmaster's email?
1603
		if (!empty($_POST['server_email']) && (empty($webmaster_email) || $webmaster_email == '[email protected]'))
1604
			installer_updateSettingsFile(array('webmaster_email' => $_POST['server_email']));
1605
1606
		// Work out whether we're going to have dodgy characters and remove them.
1607
		$invalid_characters = preg_match('~[<>&"\'=\\\]~', $_POST['username']) != 0;
1608
		$_POST['username'] = preg_replace('~[<>&"\'=\\\]~', '', $_POST['username']);
1609
1610
		$result = $smcFunc['db_query']('', '
1611
			SELECT id_member, password_salt
1612
			FROM {db_prefix}members
1613
			WHERE member_name = {string:username} OR email_address = {string:email}
1614
			LIMIT 1',
1615
			array(
1616
				'username' => $_POST['username'],
1617
				'email' => $_POST['email'],
1618
				'db_error_skip' => true,
1619
			)
1620
		);
1621
		if ($smcFunc['db_num_rows']($result) != 0)
1622
		{
1623
			list ($incontext['member_id'], $incontext['member_salt']) = $smcFunc['db_fetch_row']($result);
1624
			$smcFunc['db_free_result']($result);
1625
1626
			$incontext['account_existed'] = $txt['error_user_settings_taken'];
1627
		}
1628
		elseif ($_POST['username'] == '' || strlen($_POST['username']) > 25)
1629
		{
1630
			// Try the previous step again.
1631
			$incontext['error'] = $_POST['username'] == '' ? $txt['error_username_left_empty'] : $txt['error_username_too_long'];
1632
			return false;
1633
		}
1634
		elseif ($invalid_characters || $_POST['username'] == '_' || $_POST['username'] == '|' || strpos($_POST['username'], '[code') !== false || strpos($_POST['username'], '[/code') !== false)
1635
		{
1636
			// Try the previous step again.
1637
			$incontext['error'] = $txt['error_invalid_characters_username'];
1638
			return false;
1639
		}
1640
		elseif (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) || strlen($_POST['email']) > 255)
1641
		{
1642
			// One step back, this time fill out a proper admin email address.
1643
			$incontext['error'] = sprintf($txt['error_valid_admin_email_needed'], $_POST['username']);
1644
			return false;
1645
		}
1646
		elseif (empty($_POST['server_email']) || !filter_var($_POST['server_email'], FILTER_VALIDATE_EMAIL) || strlen($_POST['server_email']) > 255)
1647
		{
1648
			// One step back, this time fill out a proper admin email address.
1649
			$incontext['error'] = $txt['error_valid_server_email_needed'];
1650
			return false;
1651
		}
1652
		elseif ($_POST['username'] != '')
1653
		{
1654
			if (!is_callable('random_int'))
1655
				require_once('Sources/random_compat/random.php');
1656
1657
			$incontext['member_salt'] = bin2hex(random_bytes(16));
1658
1659
			// Format the username properly.
1660
			$_POST['username'] = preg_replace('~[\t\n\r\x0B\0\xA0]+~', ' ', $_POST['username']);
1661
			$ip = isset($_SERVER['REMOTE_ADDR']) ? substr($_SERVER['REMOTE_ADDR'], 0, 255) : '';
1662
1663
			$_POST['password1'] = hash_password($_POST['username'], $_POST['password1']);
1664
1665
			$incontext['member_id'] = $smcFunc['db_insert']('',
1666
				$db_prefix . 'members',
1667
				array(
1668
					'member_name' => 'string-25',
1669
					'real_name' => 'string-25',
1670
					'passwd' => 'string',
1671
					'email_address' => 'string',
1672
					'id_group' => 'int',
1673
					'posts' => 'int',
1674
					'date_registered' => 'int',
1675
					'password_salt' => 'string',
1676
					'lngfile' => 'string',
1677
					'personal_text' => 'string',
1678
					'avatar' => 'string',
1679
					'member_ip' => 'inet',
1680
					'member_ip2' => 'inet',
1681
					'buddy_list' => 'string',
1682
					'pm_ignore_list' => 'string',
1683
					'website_title' => 'string',
1684
					'website_url' => 'string',
1685
					'signature' => 'string',
1686
					'usertitle' => 'string',
1687
					'secret_question' => 'string',
1688
					'additional_groups' => 'string',
1689
					'ignore_boards' => 'string',
1690
				),
1691
				array(
1692
					$_POST['username'],
1693
					$_POST['username'],
1694
					$_POST['password1'],
1695
					$_POST['email'],
1696
					1,
1697
					0,
1698
					time(),
1699
					$incontext['member_salt'],
1700
					'',
1701
					'',
1702
					'',
1703
					$ip,
1704
					$ip,
1705
					'',
1706
					'',
1707
					'',
1708
					'',
1709
					'',
1710
					'',
1711
					'',
1712
					'',
1713
					'',
1714
				),
1715
				array('id_member'),
1716
				1
1717
			);
1718
		}
1719
1720
		// If we're here we're good.
1721
		return true;
1722
	}
1723
1724
	return false;
1725
}
1726
1727
// Final step, clean up and a complete message!
1728
function DeleteInstall()
1729
{
1730
	global $smcFunc, $db_character_set, $context, $txt, $incontext;
1731
	global $databases, $sourcedir, $modSettings, $user_info, $db_type, $boardurl;
1732
	global $auth_secret, $cookiename;
1733
1734
	$incontext['page_title'] = $txt['congratulations'];
1735
	$incontext['sub_template'] = 'delete_install';
1736
	$incontext['continue'] = 0;
1737
1738
	require(dirname(__FILE__) . '/Settings.php');
1739
	load_database();
1740
1741
	chdir(dirname(__FILE__));
1742
1743
	require_once($sourcedir . '/Errors.php');
1744
	require_once($sourcedir . '/Logging.php');
1745
	require_once($sourcedir . '/Subs.php');
1746
	require_once($sourcedir . '/Load.php');
1747
	require_once($sourcedir . '/Security.php');
1748
	require_once($sourcedir . '/Subs-Auth.php');
1749
1750
	// Reload settings & set some global funcs
1751
	reloadSettings();
1752
1753
	// Bring a warning over.
1754
	if (!empty($incontext['account_existed']))
1755
		$incontext['warning'] = $incontext['account_existed'];
1756
1757
	if (!empty($db_character_set) && !empty($databases[$db_type]['utf8_support']))
1758
		$smcFunc['db_query']('', '
1759
			SET NAMES {string:db_character_set}',
1760
			array(
1761
				'db_character_set' => $db_character_set,
1762
				'db_error_skip' => true,
1763
			)
1764
		);
1765
1766
	// As track stats is by default enabled let's add some activity.
1767
	$smcFunc['db_insert']('ignore',
1768
		'{db_prefix}log_activity',
1769
		array('date' => 'date', 'topics' => 'int', 'posts' => 'int', 'registers' => 'int'),
1770
		array(strftime('%Y-%m-%d', time()), 1, 1, (!empty($incontext['member_id']) ? 1 : 0)),
1771
		array('date')
1772
	);
1773
1774
	// We're going to want our lovely $modSettings now.
1775
	$request = $smcFunc['db_query']('', '
1776
		SELECT variable, value
1777
		FROM {db_prefix}settings',
1778
		array(
1779
			'db_error_skip' => true,
1780
		)
1781
	);
1782
	// Only proceed if we can load the data.
1783
	if ($request)
1784
	{
1785
		while ($row = $smcFunc['db_fetch_row']($request))
1786
			$modSettings[$row[0]] = $row[1];
1787
		$smcFunc['db_free_result']($request);
1788
	}
1789
1790
	// Automatically log them in ;)
1791
	if (isset($incontext['member_id']) && isset($incontext['member_salt']))
1792
		setLoginCookie(3153600 * 60, $incontext['member_id'], hash_salt($_POST['password1'], $incontext['member_salt']));
1793
1794
	$result = $smcFunc['db_query']('', '
1795
		SELECT value
1796
		FROM {db_prefix}settings
1797
		WHERE variable = {string:db_sessions}',
1798
		array(
1799
			'db_sessions' => 'databaseSession_enable',
1800
			'db_error_skip' => true,
1801
		)
1802
	);
1803
	if ($smcFunc['db_num_rows']($result) != 0)
1804
		list ($db_sessions) = $smcFunc['db_fetch_row']($result);
1805
	$smcFunc['db_free_result']($result);
1806
1807
	if (empty($db_sessions))
1808
		$_SESSION['admin_time'] = time();
1809
	else
1810
	{
1811
		$_SERVER['HTTP_USER_AGENT'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 211);
1812
1813
		$smcFunc['db_insert']('replace',
1814
			'{db_prefix}sessions',
1815
			array(
1816
				'session_id' => 'string', 'last_update' => 'int', 'data' => 'string',
1817
			),
1818
			array(
1819
				session_id(), time(), 'USER_AGENT|s:' . strlen($_SERVER['HTTP_USER_AGENT']) . ':"' . $_SERVER['HTTP_USER_AGENT'] . '";admin_time|i:' . time() . ';',
1820
			),
1821
			array('session_id')
1822
		);
1823
	}
1824
1825
	updateStats('member');
1826
	updateStats('message');
1827
	updateStats('topic');
1828
1829
	// This function is needed to do the updateStats('subject') call.
1830
	$smcFunc['strtolower'] = $db_character_set != 'utf8' && $txt['lang_character_set'] != 'UTF-8' ? 'strtolower' : function($string)
1831
	{
1832
		global $sourcedir;
1833
		if (function_exists('mb_strtolower'))
1834
			return mb_strtolower($string, 'UTF-8');
1835
		require_once($sourcedir . '/Subs-Charset.php');
1836
		return utf8_strtolower($string);
1837
	};
1838
1839
	$request = $smcFunc['db_query']('', '
1840
		SELECT id_msg
1841
		FROM {db_prefix}messages
1842
		WHERE id_msg = 1
1843
			AND modified_time = 0
1844
		LIMIT 1',
1845
		array(
1846
			'db_error_skip' => true,
1847
		)
1848
	);
1849
	$context['utf8'] = $db_character_set === 'utf8' || $txt['lang_character_set'] === 'UTF-8';
1850
	if ($smcFunc['db_num_rows']($request) > 0)
1851
		updateStats('subject', 1, htmlspecialchars($txt['default_topic_subject']));
1852
	$smcFunc['db_free_result']($request);
1853
1854
	// Now is the perfect time to fetch the SM files.
1855
	require_once($sourcedir . '/ScheduledTasks.php');
1856
	// Sanity check that they loaded earlier!
1857
	if (isset($modSettings['recycle_board']))
1858
	{
1859
		scheduled_fetchSMfiles(); // Now go get those files!
1860
1861
		// We've just installed!
1862
		$user_info['ip'] = $_SERVER['REMOTE_ADDR'];
1863
		$user_info['id'] = isset($incontext['member_id']) ? $incontext['member_id'] : 0;
1864
		logAction('install', array('version' => SMF_FULL_VERSION), 'admin');
1865
	}
1866
1867
	// Disable the legacy BBC by default for new installs
1868
	updateSettings(array(
1869
		'disabledBBC' => implode(',', $context['legacy_bbc']),
1870
	));
1871
1872
	// Some final context for the template.
1873
	$incontext['dir_still_writable'] = is_writable(dirname(__FILE__)) && substr(__FILE__, 1, 2) != ':\\';
1874
	$incontext['probably_delete_install'] = isset($_SESSION['installer_temp_ftp']) || is_writable(dirname(__FILE__)) || is_writable(__FILE__);
1875
1876
	// Update hash's cost to an appropriate setting
1877
	updateSettings(array(
1878
		'bcrypt_hash_cost' => hash_benchmark(),
1879
	));
1880
1881
	return false;
1882
}
1883
1884
function installer_updateSettingsFile($vars, $rebuild = false)
1885
{
1886
	global $sourcedir, $context, $db_character_set, $txt;
1887
1888
	$context['utf8'] = (isset($vars['db_character_set']) && $vars['db_character_set'] === 'utf8') || (!empty($db_character_set) && $db_character_set === 'utf8') || (!empty($txt) && $txt['lang_character_set'] === 'UTF-8');
1889
1890
	if (empty($sourcedir))
1891
	{
1892
		if (file_exists(dirname(__FILE__) . '/Sources') && is_dir(dirname(__FILE__) . '/Sources'))
1893
			$sourcedir = dirname(__FILE__) . '/Sources';
1894
		else
1895
			return false;
1896
	}
1897
1898
	if (!is_writeable(dirname(__FILE__) . '/Settings.php'))
1899
	{
1900
		@chmod(dirname(__FILE__) . '/Settings.php', 0777);
1901
1902
		if (!is_writeable(dirname(__FILE__) . '/Settings.php'))
1903
			return false;
1904
	}
1905
1906
	require_once($sourcedir . '/Subs.php');
1907
	require_once($sourcedir . '/Subs-Admin.php');
1908
1909
	return updateSettingsFile($vars, false, $rebuild);
1910
}
1911
1912
// Create an .htaccess file to prevent mod_security. SMF has filtering built-in.
1913
function fixModSecurity()
1914
{
1915
	$htaccess_addition = '
1916
<IfModule mod_security.c>
1917
	# Turn off mod_security filtering.  SMF is a big boy, it doesn\'t need its hands held.
1918
	SecFilterEngine Off
1919
1920
	# The below probably isn\'t needed, but better safe than sorry.
1921
	SecFilterScanPOST Off
1922
</IfModule>';
1923
1924
	if (!function_exists('apache_get_modules') || !in_array('mod_security', apache_get_modules()))
1925
		return true;
1926
	elseif (file_exists(dirname(__FILE__) . '/.htaccess') && is_writable(dirname(__FILE__) . '/.htaccess'))
1927
	{
1928
		$current_htaccess = implode('', file(dirname(__FILE__) . '/.htaccess'));
0 ignored issues
show
It seems like file(dirname(__FILE__) . '/.htaccess') can also be of type false; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

1928
		$current_htaccess = implode('', /** @scrutinizer ignore-type */ file(dirname(__FILE__) . '/.htaccess'));
Loading history...
1929
1930
		// Only change something if mod_security hasn't been addressed yet.
1931
		if (strpos($current_htaccess, '<IfModule mod_security.c>') === false)
1932
		{
1933
			if ($ht_handle = fopen(dirname(__FILE__) . '/.htaccess', 'a'))
1934
			{
1935
				fwrite($ht_handle, $htaccess_addition);
1936
				fclose($ht_handle);
1937
				return true;
1938
			}
1939
			else
1940
				return false;
1941
		}
1942
		else
1943
			return true;
1944
	}
1945
	elseif (file_exists(dirname(__FILE__) . '/.htaccess'))
1946
		return strpos(implode('', file(dirname(__FILE__) . '/.htaccess')), '<IfModule mod_security.c>') !== false;
1947
	elseif (is_writable(dirname(__FILE__)))
1948
	{
1949
		if ($ht_handle = fopen(dirname(__FILE__) . '/.htaccess', 'w'))
1950
		{
1951
			fwrite($ht_handle, $htaccess_addition);
1952
			fclose($ht_handle);
1953
			return true;
1954
		}
1955
		else
1956
			return false;
1957
	}
1958
	else
1959
		return false;
1960
}
1961
1962
function template_install_above()
1963
{
1964
	global $incontext, $txt, $installurl;
1965
1966
	echo '<!DOCTYPE html>
1967
<html', $txt['lang_rtl'] == true ? ' dir="rtl"' : '', '>
1968
<head>
1969
	<meta charset="', isset($txt['lang_character_set']) ? $txt['lang_character_set'] : 'UTF-8', '">
1970
	<meta name="robots" content="noindex">
1971
	<title>', $txt['smf_installer'], '</title>
1972
	<link rel="stylesheet" href="Themes/default/css/index.css">
1973
	<link rel="stylesheet" href="Themes/default/css/install.css">
1974
	', $txt['lang_rtl'] == true ? '<link rel="stylesheet" href="Themes/default/css/rtl.css">' : '', '
1975
1976
	<script src="Themes/default/scripts/jquery-' . JQUERY_VERSION . '.min.js"></script>
1977
	<script src="Themes/default/scripts/script.js"></script>
1978
</head>
1979
<body>
1980
	<div id="footerfix">
1981
	<div id="header">
1982
		<h1 class="forumtitle">', $txt['smf_installer'], '</h1>
1983
		<img id="smflogo" src="Themes/default/images/smflogo.svg" alt="Simple Machines Forum" title="Simple Machines Forum">
1984
	</div>
1985
	<div id="wrapper">';
1986
1987
	// Have we got a language drop down - if so do it on the first step only.
1988
	if (!empty($incontext['detected_languages']) && count($incontext['detected_languages']) > 1 && $incontext['current_step'] == 0)
1989
	{
1990
		echo '
1991
		<div id="upper_section">
1992
			<div id="inner_section">
1993
				<div id="inner_wrap">
1994
					<div class="news">
1995
						<form action="', $installurl, '" method="get">
1996
							<label for="installer_language">', $txt['installer_language'], ':</label>
1997
							<select id="installer_language" name="lang_file" onchange="location.href = \'', $installurl, '?lang_file=\' + this.options[this.selectedIndex].value;">';
1998
1999
		foreach ($incontext['detected_languages'] as $lang => $name)
2000
			echo '
2001
								<option', isset($_SESSION['installer_temp_lang']) && $_SESSION['installer_temp_lang'] == $lang ? ' selected' : '', ' value="', $lang, '">', $name, '</option>';
2002
2003
		echo '
2004
							</select>
2005
							<noscript><input type="submit" value="', $txt['installer_language_set'], '" class="button"></noscript>
2006
						</form>
2007
					</div><!-- .news -->
2008
					<hr class="clear">
2009
				</div><!-- #inner_wrap -->
2010
			</div><!-- #inner_section -->
2011
		</div><!-- #upper_section -->';
2012
	}
2013
2014
	echo '
2015
		<div id="content_section">
2016
			<div id="main_content_section">
2017
				<div id="main_steps">
2018
					<h2>', $txt['upgrade_progress'], '</h2>
2019
					<ul class="steps_list">';
2020
2021
	foreach ($incontext['steps'] as $num => $step)
2022
		echo '
2023
						<li', $num == $incontext['current_step'] ? ' class="stepcurrent"' : '', '>
2024
							', $txt['upgrade_step'], ' ', $step[0], ': ', $step[1], '
2025
						</li>';
2026
2027
	echo '
2028
					</ul>
2029
				</div>
2030
				<div id="install_progress">
2031
					<div id="progress_bar" class="progress_bar progress_green">
2032
						<h3>'. $txt['upgrade_overall_progress'], '</h3>
2033
						<span id="overall_text">', $incontext['overall_percent'], '%</span>
2034
						<div id="overall_progress" class="bar" style="width: ', $incontext['overall_percent'], '%;"></div>
2035
					</div>
2036
				</div>
2037
				<div id="main_screen" class="clear">
2038
					<h2>', $incontext['page_title'], '</h2>
2039
					<div class="panel">';
2040
}
2041
2042
function template_install_below()
2043
{
2044
	global $incontext, $txt;
2045
2046
	if (!empty($incontext['continue']) || !empty($incontext['skip']))
2047
	{
2048
		echo '
2049
							<div class="floatright">';
2050
2051
		if (!empty($incontext['continue']))
2052
			echo '
2053
								<input type="submit" id="contbutt" name="contbutt" value="', $txt['upgrade_continue'], '" onclick="return submitThisOnce(this);" class="button">';
2054
		if (!empty($incontext['skip']))
2055
			echo '
2056
								<input type="submit" id="skip" name="skip" value="', $txt['upgrade_skip'], '" onclick="return submitThisOnce(this);" class="button">';
2057
		echo '
2058
							</div>';
2059
	}
2060
2061
	// Show the closing form tag and other data only if not in the last step
2062
	if (count($incontext['steps']) - 1 !== (int) $incontext['current_step'])
2063
		echo '
2064
						</form>';
2065
2066
	echo '
2067
					</div><!-- .panel -->
2068
				</div><!-- #main_screen -->
2069
			</div><!-- #main_content_section -->
2070
		</div><!-- #content_section -->
2071
	</div><!-- #wrapper -->
2072
	</div><!-- #footerfix -->
2073
	<div id="footer">
2074
		<ul>
2075
			<li class="copyright"><a href="https://www.simplemachines.org/" title="Simple Machines Forum" target="_blank" rel="noopener">' . SMF_FULL_VERSION . ' &copy; ' . SMF_SOFTWARE_YEAR . ', Simple Machines</a></li>
2076
		</ul>
2077
	</div>
2078
</body>
2079
</html>';
2080
}
2081
2082
// Welcome them to the wonderful world of SMF!
2083
function template_welcome_message()
2084
{
2085
	global $incontext, $txt;
2086
2087
	echo '
2088
	<script src="https://www.simplemachines.org/smf/current-version.js?version=' . urlencode(SMF_VERSION) . '"></script>
2089
	<form action="', $incontext['form_url'], '" method="post">
2090
		<p>', sprintf($txt['install_welcome_desc'], SMF_VERSION), '</p>
2091
		<div id="version_warning" class="noticebox hidden">
2092
			<h3>', $txt['error_warning_notice'], '</h3>
2093
			', sprintf($txt['error_script_outdated'], '<em id="smfVersion" style="white-space: nowrap;">??</em>', '<em id="yourVersion" style="white-space: nowrap;">' . SMF_VERSION . '</em>'), '
2094
		</div>';
2095
2096
	// Show the warnings, or not.
2097
	if (template_warning_divs())
2098
		echo '
2099
		<h3>', $txt['install_all_lovely'], '</h3>';
2100
2101
	// Say we want the continue button!
2102
	if (empty($incontext['error']))
2103
		$incontext['continue'] = 1;
2104
2105
	// For the latest version stuff.
2106
	echo '
2107
		<script>
2108
			// Latest version?
2109
			function smfCurrentVersion()
2110
			{
2111
				var smfVer, yourVer;
2112
2113
				if (!(\'smfVersion\' in window))
2114
					return;
2115
2116
				window.smfVersion = window.smfVersion.replace(/SMF\s?/g, \'\');
2117
2118
				smfVer = document.getElementById("smfVersion");
2119
				yourVer = document.getElementById("yourVersion");
2120
2121
				setInnerHTML(smfVer, window.smfVersion);
2122
2123
				var currentVersion = getInnerHTML(yourVer);
2124
				if (currentVersion < window.smfVersion)
2125
					document.getElementById(\'version_warning\').classList.remove(\'hidden\');
2126
			}
2127
			addLoadEvent(smfCurrentVersion);
2128
		</script>';
2129
}
2130
2131
// A shortcut for any warning stuff.
2132
function template_warning_divs()
2133
{
2134
	global $txt, $incontext;
2135
2136
	// Errors are very serious..
2137
	if (!empty($incontext['error']))
2138
		echo '
2139
		<div class="errorbox">
2140
			<h3>', $txt['upgrade_critical_error'], '</h3>
2141
			', $incontext['error'], '
2142
		</div>';
2143
	// A warning message?
2144
	elseif (!empty($incontext['warning']))
2145
		echo '
2146
		<div class="errorbox">
2147
			<h3>', $txt['upgrade_warning'], '</h3>
2148
			', $incontext['warning'], '
2149
		</div>';
2150
2151
	return empty($incontext['error']) && empty($incontext['warning']);
2152
}
2153
2154
function template_chmod_files()
2155
{
2156
	global $txt, $incontext;
2157
2158
	echo '
2159
		<p>', $txt['ftp_setup_why_info'], '</p>
2160
		<ul class="error_content">
2161
			<li>', implode('</li>
2162
			<li>', $incontext['failed_files']), '</li>
2163
		</ul>';
2164
2165
	if (isset($incontext['systemos'], $incontext['detected_path']) && $incontext['systemos'] == 'linux')
2166
		echo '
2167
		<hr>
2168
		<p>', $txt['chmod_linux_info'], '</p>
2169
		<samp># chmod a+w ', implode(' ' . $incontext['detected_path'] . '/', $incontext['failed_files']), '</samp>';
2170
2171
	// This is serious!
2172
	if (!template_warning_divs())
2173
		return;
2174
2175
	echo '
2176
		<hr>
2177
		<p>', $txt['ftp_setup_info'], '</p>';
2178
2179
	if (!empty($incontext['ftp_errors']))
2180
		echo '
2181
		<div class="error_message">
2182
			', $txt['error_ftp_no_connect'], '<br><br>
2183
			<code>', implode('<br>', $incontext['ftp_errors']), '</code>
2184
		</div>';
2185
2186
	echo '
2187
		<form action="', $incontext['form_url'], '" method="post">
2188
			<dl class="settings">
2189
				<dt>
2190
					<label for="ftp_server">', $txt['ftp_server'], ':</label>
2191
				</dt>
2192
				<dd>
2193
					<div class="floatright">
2194
						<label for="ftp_port" class="textbox"><strong>', $txt['ftp_port'], ':&nbsp;</strong></label>
2195
						<input type="text" size="3" name="ftp_port" id="ftp_port" value="', $incontext['ftp']['port'], '">
2196
					</div>
2197
					<input type="text" size="30" name="ftp_server" id="ftp_server" value="', $incontext['ftp']['server'], '">
2198
					<div class="smalltext block">', $txt['ftp_server_info'], '</div>
2199
				</dd>
2200
				<dt>
2201
					<label for="ftp_username">', $txt['ftp_username'], ':</label>
2202
				</dt>
2203
				<dd>
2204
					<input type="text" size="30" name="ftp_username" id="ftp_username" value="', $incontext['ftp']['username'], '">
2205
					<div class="smalltext block">', $txt['ftp_username_info'], '</div>
2206
				</dd>
2207
				<dt>
2208
					<label for="ftp_password">', $txt['ftp_password'], ':</label>
2209
				</dt>
2210
				<dd>
2211
					<input type="password" size="30" name="ftp_password" id="ftp_password">
2212
					<div class="smalltext block">', $txt['ftp_password_info'], '</div>
2213
				</dd>
2214
				<dt>
2215
					<label for="ftp_path">', $txt['ftp_path'], ':</label>
2216
				</dt>
2217
				<dd>
2218
					<input type="text" size="30" name="ftp_path" id="ftp_path" value="', $incontext['ftp']['path'], '">
2219
					<div class="smalltext block">', $incontext['ftp']['path_msg'], '</div>
2220
				</dd>
2221
			</dl>
2222
			<div class="righttext buttons">
2223
				<input type="submit" value="', $txt['ftp_connect'], '" onclick="return submitThisOnce(this);" class="button">
2224
			</div>
2225
		</form>
2226
		<a href="', $incontext['form_url'], '">', $txt['error_message_click'], '</a> ', $txt['ftp_setup_again'];
2227
}
2228
2229
// Get the database settings prepared.
2230
function template_database_settings()
2231
{
2232
	global $incontext, $txt;
2233
2234
	echo '
2235
	<form action="', $incontext['form_url'], '" method="post">
2236
		<p>', $txt['db_settings_info'], '</p>';
2237
2238
	template_warning_divs();
2239
2240
	echo '
2241
		<dl class="settings">';
2242
2243
	// More than one database type?
2244
	if (count($incontext['supported_databases']) > 1)
2245
	{
2246
		echo '
2247
			<dt>
2248
				<label for="db_type_input">', $txt['db_settings_type'], ':</label>
2249
			</dt>
2250
			<dd>
2251
				<select name="db_type" id="db_type_input" onchange="toggleDBInput();">';
2252
2253
		foreach ($incontext['supported_databases'] as $key => $db)
2254
			echo '
2255
					<option value="', $key, '"', isset($_POST['db_type']) && $_POST['db_type'] == $key ? ' selected' : '', '>', $db['name'], '</option>';
2256
2257
		echo '
2258
				</select>
2259
				<div class="smalltext">', $txt['db_settings_type_info'], '</div>
2260
			</dd>';
2261
	}
2262
	else
2263
	{
2264
		echo '
2265
			<dd>
2266
				<input type="hidden" name="db_type" value="', $incontext['db']['type'], '">
2267
			</dd>';
2268
	}
2269
2270
	echo '
2271
			<dt>
2272
				<label for="db_server_input">', $txt['db_settings_server'], ':</label>
2273
			</dt>
2274
			<dd>
2275
				<input type="text" name="db_server" id="db_server_input" value="', $incontext['db']['server'], '" size="30">
2276
				<div class="smalltext">', $txt['db_settings_server_info'], '</div>
2277
			</dd>
2278
			<dt>
2279
				<label for="db_port_input">', $txt['db_settings_port'], ':</label>
2280
			</dt>
2281
			<dd>
2282
				<input type="text" name="db_port" id="db_port_input" value="', $incontext['db']['port'], '">
2283
				<div class="smalltext">', $txt['db_settings_port_info'], '</div>
2284
			</dd>
2285
			<dt>
2286
				<label for="db_user_input">', $txt['db_settings_username'], ':</label>
2287
			</dt>
2288
			<dd>
2289
				<input type="text" name="db_user" id="db_user_input" value="', $incontext['db']['user'], '" size="30">
2290
				<div class="smalltext">', $txt['db_settings_username_info'], '</div>
2291
			</dd>
2292
			<dt>
2293
				<label for="db_passwd_input">', $txt['db_settings_password'], ':</label>
2294
			</dt>
2295
			<dd>
2296
				<input type="password" name="db_passwd" id="db_passwd_input" value="', $incontext['db']['pass'], '" size="30">
2297
				<div class="smalltext">', $txt['db_settings_password_info'], '</div>
2298
			</dd>
2299
			<dt>
2300
				<label for="db_name_input">', $txt['db_settings_database'], ':</label>
2301
			</dt>
2302
			<dd>
2303
				<input type="text" name="db_name" id="db_name_input" value="', empty($incontext['db']['name']) ? 'smf' : $incontext['db']['name'], '" size="30">
2304
				<div class="smalltext">
2305
					', $txt['db_settings_database_info'], '
2306
					<span id="db_name_info_warning">', $txt['db_settings_database_info_note'], '</span>
2307
				</div>
2308
			</dd>
2309
			<dt>
2310
				<label for="db_prefix_input">', $txt['db_settings_prefix'], ':</label>
2311
			</dt>
2312
			<dd>
2313
				<input type="text" name="db_prefix" id="db_prefix_input" value="', $incontext['db']['prefix'], '" size="30">
2314
				<div class="smalltext">', $txt['db_settings_prefix_info'], '</div>
2315
			</dd>
2316
		</dl>';
2317
2318
	// Toggles a warning related to db names in PostgreSQL
2319
	echo '
2320
		<script>
2321
			function toggleDBInput()
2322
			{
2323
				if (document.getElementById(\'db_type_input\').value == \'postgresql\')
2324
					document.getElementById(\'db_name_info_warning\').classList.add(\'hidden\');
2325
				else
2326
					document.getElementById(\'db_name_info_warning\').classList.remove(\'hidden\');
2327
			}
2328
			toggleDBInput();
2329
		</script>';
2330
}
2331
2332
// Stick in their forum settings.
2333
function template_forum_settings()
2334
{
2335
	global $incontext, $txt;
2336
2337
	echo '
2338
	<form action="', $incontext['form_url'], '" method="post">
2339
		<h3>', $txt['install_settings_info'], '</h3>';
2340
2341
	template_warning_divs();
2342
2343
	echo '
2344
		<dl class="settings">
2345
			<dt>
2346
				<label for="mbname_input">', $txt['install_settings_name'], ':</label>
2347
			</dt>
2348
			<dd>
2349
				<input type="text" name="mbname" id="mbname_input" value="', $txt['install_settings_name_default'], '" size="65">
2350
				<div class="smalltext">', $txt['install_settings_name_info'], '</div>
2351
			</dd>
2352
			<dt>
2353
				<label for="boardurl_input">', $txt['install_settings_url'], ':</label>
2354
			</dt>
2355
			<dd>
2356
				<input type="text" name="boardurl" id="boardurl_input" value="', $incontext['detected_url'], '" size="65">
2357
				<div class="smalltext">', $txt['install_settings_url_info'], '</div>
2358
			</dd>
2359
			<dt>
2360
				<label for="reg_mode">', $txt['install_settings_reg_mode'], ':</label>
2361
			</dt>
2362
			<dd>
2363
				<select name="reg_mode" id="reg_mode">
2364
					<optgroup label="', $txt['install_settings_reg_modes'], ':">
2365
						<option value="0" selected>', $txt['install_settings_reg_immediate'], '</option>
2366
						<option value="1">', $txt['install_settings_reg_email'], '</option>
2367
						<option value="2">', $txt['install_settings_reg_admin'], '</option>
2368
						<option value="3">', $txt['install_settings_reg_disabled'], '</option>
2369
					</optgroup>
2370
				</select>
2371
				<div class="smalltext">', $txt['install_settings_reg_mode_info'], '</div>
2372
			</dd>
2373
			<dt>', $txt['install_settings_compress'], ':</dt>
2374
			<dd>
2375
				<input type="checkbox" name="compress" id="compress_check" checked>
2376
				<label for="compress_check">', $txt['install_settings_compress_title'], '</label>
2377
				<div class="smalltext">', $txt['install_settings_compress_info'], '</div>
2378
			</dd>
2379
			<dt>', $txt['install_settings_dbsession'], ':</dt>
2380
			<dd>
2381
				<input type="checkbox" name="dbsession" id="dbsession_check" checked>
2382
				<label for="dbsession_check">', $txt['install_settings_dbsession_title'], '</label>
2383
				<div class="smalltext">', $incontext['test_dbsession'] ? $txt['install_settings_dbsession_info1'] : $txt['install_settings_dbsession_info2'], '</div>
2384
			</dd>
2385
			<dt>', $txt['install_settings_utf8'], ':</dt>
2386
			<dd>
2387
				<input type="checkbox" name="utf8" id="utf8_check"', $incontext['utf8_default'] ? ' checked' : '', '', $incontext['utf8_required'] ? ' disabled' : '', '>
2388
				<label for="utf8_check">', $txt['install_settings_utf8_title'], '</label>
2389
				<div class="smalltext">', $txt['install_settings_utf8_info'], '</div>
2390
			</dd>
2391
			<dt>', $txt['install_settings_stats'], ':</dt>
2392
			<dd>
2393
				<input type="checkbox" name="stats" id="stats_check" checked="checked">
2394
				<label for="stats_check">', $txt['install_settings_stats_title'], '</label>
2395
				<div class="smalltext">', $txt['install_settings_stats_info'], '</div>
2396
			</dd>
2397
			<dt>', $txt['force_ssl'], ':</dt>
2398
			<dd>
2399
				<input type="checkbox" name="force_ssl" id="force_ssl"', $incontext['ssl_chkbx_checked'] ? ' checked' : '',
2400
					$incontext['ssl_chkbx_protected'] ? ' disabled' : '', '>
2401
				<label for="force_ssl">', $txt['force_ssl_label'], '</label>
2402
				<div class="smalltext"><strong>', $txt['force_ssl_info'], '</strong></div>
2403
			</dd>
2404
		</dl>';
2405
}
2406
2407
// Show results of the database population.
2408
function template_populate_database()
2409
{
2410
	global $incontext, $txt;
2411
2412
	echo '
2413
	<form action="', $incontext['form_url'], '" method="post">
2414
		<p>', !empty($incontext['was_refresh']) ? $txt['user_refresh_install_desc'] : $txt['db_populate_info'], '</p>';
2415
2416
	if (!empty($incontext['sql_results']))
2417
	{
2418
		echo '
2419
		<ul>
2420
			<li>', implode('</li><li>', $incontext['sql_results']), '</li>
2421
		</ul>';
2422
	}
2423
2424
	if (!empty($incontext['failures']))
2425
	{
2426
		echo '
2427
		<div class="red">', $txt['error_db_queries'], '</div>
2428
		<ul>';
2429
2430
		foreach ($incontext['failures'] as $line => $fail)
2431
			echo '
2432
			<li><strong>', $txt['error_db_queries_line'], $line + 1, ':</strong> ', nl2br(htmlspecialchars($fail)), '</li>';
2433
2434
		echo '
2435
		</ul>';
2436
	}
2437
2438
	echo '
2439
		<p>', $txt['db_populate_info2'], '</p>';
2440
2441
	template_warning_divs();
2442
2443
	echo '
2444
		<input type="hidden" name="pop_done" value="1">';
2445
}
2446
2447
// Create the admin account.
2448
function template_admin_account()
2449
{
2450
	global $incontext, $txt;
2451
2452
	echo '
2453
	<form action="', $incontext['form_url'], '" method="post">
2454
		<p>', $txt['user_settings_info'], '</p>';
2455
2456
	template_warning_divs();
2457
2458
	echo '
2459
		<dl class="settings">
2460
			<dt>
2461
				<label for="username">', $txt['user_settings_username'], ':</label>
2462
			</dt>
2463
			<dd>
2464
				<input type="text" name="username" id="username" value="', $incontext['username'], '" size="40">
2465
				<div class="smalltext">', $txt['user_settings_username_info'], '</div>
2466
			</dd>
2467
			<dt>
2468
				<label for="password1">', $txt['user_settings_password'], ':</label>
2469
			</dt>
2470
			<dd>
2471
				<input type="password" name="password1" id="password1" size="40">
2472
				<div class="smalltext">', $txt['user_settings_password_info'], '</div>
2473
			</dd>
2474
			<dt>
2475
				<label for="password2">', $txt['user_settings_again'], ':</label>
2476
			</dt>
2477
			<dd>
2478
				<input type="password" name="password2" id="password2" size="40">
2479
				<div class="smalltext">', $txt['user_settings_again_info'], '</div>
2480
			</dd>
2481
			<dt>
2482
				<label for="email">', $txt['user_settings_admin_email'], ':</label>
2483
			</dt>
2484
			<dd>
2485
				<input type="text" name="email" id="email" value="', $incontext['email'], '" size="40">
2486
				<div class="smalltext">', $txt['user_settings_admin_email_info'], '</div>
2487
			</dd>
2488
			<dt>
2489
				<label for="server_email">', $txt['user_settings_server_email'], ':</label>
2490
			</dt>
2491
			<dd>
2492
				<input type="text" name="server_email" id="server_email" value="', $incontext['server_email'], '" size="40">
2493
				<div class="smalltext">', $txt['user_settings_server_email_info'], '</div>
2494
			</dd>
2495
		</dl>';
2496
2497
	if ($incontext['require_db_confirm'])
2498
		echo '
2499
		<h2>', $txt['user_settings_database'], '</h2>
2500
		<p>', $txt['user_settings_database_info'], '</p>
2501
2502
		<div class="lefttext">
2503
			<input type="password" name="password3" size="30">
2504
		</div>';
2505
}
2506
2507
// Tell them it's done, and to delete.
2508
function template_delete_install()
2509
{
2510
	global $incontext, $installurl, $txt, $boardurl;
2511
2512
	echo '
2513
		<p>', $txt['congratulations_help'], '</p>';
2514
2515
	template_warning_divs();
2516
2517
	// Install directory still writable?
2518
	if ($incontext['dir_still_writable'])
2519
		echo '
2520
		<p><em>', $txt['still_writable'], '</em></p>';
2521
2522
	// Don't show the box if it's like 99% sure it won't work :P.
2523
	if ($incontext['probably_delete_install'])
2524
		echo '
2525
		<label>
2526
			<input type="checkbox" id="delete_self" onclick="doTheDelete();">
2527
			<strong>', $txt['delete_installer'], !isset($_SESSION['installer_temp_ftp']) ? ' ' . $txt['delete_installer_maybe'] : '', '</strong>
2528
		</label>
2529
		<script>
2530
			function doTheDelete()
2531
			{
2532
				var theCheck = document.getElementById ? document.getElementById("delete_self") : document.all.delete_self;
2533
				var tempImage = new Image();
2534
2535
				tempImage.src = "', $installurl, '?delete=1&ts_" + (new Date().getTime());
2536
				tempImage.width = 0;
2537
				theCheck.disabled = true;
2538
			}
2539
		</script>';
2540
2541
	echo '
2542
		<p>', sprintf($txt['go_to_your_forum'], $boardurl . '/index.php'), '</p>
2543
		<br>
2544
		', $txt['good_luck'];
2545
}
2546
2547
?>