Passed
Push — release-2.1 ( 2f6815...2f165a )
by
unknown
04:16
created

DeleteInstall()   F

Complexity

Conditions 21
Paths 18432

Size

Total Lines 154
Code Lines 84

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 84
nc 18432
nop 0
dl 0
loc 154
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Simple Machines Forum (SMF)
5
 *
6
 * @package SMF
7
 * @author Simple Machines https://www.simplemachines.org
8
 * @copyright 2021 Simple Machines and individual contributors
9
 * @license https://www.simplemachines.org/about/smf/license.php BSD
10
 *
11
 * @version 2.1 RC3
12
 */
13
14
define('SMF_VERSION', '2.1 RC3');
15
define('SMF_FULL_VERSION', 'SMF ' . SMF_VERSION);
16
define('SMF_SOFTWARE_YEAR', '2021');
17
define('DB_SCRIPT_VERSION', '2-1');
18
define('SMF_INSTALLING', 1);
19
20
define('JQUERY_VERSION', '3.5.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.6.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.6',
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
Bug introduced by
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...
Bug introduced by
'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;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
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')
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! empty($_SERVER['HTTP_...FORWARDED_SSL'] == 'on', Probably Intended Meaning: ! empty($_SERVER['HTTP_X...ORWARDED_SSL'] == 'on')
Loading history...
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
Bug introduced by
timezone_identifiers_list() of type void is incompatible with the type array expected by parameter $haystack of in_array(). ( 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...
Bug introduced by
Are you sure the usage of timezone_identifiers_list() is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
266
		{
267
			$server_offset = @mktime(0, 0, 0, 1, 1, 1970);
268
			$timezone_id = timezone_name_from_abbr('', $server_offset, 0);
0 ignored issues
show
Bug introduced by
It seems like $server_offset can also be of type false; however, parameter $utcOffset of timezone_name_from_abbr() does only seem to accept integer, 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

268
			$timezone_id = timezone_name_from_abbr('', /** @scrutinizer ignore-type */ $server_offset, 0);
Loading history...
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;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
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();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

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

Loading history...
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)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $extra_files seems to be defined by a foreach iteration on line 541. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
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
Bug introduced by
It seems like $fp can also be of type false; however, parameter $stream 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)
0 ignored issues
show
introduced by
The condition $ftp->error === false is always false.
Loading history...
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))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $ftp does not seem to be defined for all execution paths leading up to this point.
Loading history...
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;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$modSettings was never initialized. Although not strictly required by PHP, it is generally a good practice to add $modSettings = array(); before regardless.
Loading history...
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
		// Still no connection?  Big fat error message :P.
866
		if (!$db_connection)
0 ignored issues
show
introduced by
$db_connection is of type null|resource, thus it always evaluated to false.
Loading history...
867
		{
868
			// Get error info...  Recast just in case we get false or 0...
869
			$error_message = $smcFunc['db_connect_error']();
870
			if (empty($error_message))
871
				$error_message = '';
872
			$error_number = $smcFunc['db_connect_errno']();
873
			if (empty($error_number))
874
				$error_number = '';
875
			$db_error = (!empty($error_number) ? $error_number . ': ' : '') . $error_message;
876
877
			$incontext['error'] = $txt['error_db_connect'] . '<div class="error_content"><strong>' . $db_error . '</strong></div>';
878
			return false;
879
		}
880
881
		// Do they meet the install requirements?
882
		// @todo Old client, new server?
883
		if (version_compare($databases[$db_type]['version'], preg_replace('~^\D*|\-.+?$~', '', eval($databases[$db_type]['version_check']))) > 0)
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
884
		{
885
			$incontext['error'] = $txt['error_db_too_low'];
886
			return false;
887
		}
888
889
		// Let's try that database on for size... assuming we haven't already lost the opportunity.
890
		if ($db_name != '' && !$needsDB)
891
		{
892
			$smcFunc['db_query']('', "
893
				CREATE DATABASE IF NOT EXISTS `$db_name`",
894
				array(
895
					'security_override' => true,
896
					'db_error_skip' => true,
897
				),
898
				$db_connection
899
			);
900
901
			// Okay, let's try the prefix if it didn't work...
902
			if (!$smcFunc['db_select_db']($db_name, $db_connection) && $db_name != '')
903
			{
904
				$smcFunc['db_query']('', "
905
					CREATE DATABASE IF NOT EXISTS `$_POST[db_prefix]$db_name`",
906
					array(
907
						'security_override' => true,
908
						'db_error_skip' => true,
909
					),
910
					$db_connection
911
				);
912
913
				if ($smcFunc['db_select_db']($_POST['db_prefix'] . $db_name, $db_connection))
914
				{
915
					$db_name = $_POST['db_prefix'] . $db_name;
916
					installer_updateSettingsFile(array('db_name' => $db_name));
917
				}
918
			}
919
920
			// Okay, now let's try to connect...
921
			if (!$smcFunc['db_select_db']($db_name, $db_connection))
922
			{
923
				$incontext['error'] = sprintf($txt['error_db_database'], $db_name);
924
				return false;
925
			}
926
		}
927
928
		return true;
929
	}
930
931
	return false;
932
}
933
934
// Let's start with basic forum type settings.
935
function ForumSettings()
936
{
937
	global $txt, $incontext, $databases, $db_type, $db_connection, $smcFunc;
938
939
	$incontext['sub_template'] = 'forum_settings';
940
	$incontext['page_title'] = $txt['install_settings'];
941
942
	// Let's see if we got the database type correct.
943
	if (isset($_POST['db_type'], $databases[$_POST['db_type']]))
944
		$db_type = $_POST['db_type'];
945
946
	// Else we'd better be able to get the connection.
947
	else
948
		load_database();
949
950
	$db_type = isset($_POST['db_type']) ? $_POST['db_type'] : $db_type;
951
952
	// What host and port are we on?
953
	$host = empty($_SERVER['HTTP_HOST']) ? $_SERVER['SERVER_NAME'] . (empty($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == '80' ? '' : ':' . $_SERVER['SERVER_PORT']) : $_SERVER['HTTP_HOST'];
954
955
	$secure = false;
956
957
	if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on')
958
		$secure = true;
959
	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')
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: (! empty($_SERVER['HTTP_...FORWARDED_SSL'] == 'on', Probably Intended Meaning: ! empty($_SERVER['HTTP_X...ORWARDED_SSL'] == 'on')
Loading history...
960
		$secure = true;
961
962
	// Now, to put what we've learned together... and add a path.
963
	$incontext['detected_url'] = 'http' . ($secure ? 's' : '') . '://' . $host . substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));
964
965
	// Check if the database sessions will even work.
966
	$incontext['test_dbsession'] = (ini_get('session.auto_start') != 1);
967
	$incontext['utf8_default'] = $databases[$db_type]['utf8_default'];
968
	$incontext['utf8_required'] = $databases[$db_type]['utf8_required'];
969
970
	$incontext['continue'] = 1;
971
972
	// Check Postgres setting
973
	if ( $db_type === 'postgresql')
974
	{
975
		load_database();
976
		$result = $smcFunc['db_query']('', '
977
			show standard_conforming_strings',
978
			array(
979
				'db_error_skip' => true,
980
			)
981
		);
982
983
		if ($result !== false)
984
		{
985
			$row = $smcFunc['db_fetch_assoc']($result);
986
			if ($row['standard_conforming_strings'] !== 'on')
987
				{
988
					$incontext['continue'] = 0;
989
					$incontext['error'] = $txt['error_pg_scs'];
990
				}
991
			$smcFunc['db_free_result']($result);
992
		}
993
	}
994
995
	// Setup the SSL checkbox...
996
	$incontext['ssl_chkbx_protected'] = false;
997
	$incontext['ssl_chkbx_checked'] = false;
998
999
	// If redirect in effect, force ssl ON
1000
	require_once(dirname(__FILE__) . '/Sources/Subs.php');
1001
	if (https_redirect_active($incontext['detected_url']))
1002
	{
1003
		$incontext['ssl_chkbx_protected'] = true;
1004
		$incontext['ssl_chkbx_checked'] = true;
1005
		$_POST['force_ssl'] = true;
1006
	}
1007
	// If no cert, make sure ssl stays OFF
1008
	if (!ssl_cert_found($incontext['detected_url']))
1009
	{
1010
		$incontext['ssl_chkbx_protected'] = true;
1011
		$incontext['ssl_chkbx_checked'] = false;
1012
	}
1013
1014
	// Submitting?
1015
	if (isset($_POST['boardurl']))
1016
	{
1017
		if (substr($_POST['boardurl'], -10) == '/index.php')
1018
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -10);
1019
		elseif (substr($_POST['boardurl'], -1) == '/')
1020
			$_POST['boardurl'] = substr($_POST['boardurl'], 0, -1);
1021
		if (substr($_POST['boardurl'], 0, 7) != 'http://' && substr($_POST['boardurl'], 0, 7) != 'file://' && substr($_POST['boardurl'], 0, 8) != 'https://')
1022
			$_POST['boardurl'] = 'http://' . $_POST['boardurl'];
1023
1024
		// Make sure boardurl is aligned with ssl setting
1025
		if (empty($_POST['force_ssl']))
1026
			$_POST['boardurl'] = strtr($_POST['boardurl'], array('https://' => 'http://'));
1027
		else
1028
			$_POST['boardurl'] = strtr($_POST['boardurl'], array('http://' => 'https://'));
1029
1030
		// Deal with different operating systems' directory structure...
1031
		$path = rtrim(str_replace(DIRECTORY_SEPARATOR, '/', __DIR__), '/');
1032
1033
		// Load the compatibility library if necessary.
1034
		if (!is_callable('random_bytes'))
1035
			require_once('Sources/random_compat/random.php');
1036
1037
		// Save these variables.
1038
		$vars = array(
1039
			'boardurl' => $_POST['boardurl'],
1040
			'boarddir' => $path,
1041
			'sourcedir' => $path . '/Sources',
1042
			'cachedir' => $path . '/cache',
1043
			'packagesdir' => $path . '/Packages',
1044
			'tasksdir' => $path . '/Sources/tasks',
1045
			'mbname' => strtr($_POST['mbname'], array('\"' => '"')),
1046
			'language' => substr($_SESSION['installer_temp_lang'], 8, -4),
1047
			'image_proxy_secret' => bin2hex(random_bytes(10)),
1048
			'image_proxy_enabled' => !empty($_POST['force_ssl']),
1049
			'auth_secret' => bin2hex(random_bytes(32)),
1050
		);
1051
1052
		// Must save!
1053
		if (!installer_updateSettingsFile($vars))
1054
		{
1055
			$incontext['error'] = $txt['settings_error'];
1056
			return false;
1057
		}
1058
1059
		// Make sure it works.
1060
		require(dirname(__FILE__) . '/Settings.php');
1061
1062
		// UTF-8 requires a setting to override the language charset.
1063
		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'])))
1064
		{
1065
			if (!$databases[$db_type]['utf8_support']())
1066
			{
1067
				$incontext['error'] = sprintf($txt['error_utf8_support']);
1068
				return false;
1069
			}
1070
1071
			if (!empty($databases[$db_type]['utf8_version_check']) && version_compare($databases[$db_type]['utf8_version'], preg_replace('~\-.+?$~', '', eval($databases[$db_type]['utf8_version_check'])), '>'))
0 ignored issues
show
introduced by
The use of eval() is discouraged.
Loading history...
1072
			{
1073
				$incontext['error'] = sprintf($txt['error_utf8_version'], $databases[$db_type]['utf8_version']);
1074
				return false;
1075
			}
1076
			else
1077
				// Set the character set here.
1078
				installer_updateSettingsFile(array('db_character_set' => 'utf8'));
1079
		}
1080
1081
		// Good, skip on.
1082
		return true;
1083
	}
1084
1085
	return false;
1086
}
1087
1088
// Step one: Do the SQL thang.
1089
function DatabasePopulation()
1090
{
1091
	global $db_character_set, $txt, $db_connection, $smcFunc, $databases, $modSettings, $db_type, $db_prefix, $incontext, $db_name, $boardurl;
1092
1093
	$incontext['sub_template'] = 'populate_database';
1094
	$incontext['page_title'] = $txt['db_populate'];
1095
	$incontext['continue'] = 1;
1096
1097
	// Already done?
1098
	if (isset($_POST['pop_done']))
1099
		return true;
1100
1101
	// Reload settings.
1102
	require(dirname(__FILE__) . '/Settings.php');
1103
	load_database();
1104
1105
	// Before running any of the queries, let's make sure another version isn't already installed.
1106
	$result = $smcFunc['db_query']('', '
1107
		SELECT variable, value
1108
		FROM {db_prefix}settings',
1109
		array(
1110
			'db_error_skip' => true,
1111
		)
1112
	);
1113
	$newSettings = array();
1114
	$modSettings = array();
1115
	if ($result !== false)
1116
	{
1117
		while ($row = $smcFunc['db_fetch_assoc']($result))
1118
			$modSettings[$row['variable']] = $row['value'];
1119
		$smcFunc['db_free_result']($result);
1120
1121
		// Do they match?  If so, this is just a refresh so charge on!
1122
		if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] != SMF_VERSION)
1123
		{
1124
			$incontext['error'] = $txt['error_versions_do_not_match'];
1125
			return false;
1126
		}
1127
	}
1128
	$modSettings['disableQueryCheck'] = true;
1129
1130
	// If doing UTF8, select it. PostgreSQL requires passing it as a string...
1131
	if (!empty($db_character_set) && $db_character_set == 'utf8' && !empty($databases[$db_type]['utf8_support']))
1132
		$smcFunc['db_query']('', '
1133
			SET NAMES {string:utf8}',
1134
			array(
1135
				'db_error_skip' => true,
1136
				'utf8' => 'utf8',
1137
			)
1138
		);
1139
1140
	// Windows likes to leave the trailing slash, which yields to C:\path\to\SMF\/attachments...
1141
	if (substr(__DIR__, -1) == '\\')
1142
		$attachdir = __DIR__ . 'attachments';
1143
	else
1144
		$attachdir = __DIR__ . '/attachments';
1145
1146
	$replaces = array(
1147
		'{$db_prefix}' => $db_prefix,
1148
		'{$attachdir}' => json_encode(array(1 => $smcFunc['db_escape_string']($attachdir))),
1149
		'{$boarddir}' => $smcFunc['db_escape_string'](dirname(__FILE__)),
1150
		'{$boardurl}' => $boardurl,
1151
		'{$enableCompressedOutput}' => isset($_POST['compress']) ? '1' : '0',
1152
		'{$databaseSession_enable}' => isset($_POST['dbsession']) ? '1' : '0',
1153
		'{$smf_version}' => SMF_VERSION,
1154
		'{$current_time}' => time(),
1155
		'{$sched_task_offset}' => 82800 + mt_rand(0, 86399),
1156
		'{$registration_method}' => isset($_POST['reg_mode']) ? $_POST['reg_mode'] : 0,
1157
	);
1158
1159
	foreach ($txt as $key => $value)
1160
	{
1161
		if (substr($key, 0, 8) == 'default_')
1162
			$replaces['{$' . $key . '}'] = $smcFunc['db_escape_string']($value);
1163
	}
1164
	$replaces['{$default_reserved_names}'] = strtr($replaces['{$default_reserved_names}'], array('\\\\n' => '\\n'));
1165
1166
	// MySQL-specific stuff - storage engine and UTF8 handling
1167
	if (substr($db_type, 0, 5) == 'mysql')
1168
	{
1169
		// Just in case the query fails for some reason...
1170
		$engines = array();
1171
1172
		// Figure out storage engines - what do we have, etc.
1173
		$get_engines = $smcFunc['db_query']('', 'SHOW ENGINES', array());
1174
1175
		while ($row = $smcFunc['db_fetch_assoc']($get_engines))
1176
		{
1177
			if ($row['Support'] == 'YES' || $row['Support'] == 'DEFAULT')
1178
				$engines[] = $row['Engine'];
1179
		}
1180
1181
		// Done with this now
1182
		$smcFunc['db_free_result']($get_engines);
1183
1184
		// InnoDB is better, so use it if possible...
1185
		$has_innodb = in_array('InnoDB', $engines);
1186
		$replaces['{$engine}'] = $has_innodb ? 'InnoDB' : 'MyISAM';
1187
		$replaces['{$memory}'] = (!$has_innodb && in_array('MEMORY', $engines)) ? 'MEMORY' : $replaces['{$engine}'];
1188
1189
		// If the UTF-8 setting was enabled, add it to the table definitions.
1190
		if (!empty($databases[$db_type]['utf8_support']) && (!empty($databases[$db_type]['utf8_required']) || isset($_POST['utf8'])))
1191
		{
1192
			$replaces['{$engine}'] .= ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
1193
			$replaces['{$memory}'] .= ' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci';
1194
		}
1195
1196
		// One last thing - if we don't have InnoDB, we can't do transactions...
1197
		if (!$has_innodb)
1198
		{
1199
			$replaces['START TRANSACTION;'] = '';
1200
			$replaces['COMMIT;'] = '';
1201
		}
1202
	}
1203
	else
1204
	{
1205
		$has_innodb = false;
1206
	}
1207
1208
	// Read in the SQL.  Turn this on and that off... internationalize... etc.
1209
	$type = ($db_type == 'mysqli' ? 'mysql' : $db_type);
1210
	$sql_lines = explode("\n", strtr(implode(' ', file(dirname(__FILE__) . '/install_' . DB_SCRIPT_VERSION . '_' . $type . '.sql')), $replaces));
1211
1212
	// Execute the SQL.
1213
	$current_statement = '';
1214
	$exists = array();
1215
	$incontext['failures'] = array();
1216
	$incontext['sql_results'] = array(
1217
		'tables' => 0,
1218
		'inserts' => 0,
1219
		'table_dups' => 0,
1220
		'insert_dups' => 0,
1221
	);
1222
	foreach ($sql_lines as $count => $line)
1223
	{
1224
		// No comments allowed!
1225
		if (substr(trim($line), 0, 1) != '#')
1226
			$current_statement .= "\n" . rtrim($line);
1227
1228
		// Is this the end of the query string?
1229
		if (empty($current_statement) || (preg_match('~;[\s]*$~s', $line) == 0 && $count != count($sql_lines)))
1230
			continue;
1231
1232
		// Does this table already exist?  If so, don't insert more data into it!
1233
		if (preg_match('~^\s*INSERT INTO ([^\s\n\r]+?)~', $current_statement, $match) != 0 && in_array($match[1], $exists))
1234
		{
1235
			preg_match_all('~\)[,;]~', $current_statement, $matches);
1236
			if (!empty($matches[0]))
1237
				$incontext['sql_results']['insert_dups'] += count($matches[0]);
1238
			else
1239
				$incontext['sql_results']['insert_dups']++;
1240
1241
			$current_statement = '';
1242
			continue;
1243
		}
1244
1245
		if ($smcFunc['db_query']('', $current_statement, array('security_override' => true, 'db_error_skip' => true), $db_connection) === false)
1246
		{
1247
			// Error 1050: Table already exists!
1248
			// @todo Needs to be made better!
1249
			if ((($db_type != 'mysql' && $db_type != 'mysqli') || mysqli_errno($db_connection) == 1050) && preg_match('~^\s*CREATE TABLE ([^\s\n\r]+?)~', $current_statement, $match) == 1)
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($db_type != 'mysql' && ...statement, $match) == 1, Probably Intended Meaning: $db_type != 'mysql' && $...tatement, $match) == 1)
Loading history...
1250
			{
1251
				$exists[] = $match[1];
1252
				$incontext['sql_results']['table_dups']++;
1253
			}
1254
			// Don't error on duplicate indexes (or duplicate operators in PostgreSQL.)
1255
			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)))
1256
			{
1257
				// MySQLi requires a connection object. It's optional with MySQL and Postgres
1258
				$incontext['failures'][$count] = $smcFunc['db_error']($db_connection);
1259
			}
1260
		}
1261
		else
1262
		{
1263
			if (preg_match('~^\s*CREATE TABLE ([^\s\n\r]+?)~', $current_statement, $match) == 1)
1264
				$incontext['sql_results']['tables']++;
1265
			elseif (preg_match('~^\s*INSERT INTO ([^\s\n\r]+?)~', $current_statement, $match) == 1)
1266
			{
1267
				preg_match_all('~\)[,;]~', $current_statement, $matches);
1268
				if (!empty($matches[0]))
1269
					$incontext['sql_results']['inserts'] += count($matches[0]);
1270
				else
1271
					$incontext['sql_results']['inserts']++;
1272
			}
1273
		}
1274
1275
		$current_statement = '';
1276
1277
		// Wait, wait, I'm still working here!
1278
		set_time_limit(60);
1279
	}
1280
1281
	// Sort out the context for the SQL.
1282
	foreach ($incontext['sql_results'] as $key => $number)
1283
	{
1284
		if ($number == 0)
1285
			unset($incontext['sql_results'][$key]);
1286
		else
1287
			$incontext['sql_results'][$key] = sprintf($txt['db_populate_' . $key], $number);
1288
	}
1289
1290
	// Make sure UTF will be used globally.
1291
	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'])))
1292
		$newSettings[] = array('global_character_set', 'UTF-8');
1293
1294
	// Are we allowing stat collection?
1295
	if (!empty($_POST['stats']) && substr($boardurl, 0, 16) != 'http://localhost' && empty($modSettings['allow_sm_stats']) && empty($modSettings['enable_sm_stats']))
1296
	{
1297
		$incontext['allow_sm_stats'] = true;
1298
1299
		// Attempt to register the site etc.
1300
		$fp = @fsockopen('www.simplemachines.org', 443, $errno, $errstr);
1301
		if (!$fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
1302
			$fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
1303
		if ($fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
1304
		{
1305
			$out = 'GET /smf/stats/register_stats.php?site=' . base64_encode($boardurl) . ' HTTP/1.1' . "\r\n";
1306
			$out .= 'Host: www.simplemachines.org' . "\r\n";
1307
			$out .= 'Connection: Close' . "\r\n\r\n";
1308
			fwrite($fp, $out);
1309
1310
			$return_data = '';
1311
			while (!feof($fp))
1312
				$return_data .= fgets($fp, 128);
1313
1314
			fclose($fp);
1315
1316
			// Get the unique site ID.
1317
			preg_match('~SITE-ID:\s(\w{10})~', $return_data, $ID);
1318
1319
			if (!empty($ID[1]))
1320
				$smcFunc['db_insert']('replace',
1321
					$db_prefix . 'settings',
1322
					array('variable' => 'string', 'value' => 'string'),
1323
					array(
1324
						array('sm_stats_key', $ID[1]),
1325
						array('enable_sm_stats', 1),
1326
					),
1327
					array('variable')
1328
				);
1329
		}
1330
	}
1331
	// Don't remove stat collection unless we unchecked the box for real, not from the loop.
1332
	elseif (empty($_POST['stats']) && empty($incontext['allow_sm_stats']))
1333
		$smcFunc['db_query']('', '
1334
			DELETE FROM {db_prefix}settings
1335
			WHERE variable = {string:enable_sm_stats}',
1336
			array(
1337
				'enable_sm_stats' => 'enable_sm_stats',
1338
				'db_error_skip' => true,
1339
			)
1340
		);
1341
1342
	// Are we enabling SSL?
1343
	if (!empty($_POST['force_ssl']))
1344
		$newSettings[] = array('force_ssl', 1);
1345
1346
	// Setting a timezone is required.
1347
	if (!isset($modSettings['default_timezone']) && function_exists('date_default_timezone_set'))
1348
	{
1349
		// Get PHP's default timezone, if set
1350
		$ini_tz = ini_get('date.timezone');
1351
		if (!empty($ini_tz))
1352
			$timezone_id = $ini_tz;
1353
		else
1354
			$timezone_id = '';
1355
1356
		// If date.timezone is unset, invalid, or just plain weird, make a best guess
1357
		if (!in_array($timezone_id, timezone_identifiers_list()))
0 ignored issues
show
Bug introduced by
timezone_identifiers_list() of type void is incompatible with the type array expected by parameter $haystack of in_array(). ( Ignorable by Annotation )

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

1357
		if (!in_array($timezone_id, /** @scrutinizer ignore-type */ timezone_identifiers_list()))
Loading history...
Bug introduced by
Are you sure the usage of timezone_identifiers_list() is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
1358
		{
1359
			$server_offset = @mktime(0, 0, 0, 1, 1, 1970);
1360
			$timezone_id = timezone_name_from_abbr('', $server_offset, 0);
0 ignored issues
show
Bug introduced by
It seems like $server_offset can also be of type false; however, parameter $utcOffset of timezone_name_from_abbr() does only seem to accept integer, 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

1360
			$timezone_id = timezone_name_from_abbr('', /** @scrutinizer ignore-type */ $server_offset, 0);
Loading history...
1361
		}
1362
1363
		if (date_default_timezone_set($timezone_id))
1364
			$newSettings[] = array('default_timezone', $timezone_id);
1365
	}
1366
1367
	if (!empty($newSettings))
1368
	{
1369
		$smcFunc['db_insert']('replace',
1370
			'{db_prefix}settings',
1371
			array('variable' => 'string-255', 'value' => 'string-65534'),
1372
			$newSettings,
1373
			array('variable')
1374
		);
1375
	}
1376
1377
	// Populate the smiley_files table.
1378
	// Can't just dump this data in the SQL file because we need to know the id for each smiley.
1379
	$smiley_filenames = array(
1380
		':)' => 'smiley',
1381
		';)' => 'wink',
1382
		':D' => 'cheesy',
1383
		';D' => 'grin',
1384
		'>:(' => 'angry',
1385
		':(' => 'sad',
1386
		':o' => 'shocked',
1387
		'8)' => 'cool',
1388
		'???' => 'huh',
1389
		'::)' => 'rolleyes',
1390
		':P' => 'tongue',
1391
		':-[' => 'embarrassed',
1392
		':-X' => 'lipsrsealed',
1393
		':-\\' => 'undecided',
1394
		':-*' => 'kiss',
1395
		':\'(' => 'cry',
1396
		'>:D' => 'evil',
1397
		'^-^' => 'azn',
1398
		'O0' => 'afro',
1399
		':))' => 'laugh',
1400
		'C:-)' => 'police',
1401
		'O:-)' => 'angel'
1402
	);
1403
	$smiley_set_extensions = array('fugue' => '.png', 'alienine' => '.png');
1404
1405
	$smiley_inserts = array();
1406
	$request = $smcFunc['db_query']('', '
1407
		SELECT id_smiley, code
1408
		FROM {db_prefix}smileys',
1409
		array()
1410
	);
1411
	while ($row = $smcFunc['db_fetch_assoc']($request))
1412
	{
1413
		foreach ($smiley_set_extensions as $set => $ext)
1414
			$smiley_inserts[] = array($row['id_smiley'], $set, $smiley_filenames[$row['code']] . $ext);
1415
	}
1416
	$smcFunc['db_free_result']($request);
1417
1418
	$smcFunc['db_insert']('ignore',
1419
		'{db_prefix}smiley_files',
1420
		array('id_smiley' => 'int', 'smiley_set' => 'string-48', 'filename' => 'string-48'),
1421
		$smiley_inserts,
1422
		array('id_smiley', 'smiley_set')
1423
	);
1424
1425
	// Let's optimize those new tables, but not on InnoDB, ok?
1426
	if (!$has_innodb)
1427
	{
1428
		db_extend();
1429
		$tables = $smcFunc['db_list_tables']($db_name, $db_prefix . '%');
1430
		foreach ($tables as $table)
1431
		{
1432
			$smcFunc['db_optimize_table']($table) != -1 or $db_messed = true;
1433
1434
			if (!empty($db_messed))
1435
			{
1436
				$incontext['failures'][-1] = $smcFunc['db_error']();
1437
				break;
1438
			}
1439
		}
1440
	}
1441
1442
	// MySQL specific stuff
1443
	if (substr($db_type, 0, 5) != 'mysql')
1444
		return false;
1445
1446
	// Find database user privileges.
1447
	$privs = array();
1448
	$get_privs = $smcFunc['db_query']('', 'SHOW PRIVILEGES', array());
1449
	while ($row = $smcFunc['db_fetch_assoc']($get_privs))
1450
	{
1451
		if ($row['Privilege'] == 'Alter')
1452
			$privs[] = $row['Privilege'];
1453
	}
1454
	$smcFunc['db_free_result']($get_privs);
1455
1456
	// Check for the ALTER privilege.
1457
	if (!empty($databases[$db_type]['alter_support']) && !in_array('Alter', $privs))
1458
	{
1459
		$incontext['error'] = $txt['error_db_alter_priv'];
1460
		return false;
1461
	}
1462
1463
	if (!empty($exists))
1464
	{
1465
		$incontext['page_title'] = $txt['user_refresh_install'];
1466
		$incontext['was_refresh'] = true;
1467
	}
1468
1469
	return false;
1470
}
1471
1472
// Ask for the administrator login information.
1473
function AdminAccount()
1474
{
1475
	global $txt, $db_type, $smcFunc, $incontext, $db_prefix, $db_passwd, $sourcedir, $db_character_set;
1476
1477
	$incontext['sub_template'] = 'admin_account';
1478
	$incontext['page_title'] = $txt['user_settings'];
1479
	$incontext['continue'] = 1;
1480
1481
	// Skipping?
1482
	if (!empty($_POST['skip']))
1483
		return true;
1484
1485
	// Need this to check whether we need the database password.
1486
	require(dirname(__FILE__) . '/Settings.php');
1487
	load_database();
1488
1489
	require_once($sourcedir . '/Subs-Auth.php');
1490
1491
	require_once($sourcedir . '/Subs.php');
1492
1493
	// Reload settings & set some global funcs
1494
	require_once($sourcedir . '/Load.php');
1495
	reloadSettings();
1496
1497
	// We need this to properly hash the password for Admin
1498
	$smcFunc['strtolower'] = $db_character_set != 'utf8' && $txt['lang_character_set'] != 'UTF-8' ? 'strtolower' : function($string)
1499
	{
1500
		global $sourcedir;
1501
		if (function_exists('mb_strtolower'))
1502
			return mb_strtolower($string, 'UTF-8');
1503
		require_once($sourcedir . '/Subs-Charset.php');
1504
		return utf8_strtolower($string);
1505
	};
1506
1507
	if (!isset($_POST['username']))
1508
		$_POST['username'] = '';
1509
	if (!isset($_POST['email']))
1510
		$_POST['email'] = '';
1511
	if (!isset($_POST['server_email']))
1512
		$_POST['server_email'] = '';
1513
1514
	$incontext['username'] = htmlspecialchars($_POST['username']);
1515
	$incontext['email'] = htmlspecialchars($_POST['email']);
1516
	$incontext['server_email'] = htmlspecialchars($_POST['server_email']);
1517
1518
	$incontext['require_db_confirm'] = empty($db_type);
1519
1520
	// Only allow skipping if we think they already have an account setup.
1521
	$request = $smcFunc['db_query']('', '
1522
		SELECT id_member
1523
		FROM {db_prefix}members
1524
		WHERE id_group = {int:admin_group} OR FIND_IN_SET({int:admin_group}, additional_groups) != 0
1525
		LIMIT 1',
1526
		array(
1527
			'db_error_skip' => true,
1528
			'admin_group' => 1,
1529
		)
1530
	);
1531
	if ($smcFunc['db_num_rows']($request) != 0)
1532
		$incontext['skip'] = 1;
1533
	$smcFunc['db_free_result']($request);
1534
1535
	// Trying to create an account?
1536
	if (isset($_POST['password1']) && !empty($_POST['contbutt']))
1537
	{
1538
		// Wrong password?
1539
		if ($incontext['require_db_confirm'] && $_POST['password3'] != $db_passwd)
1540
		{
1541
			$incontext['error'] = $txt['error_db_connect'];
1542
			return false;
1543
		}
1544
		// Not matching passwords?
1545
		if ($_POST['password1'] != $_POST['password2'])
1546
		{
1547
			$incontext['error'] = $txt['error_user_settings_again_match'];
1548
			return false;
1549
		}
1550
		// No password?
1551
		if (strlen($_POST['password1']) < 4)
1552
		{
1553
			$incontext['error'] = $txt['error_user_settings_no_password'];
1554
			return false;
1555
		}
1556
		if (!file_exists($sourcedir . '/Subs.php'))
1557
		{
1558
			$incontext['error'] = sprintf($txt['error_sourcefile_missing'], 'Subs.php');
1559
			return false;
1560
		}
1561
1562
		// Update the webmaster's email?
1563
		if (!empty($_POST['server_email']) && (empty($webmaster_email) || $webmaster_email == '[email protected]'))
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $webmaster_email seems to never exist and therefore empty should always be true.
Loading history...
1564
			installer_updateSettingsFile(array('webmaster_email' => $_POST['server_email']));
1565
1566
		// Work out whether we're going to have dodgy characters and remove them.
1567
		$invalid_characters = preg_match('~[<>&"\'=\\\]~', $_POST['username']) != 0;
1568
		$_POST['username'] = preg_replace('~[<>&"\'=\\\]~', '', $_POST['username']);
1569
1570
		$result = $smcFunc['db_query']('', '
1571
			SELECT id_member, password_salt
1572
			FROM {db_prefix}members
1573
			WHERE member_name = {string:username} OR email_address = {string:email}
1574
			LIMIT 1',
1575
			array(
1576
				'username' => $_POST['username'],
1577
				'email' => $_POST['email'],
1578
				'db_error_skip' => true,
1579
			)
1580
		);
1581
		if ($smcFunc['db_num_rows']($result) != 0)
1582
		{
1583
			list ($incontext['member_id'], $incontext['member_salt']) = $smcFunc['db_fetch_row']($result);
1584
			$smcFunc['db_free_result']($result);
1585
1586
			$incontext['account_existed'] = $txt['error_user_settings_taken'];
1587
		}
1588
		elseif ($_POST['username'] == '' || strlen($_POST['username']) > 25)
1589
		{
1590
			// Try the previous step again.
1591
			$incontext['error'] = $_POST['username'] == '' ? $txt['error_username_left_empty'] : $txt['error_username_too_long'];
1592
			return false;
1593
		}
1594
		elseif ($invalid_characters || $_POST['username'] == '_' || $_POST['username'] == '|' || strpos($_POST['username'], '[code') !== false || strpos($_POST['username'], '[/code') !== false)
1595
		{
1596
			// Try the previous step again.
1597
			$incontext['error'] = $txt['error_invalid_characters_username'];
1598
			return false;
1599
		}
1600
		elseif (empty($_POST['email']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) || strlen($_POST['email']) > 255)
1601
		{
1602
			// One step back, this time fill out a proper admin email address.
1603
			$incontext['error'] = sprintf($txt['error_valid_admin_email_needed'], $_POST['username']);
1604
			return false;
1605
		}
1606
		elseif (empty($_POST['server_email']) || !filter_var($_POST['server_email'], FILTER_VALIDATE_EMAIL) || strlen($_POST['server_email']) > 255)
1607
		{
1608
			// One step back, this time fill out a proper admin email address.
1609
			$incontext['error'] = $txt['error_valid_server_email_needed'];
1610
			return false;
1611
		}
1612
		elseif ($_POST['username'] != '')
1613
		{
1614
			if (!is_callable('random_int'))
1615
				require_once('Sources/random_compat/random.php');
1616
1617
			$incontext['member_salt'] = bin2hex(random_bytes(16));
1618
1619
			// Format the username properly.
1620
			$_POST['username'] = preg_replace('~[\t\n\r\x0B\0\xA0]+~', ' ', $_POST['username']);
1621
			$ip = isset($_SERVER['REMOTE_ADDR']) ? substr($_SERVER['REMOTE_ADDR'], 0, 255) : '';
1622
1623
			$_POST['password1'] = hash_password($_POST['username'], $_POST['password1']);
1624
1625
			$incontext['member_id'] = $smcFunc['db_insert']('',
1626
				$db_prefix . 'members',
1627
				array(
1628
					'member_name' => 'string-25',
1629
					'real_name' => 'string-25',
1630
					'passwd' => 'string',
1631
					'email_address' => 'string',
1632
					'id_group' => 'int',
1633
					'posts' => 'int',
1634
					'date_registered' => 'int',
1635
					'password_salt' => 'string',
1636
					'lngfile' => 'string',
1637
					'personal_text' => 'string',
1638
					'avatar' => 'string',
1639
					'member_ip' => 'inet',
1640
					'member_ip2' => 'inet',
1641
					'buddy_list' => 'string',
1642
					'pm_ignore_list' => 'string',
1643
					'website_title' => 'string',
1644
					'website_url' => 'string',
1645
					'signature' => 'string',
1646
					'usertitle' => 'string',
1647
					'secret_question' => 'string',
1648
					'additional_groups' => 'string',
1649
					'ignore_boards' => 'string',
1650
				),
1651
				array(
1652
					$_POST['username'],
1653
					$_POST['username'],
1654
					$_POST['password1'],
1655
					$_POST['email'],
1656
					1,
1657
					0,
1658
					time(),
1659
					$incontext['member_salt'],
1660
					'',
1661
					'',
1662
					'',
1663
					$ip,
1664
					$ip,
1665
					'',
1666
					'',
1667
					'',
1668
					'',
1669
					'',
1670
					'',
1671
					'',
1672
					'',
1673
					'',
1674
				),
1675
				array('id_member'),
1676
				1
1677
			);
1678
		}
1679
1680
		// If we're here we're good.
1681
		return true;
1682
	}
1683
1684
	return false;
1685
}
1686
1687
// Final step, clean up and a complete message!
1688
function DeleteInstall()
1689
{
1690
	global $smcFunc, $db_character_set, $context, $txt, $incontext;
1691
	global $databases, $sourcedir, $modSettings, $user_info, $db_type, $boardurl;
1692
	global $auth_secret, $cookiename;
1693
1694
	$incontext['page_title'] = $txt['congratulations'];
1695
	$incontext['sub_template'] = 'delete_install';
1696
	$incontext['continue'] = 0;
1697
1698
	require(dirname(__FILE__) . '/Settings.php');
1699
	load_database();
1700
1701
	chdir(dirname(__FILE__));
1702
1703
	require_once($sourcedir . '/Errors.php');
1704
	require_once($sourcedir . '/Logging.php');
1705
	require_once($sourcedir . '/Subs.php');
1706
	require_once($sourcedir . '/Load.php');
1707
	require_once($sourcedir . '/Security.php');
1708
	require_once($sourcedir . '/Subs-Auth.php');
1709
1710
	// Reload settings & set some global funcs
1711
	reloadSettings();
1712
1713
	// Bring a warning over.
1714
	if (!empty($incontext['account_existed']))
1715
		$incontext['warning'] = $incontext['account_existed'];
1716
1717
	if (!empty($db_character_set) && !empty($databases[$db_type]['utf8_support']))
1718
		$smcFunc['db_query']('', '
1719
			SET NAMES {string:db_character_set}',
1720
			array(
1721
				'db_character_set' => $db_character_set,
1722
				'db_error_skip' => true,
1723
			)
1724
		);
1725
1726
	// As track stats is by default enabled let's add some activity.
1727
	$smcFunc['db_insert']('ignore',
1728
		'{db_prefix}log_activity',
1729
		array('date' => 'date', 'topics' => 'int', 'posts' => 'int', 'registers' => 'int'),
1730
		array(strftime('%Y-%m-%d', time()), 1, 1, (!empty($incontext['member_id']) ? 1 : 0)),
1731
		array('date')
1732
	);
1733
1734
	// We're going to want our lovely $modSettings now.
1735
	$request = $smcFunc['db_query']('', '
1736
		SELECT variable, value
1737
		FROM {db_prefix}settings',
1738
		array(
1739
			'db_error_skip' => true,
1740
		)
1741
	);
1742
	// Only proceed if we can load the data.
1743
	if ($request)
1744
	{
1745
		while ($row = $smcFunc['db_fetch_row']($request))
1746
			$modSettings[$row[0]] = $row[1];
1747
		$smcFunc['db_free_result']($request);
1748
	}
1749
1750
	// Automatically log them in ;)
1751
	if (isset($incontext['member_id']) && isset($incontext['member_salt']))
1752
		setLoginCookie(3153600 * 60, $incontext['member_id'], hash_salt($_POST['password1'], $incontext['member_salt']));
1753
1754
	$result = $smcFunc['db_query']('', '
1755
		SELECT value
1756
		FROM {db_prefix}settings
1757
		WHERE variable = {string:db_sessions}',
1758
		array(
1759
			'db_sessions' => 'databaseSession_enable',
1760
			'db_error_skip' => true,
1761
		)
1762
	);
1763
	if ($smcFunc['db_num_rows']($result) != 0)
1764
		list ($db_sessions) = $smcFunc['db_fetch_row']($result);
1765
	$smcFunc['db_free_result']($result);
1766
1767
	if (empty($db_sessions))
1768
		$_SESSION['admin_time'] = time();
1769
	else
1770
	{
1771
		$_SERVER['HTTP_USER_AGENT'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 211);
1772
1773
		$smcFunc['db_insert']('replace',
1774
			'{db_prefix}sessions',
1775
			array(
1776
				'session_id' => 'string', 'last_update' => 'int', 'data' => 'string',
1777
			),
1778
			array(
1779
				session_id(), time(), 'USER_AGENT|s:' . strlen($_SERVER['HTTP_USER_AGENT']) . ':"' . $_SERVER['HTTP_USER_AGENT'] . '";admin_time|i:' . time() . ';',
1780
			),
1781
			array('session_id')
1782
		);
1783
	}
1784
1785
	updateStats('member');
1786
	updateStats('message');
1787
	updateStats('topic');
1788
1789
	// This function is needed to do the updateStats('subject') call.
1790
	$smcFunc['strtolower'] = $db_character_set != 'utf8' && $txt['lang_character_set'] != 'UTF-8' ? 'strtolower' : function($string)
1791
	{
1792
		global $sourcedir;
1793
		if (function_exists('mb_strtolower'))
1794
			return mb_strtolower($string, 'UTF-8');
1795
		require_once($sourcedir . '/Subs-Charset.php');
1796
		return utf8_strtolower($string);
1797
	};
1798
1799
	$request = $smcFunc['db_query']('', '
1800
		SELECT id_msg
1801
		FROM {db_prefix}messages
1802
		WHERE id_msg = 1
1803
			AND modified_time = 0
1804
		LIMIT 1',
1805
		array(
1806
			'db_error_skip' => true,
1807
		)
1808
	);
1809
	$context['utf8'] = $db_character_set === 'utf8' || $txt['lang_character_set'] === 'UTF-8';
1810
	if ($smcFunc['db_num_rows']($request) > 0)
1811
		updateStats('subject', 1, htmlspecialchars($txt['default_topic_subject']));
1812
	$smcFunc['db_free_result']($request);
1813
1814
	// Now is the perfect time to fetch the SM files.
1815
	require_once($sourcedir . '/ScheduledTasks.php');
1816
	// Sanity check that they loaded earlier!
1817
	if (isset($modSettings['recycle_board']))
1818
	{
1819
		scheduled_fetchSMfiles(); // Now go get those files!
1820
1821
		// We've just installed!
1822
		$user_info['ip'] = $_SERVER['REMOTE_ADDR'];
1823
		$user_info['id'] = isset($incontext['member_id']) ? $incontext['member_id'] : 0;
1824
		logAction('install', array('version' => SMF_FULL_VERSION), 'admin');
1825
	}
1826
1827
	// Disable the legacy BBC by default for new installs
1828
	updateSettings(array(
1829
		'disabledBBC' => implode(',', $context['legacy_bbc']),
1830
	));
1831
1832
	// Some final context for the template.
1833
	$incontext['dir_still_writable'] = is_writable(dirname(__FILE__)) && substr(__FILE__, 1, 2) != ':\\';
1834
	$incontext['probably_delete_install'] = isset($_SESSION['installer_temp_ftp']) || is_writable(dirname(__FILE__)) || is_writable(__FILE__);
1835
1836
	// Update hash's cost to an appropriate setting
1837
	updateSettings(array(
1838
		'bcrypt_hash_cost' => hash_benchmark(),
1839
	));
1840
1841
	return false;
1842
}
1843
1844
function installer_updateSettingsFile($vars, $rebuild = false)
1845
{
1846
	global $sourcedir, $context, $db_character_set, $txt;
1847
1848
	$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');
1849
1850
	if (empty($sourcedir))
1851
	{
1852
		if (file_exists(dirname(__FILE__) . '/Sources') && is_dir(dirname(__FILE__) . '/Sources'))
1853
			$sourcedir = dirname(__FILE__) . '/Sources';
1854
		else
1855
			return false;
1856
	}
1857
1858
	if (!is_writeable(dirname(__FILE__) . '/Settings.php'))
1859
	{
1860
		@chmod(dirname(__FILE__) . '/Settings.php', 0777);
1861
1862
		if (!is_writeable(dirname(__FILE__) . '/Settings.php'))
1863
			return false;
1864
	}
1865
1866
	require_once($sourcedir . '/Subs.php');
1867
	require_once($sourcedir . '/Subs-Admin.php');
1868
1869
	return updateSettingsFile($vars, false, $rebuild);
1870
}
1871
1872
// Create an .htaccess file to prevent mod_security. SMF has filtering built-in.
1873
function fixModSecurity()
1874
{
1875
	$htaccess_addition = '
1876
<IfModule mod_security.c>
1877
	# Turn off mod_security filtering.  SMF is a big boy, it doesn\'t need its hands held.
1878
	SecFilterEngine Off
1879
1880
	# The below probably isn\'t needed, but better safe than sorry.
1881
	SecFilterScanPOST Off
1882
</IfModule>';
1883
1884
	if (!function_exists('apache_get_modules') || !in_array('mod_security', apache_get_modules()))
1885
		return true;
1886
	elseif (file_exists(dirname(__FILE__) . '/.htaccess') && is_writable(dirname(__FILE__) . '/.htaccess'))
1887
	{
1888
		$current_htaccess = implode('', file(dirname(__FILE__) . '/.htaccess'));
1889
1890
		// Only change something if mod_security hasn't been addressed yet.
1891
		if (strpos($current_htaccess, '<IfModule mod_security.c>') === false)
1892
		{
1893
			if ($ht_handle = fopen(dirname(__FILE__) . '/.htaccess', 'a'))
1894
			{
1895
				fwrite($ht_handle, $htaccess_addition);
1896
				fclose($ht_handle);
1897
				return true;
1898
			}
1899
			else
1900
				return false;
1901
		}
1902
		else
1903
			return true;
1904
	}
1905
	elseif (file_exists(dirname(__FILE__) . '/.htaccess'))
1906
		return strpos(implode('', file(dirname(__FILE__) . '/.htaccess')), '<IfModule mod_security.c>') !== false;
1907
	elseif (is_writable(dirname(__FILE__)))
1908
	{
1909
		if ($ht_handle = fopen(dirname(__FILE__) . '/.htaccess', 'w'))
1910
		{
1911
			fwrite($ht_handle, $htaccess_addition);
1912
			fclose($ht_handle);
1913
			return true;
1914
		}
1915
		else
1916
			return false;
1917
	}
1918
	else
1919
		return false;
1920
}
1921
1922
function template_install_above()
1923
{
1924
	global $incontext, $txt, $installurl;
1925
1926
	echo '<!DOCTYPE html>
1927
<html', $txt['lang_rtl'] == true ? ' dir="rtl"' : '', '>
1928
<head>
1929
	<meta charset="', isset($txt['lang_character_set']) ? $txt['lang_character_set'] : 'UTF-8', '">
1930
	<meta name="robots" content="noindex">
1931
	<title>', $txt['smf_installer'], '</title>
1932
	<link rel="stylesheet" href="Themes/default/css/index.css">
1933
	<link rel="stylesheet" href="Themes/default/css/install.css">
1934
	', $txt['lang_rtl'] == true ? '<link rel="stylesheet" href="Themes/default/css/rtl.css">' : '', '
1935
1936
	<script src="Themes/default/scripts/jquery-' . JQUERY_VERSION . '.min.js"></script>
1937
	<script src="Themes/default/scripts/script.js"></script>
1938
</head>
1939
<body>
1940
	<div id="footerfix">
1941
	<div id="header">
1942
		<h1 class="forumtitle">', $txt['smf_installer'], '</h1>
1943
		<img id="smflogo" src="Themes/default/images/smflogo.svg" alt="Simple Machines Forum" title="Simple Machines Forum">
1944
	</div>
1945
	<div id="wrapper">';
1946
1947
	// Have we got a language drop down - if so do it on the first step only.
1948
	if (!empty($incontext['detected_languages']) && count($incontext['detected_languages']) > 1 && $incontext['current_step'] == 0)
1949
	{
1950
		echo '
1951
		<div id="upper_section">
1952
			<div id="inner_section">
1953
				<div id="inner_wrap">
1954
					<div class="news">
1955
						<form action="', $installurl, '" method="get">
1956
							<label for="installer_language">', $txt['installer_language'], ':</label>
1957
							<select id="installer_language" name="lang_file" onchange="location.href = \'', $installurl, '?lang_file=\' + this.options[this.selectedIndex].value;">';
1958
1959
		foreach ($incontext['detected_languages'] as $lang => $name)
1960
			echo '
1961
								<option', isset($_SESSION['installer_temp_lang']) && $_SESSION['installer_temp_lang'] == $lang ? ' selected' : '', ' value="', $lang, '">', $name, '</option>';
1962
1963
		echo '
1964
							</select>
1965
							<noscript><input type="submit" value="', $txt['installer_language_set'], '" class="button"></noscript>
1966
						</form>
1967
					</div><!-- .news -->
1968
					<hr class="clear">
1969
				</div><!-- #inner_wrap -->
1970
			</div><!-- #inner_section -->
1971
		</div><!-- #upper_section -->';
1972
	}
1973
1974
	echo '
1975
		<div id="content_section">
1976
			<div id="main_content_section">
1977
				<div id="main_steps">
1978
					<h2>', $txt['upgrade_progress'], '</h2>
1979
					<ul class="steps_list">';
1980
1981
	foreach ($incontext['steps'] as $num => $step)
1982
		echo '
1983
						<li', $num == $incontext['current_step'] ? ' class="stepcurrent"' : '', '>
1984
							', $txt['upgrade_step'], ' ', $step[0], ': ', $step[1], '
1985
						</li>';
1986
1987
	echo '
1988
					</ul>
1989
				</div>
1990
				<div id="install_progress">
1991
					<div id="progress_bar" class="progress_bar progress_green">
1992
						<h3>'. $txt['upgrade_overall_progress'], '</h3>
1993
						<span id="overall_text">', $incontext['overall_percent'], '%</span>
1994
						<div id="overall_progress" class="bar" style="width: ', $incontext['overall_percent'], '%;"></div>
1995
					</div>
1996
				</div>
1997
				<div id="main_screen" class="clear">
1998
					<h2>', $incontext['page_title'], '</h2>
1999
					<div class="panel">';
2000
}
2001
2002
function template_install_below()
2003
{
2004
	global $incontext, $txt;
2005
2006
	if (!empty($incontext['continue']) || !empty($incontext['skip']))
2007
	{
2008
		echo '
2009
							<div class="floatright">';
2010
2011
		if (!empty($incontext['continue']))
2012
			echo '
2013
								<input type="submit" id="contbutt" name="contbutt" value="', $txt['upgrade_continue'], '" onclick="return submitThisOnce(this);" class="button">';
2014
		if (!empty($incontext['skip']))
2015
			echo '
2016
								<input type="submit" id="skip" name="skip" value="', $txt['upgrade_skip'], '" onclick="return submitThisOnce(this);" class="button">';
2017
		echo '
2018
							</div>';
2019
	}
2020
2021
	// Show the closing form tag and other data only if not in the last step
2022
	if (count($incontext['steps']) - 1 !== (int) $incontext['current_step'])
2023
		echo '
2024
						</form>';
2025
2026
	echo '
2027
					</div><!-- .panel -->
2028
				</div><!-- #main_screen -->
2029
			</div><!-- #main_content_section -->
2030
		</div><!-- #content_section -->
2031
	</div><!-- #wrapper -->
2032
	</div><!-- #footerfix -->
2033
	<div id="footer">
2034
		<ul>
2035
			<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>
2036
		</ul>
2037
	</div>
2038
</body>
2039
</html>';
2040
}
2041
2042
// Welcome them to the wonderful world of SMF!
2043
function template_welcome_message()
2044
{
2045
	global $incontext, $txt;
2046
2047
	echo '
2048
	<script src="https://www.simplemachines.org/smf/current-version.js?version=' . urlencode(SMF_VERSION) . '"></script>
2049
	<form action="', $incontext['form_url'], '" method="post">
2050
		<p>', sprintf($txt['install_welcome_desc'], SMF_VERSION), '</p>
2051
		<div id="version_warning" class="noticebox hidden">
2052
			<h3>', $txt['error_warning_notice'], '</h3>
2053
			', sprintf($txt['error_script_outdated'], '<em id="smfVersion" style="white-space: nowrap;">??</em>', '<em id="yourVersion" style="white-space: nowrap;">' . SMF_VERSION . '</em>'), '
2054
		</div>';
2055
2056
	// Show the warnings, or not.
2057
	if (template_warning_divs())
2058
		echo '
2059
		<h3>', $txt['install_all_lovely'], '</h3>';
2060
2061
	// Say we want the continue button!
2062
	if (empty($incontext['error']))
2063
		$incontext['continue'] = 1;
2064
2065
	// For the latest version stuff.
2066
	echo '
2067
		<script>
2068
			// Latest version?
2069
			function smfCurrentVersion()
2070
			{
2071
				var smfVer, yourVer;
2072
2073
				if (!(\'smfVersion\' in window))
2074
					return;
2075
2076
				window.smfVersion = window.smfVersion.replace(/SMF\s?/g, \'\');
2077
2078
				smfVer = document.getElementById("smfVersion");
2079
				yourVer = document.getElementById("yourVersion");
2080
2081
				setInnerHTML(smfVer, window.smfVersion);
2082
2083
				var currentVersion = getInnerHTML(yourVer);
2084
				if (currentVersion < window.smfVersion)
2085
					document.getElementById(\'version_warning\').classList.remove(\'hidden\');
2086
			}
2087
			addLoadEvent(smfCurrentVersion);
2088
		</script>';
2089
}
2090
2091
// A shortcut for any warning stuff.
2092
function template_warning_divs()
2093
{
2094
	global $txt, $incontext;
2095
2096
	// Errors are very serious..
2097
	if (!empty($incontext['error']))
2098
		echo '
2099
		<div class="errorbox">
2100
			<h3>', $txt['upgrade_critical_error'], '</h3>
2101
			', $incontext['error'], '
2102
		</div>';
2103
	// A warning message?
2104
	elseif (!empty($incontext['warning']))
2105
		echo '
2106
		<div class="errorbox">
2107
			<h3>', $txt['upgrade_warning'], '</h3>
2108
			', $incontext['warning'], '
2109
		</div>';
2110
2111
	return empty($incontext['error']) && empty($incontext['warning']);
2112
}
2113
2114
function template_chmod_files()
2115
{
2116
	global $txt, $incontext;
2117
2118
	echo '
2119
		<p>', $txt['ftp_setup_why_info'], '</p>
2120
		<ul class="error_content">
2121
			<li>', implode('</li>
2122
			<li>', $incontext['failed_files']), '</li>
2123
		</ul>';
2124
2125
	if (isset($incontext['systemos'], $incontext['detected_path']) && $incontext['systemos'] == 'linux')
2126
		echo '
2127
		<hr>
2128
		<p>', $txt['chmod_linux_info'], '</p>
2129
		<samp># chmod a+w ', implode(' ' . $incontext['detected_path'] . '/', $incontext['failed_files']), '</samp>';
2130
2131
	// This is serious!
2132
	if (!template_warning_divs())
2133
		return;
2134
2135
	echo '
2136
		<hr>
2137
		<p>', $txt['ftp_setup_info'], '</p>';
2138
2139
	if (!empty($incontext['ftp_errors']))
2140
		echo '
2141
		<div class="error_message">
2142
			', $txt['error_ftp_no_connect'], '<br><br>
2143
			<code>', implode('<br>', $incontext['ftp_errors']), '</code>
2144
		</div>';
2145
2146
	echo '
2147
		<form action="', $incontext['form_url'], '" method="post">
2148
			<dl class="settings">
2149
				<dt>
2150
					<label for="ftp_server">', $txt['ftp_server'], ':</label>
2151
				</dt>
2152
				<dd>
2153
					<div class="floatright">
2154
						<label for="ftp_port" class="textbox"><strong>', $txt['ftp_port'], ':&nbsp;</strong></label>
2155
						<input type="text" size="3" name="ftp_port" id="ftp_port" value="', $incontext['ftp']['port'], '">
2156
					</div>
2157
					<input type="text" size="30" name="ftp_server" id="ftp_server" value="', $incontext['ftp']['server'], '">
2158
					<div class="smalltext block">', $txt['ftp_server_info'], '</div>
2159
				</dd>
2160
				<dt>
2161
					<label for="ftp_username">', $txt['ftp_username'], ':</label>
2162
				</dt>
2163
				<dd>
2164
					<input type="text" size="30" name="ftp_username" id="ftp_username" value="', $incontext['ftp']['username'], '">
2165
					<div class="smalltext block">', $txt['ftp_username_info'], '</div>
2166
				</dd>
2167
				<dt>
2168
					<label for="ftp_password">', $txt['ftp_password'], ':</label>
2169
				</dt>
2170
				<dd>
2171
					<input type="password" size="30" name="ftp_password" id="ftp_password">
2172
					<div class="smalltext block">', $txt['ftp_password_info'], '</div>
2173
				</dd>
2174
				<dt>
2175
					<label for="ftp_path">', $txt['ftp_path'], ':</label>
2176
				</dt>
2177
				<dd>
2178
					<input type="text" size="30" name="ftp_path" id="ftp_path" value="', $incontext['ftp']['path'], '">
2179
					<div class="smalltext block">', $incontext['ftp']['path_msg'], '</div>
2180
				</dd>
2181
			</dl>
2182
			<div class="righttext buttons">
2183
				<input type="submit" value="', $txt['ftp_connect'], '" onclick="return submitThisOnce(this);" class="button">
2184
			</div>
2185
		</form>
2186
		<a href="', $incontext['form_url'], '">', $txt['error_message_click'], '</a> ', $txt['ftp_setup_again'];
2187
}
2188
2189
// Get the database settings prepared.
2190
function template_database_settings()
2191
{
2192
	global $incontext, $txt;
2193
2194
	echo '
2195
	<form action="', $incontext['form_url'], '" method="post">
2196
		<p>', $txt['db_settings_info'], '</p>';
2197
2198
	template_warning_divs();
2199
2200
	echo '
2201
		<dl class="settings">';
2202
2203
	// More than one database type?
2204
	if (count($incontext['supported_databases']) > 1)
2205
	{
2206
		echo '
2207
			<dt>
2208
				<label for="db_type_input">', $txt['db_settings_type'], ':</label>
2209
			</dt>
2210
			<dd>
2211
				<select name="db_type" id="db_type_input" onchange="toggleDBInput();">';
2212
2213
		foreach ($incontext['supported_databases'] as $key => $db)
2214
			echo '
2215
					<option value="', $key, '"', isset($_POST['db_type']) && $_POST['db_type'] == $key ? ' selected' : '', '>', $db['name'], '</option>';
2216
2217
		echo '
2218
				</select>
2219
				<div class="smalltext">', $txt['db_settings_type_info'], '</div>
2220
			</dd>';
2221
	}
2222
	else
2223
	{
2224
		echo '
2225
			<dd>
2226
				<input type="hidden" name="db_type" value="', $incontext['db']['type'], '">
2227
			</dd>';
2228
	}
2229
2230
	echo '
2231
			<dt>
2232
				<label for="db_server_input">', $txt['db_settings_server'], ':</label>
2233
			</dt>
2234
			<dd>
2235
				<input type="text" name="db_server" id="db_server_input" value="', $incontext['db']['server'], '" size="30">
2236
				<div class="smalltext">', $txt['db_settings_server_info'], '</div>
2237
			</dd>
2238
			<dt>
2239
				<label for="db_port_input">', $txt['db_settings_port'], ':</label>
2240
			</dt>
2241
			<dd>
2242
				<input type="text" name="db_port" id="db_port_input" value="', $incontext['db']['port'], '">
2243
				<div class="smalltext">', $txt['db_settings_port_info'], '</div>
2244
			</dd>
2245
			<dt>
2246
				<label for="db_user_input">', $txt['db_settings_username'], ':</label>
2247
			</dt>
2248
			<dd>
2249
				<input type="text" name="db_user" id="db_user_input" value="', $incontext['db']['user'], '" size="30">
2250
				<div class="smalltext">', $txt['db_settings_username_info'], '</div>
2251
			</dd>
2252
			<dt>
2253
				<label for="db_passwd_input">', $txt['db_settings_password'], ':</label>
2254
			</dt>
2255
			<dd>
2256
				<input type="password" name="db_passwd" id="db_passwd_input" value="', $incontext['db']['pass'], '" size="30">
2257
				<div class="smalltext">', $txt['db_settings_password_info'], '</div>
2258
			</dd>
2259
			<dt>
2260
				<label for="db_name_input">', $txt['db_settings_database'], ':</label>
2261
			</dt>
2262
			<dd>
2263
				<input type="text" name="db_name" id="db_name_input" value="', empty($incontext['db']['name']) ? 'smf' : $incontext['db']['name'], '" size="30">
2264
				<div class="smalltext">
2265
					', $txt['db_settings_database_info'], '
2266
					<span id="db_name_info_warning">', $txt['db_settings_database_info_note'], '</span>
2267
				</div>
2268
			</dd>
2269
			<dt>
2270
				<label for="db_prefix_input">', $txt['db_settings_prefix'], ':</label>
2271
			</dt>
2272
			<dd>
2273
				<input type="text" name="db_prefix" id="db_prefix_input" value="', $incontext['db']['prefix'], '" size="30">
2274
				<div class="smalltext">', $txt['db_settings_prefix_info'], '</div>
2275
			</dd>
2276
		</dl>';
2277
2278
	// Toggles a warning related to db names in PostgreSQL
2279
	echo '
2280
		<script>
2281
			function toggleDBInput()
2282
			{
2283
				if (document.getElementById(\'db_type_input\').value == \'postgresql\')
2284
					document.getElementById(\'db_name_info_warning\').classList.add(\'hidden\');
2285
				else
2286
					document.getElementById(\'db_name_info_warning\').classList.remove(\'hidden\');
2287
			}
2288
			toggleDBInput();
2289
		</script>';
2290
}
2291
2292
// Stick in their forum settings.
2293
function template_forum_settings()
2294
{
2295
	global $incontext, $txt;
2296
2297
	echo '
2298
	<form action="', $incontext['form_url'], '" method="post">
2299
		<h3>', $txt['install_settings_info'], '</h3>';
2300
2301
	template_warning_divs();
2302
2303
	echo '
2304
		<dl class="settings">
2305
			<dt>
2306
				<label for="mbname_input">', $txt['install_settings_name'], ':</label>
2307
			</dt>
2308
			<dd>
2309
				<input type="text" name="mbname" id="mbname_input" value="', $txt['install_settings_name_default'], '" size="65">
2310
				<div class="smalltext">', $txt['install_settings_name_info'], '</div>
2311
			</dd>
2312
			<dt>
2313
				<label for="boardurl_input">', $txt['install_settings_url'], ':</label>
2314
			</dt>
2315
			<dd>
2316
				<input type="text" name="boardurl" id="boardurl_input" value="', $incontext['detected_url'], '" size="65">
2317
				<div class="smalltext">', $txt['install_settings_url_info'], '</div>
2318
			</dd>
2319
			<dt>
2320
				<label for="reg_mode">', $txt['install_settings_reg_mode'], ':</label>
2321
			</dt>
2322
			<dd>
2323
				<select name="reg_mode" id="reg_mode">
2324
					<optgroup label="', $txt['install_settings_reg_modes'], ':">
2325
						<option value="0" selected>', $txt['install_settings_reg_immediate'], '</option>
2326
						<option value="1">', $txt['install_settings_reg_email'], '</option>
2327
						<option value="2">', $txt['install_settings_reg_admin'], '</option>
2328
						<option value="3">', $txt['install_settings_reg_disabled'], '</option>
2329
					</optgroup>
2330
				</select>
2331
				<div class="smalltext">', $txt['install_settings_reg_mode_info'], '</div>
2332
			</dd>
2333
			<dt>', $txt['install_settings_compress'], ':</dt>
2334
			<dd>
2335
				<input type="checkbox" name="compress" id="compress_check" checked>
2336
				<label for="compress_check">', $txt['install_settings_compress_title'], '</label>
2337
				<div class="smalltext">', $txt['install_settings_compress_info'], '</div>
2338
			</dd>
2339
			<dt>', $txt['install_settings_dbsession'], ':</dt>
2340
			<dd>
2341
				<input type="checkbox" name="dbsession" id="dbsession_check" checked>
2342
				<label for="dbsession_check">', $txt['install_settings_dbsession_title'], '</label>
2343
				<div class="smalltext">', $incontext['test_dbsession'] ? $txt['install_settings_dbsession_info1'] : $txt['install_settings_dbsession_info2'], '</div>
2344
			</dd>
2345
			<dt>', $txt['install_settings_utf8'], ':</dt>
2346
			<dd>
2347
				<input type="checkbox" name="utf8" id="utf8_check"', $incontext['utf8_default'] ? ' checked' : '', '', $incontext['utf8_required'] ? ' disabled' : '', '>
2348
				<label for="utf8_check">', $txt['install_settings_utf8_title'], '</label>
2349
				<div class="smalltext">', $txt['install_settings_utf8_info'], '</div>
2350
			</dd>
2351
			<dt>', $txt['install_settings_stats'], ':</dt>
2352
			<dd>
2353
				<input type="checkbox" name="stats" id="stats_check" checked="checked">
2354
				<label for="stats_check">', $txt['install_settings_stats_title'], '</label>
2355
				<div class="smalltext">', $txt['install_settings_stats_info'], '</div>
2356
			</dd>
2357
			<dt>', $txt['force_ssl'], ':</dt>
2358
			<dd>
2359
				<input type="checkbox" name="force_ssl" id="force_ssl"', $incontext['ssl_chkbx_checked'] ? ' checked' : '',
2360
					$incontext['ssl_chkbx_protected'] ? ' disabled' : '', '>
2361
				<label for="force_ssl">', $txt['force_ssl_label'], '</label>
2362
				<div class="smalltext"><strong>', $txt['force_ssl_info'], '</strong></div>
2363
			</dd>
2364
		</dl>';
2365
}
2366
2367
// Show results of the database population.
2368
function template_populate_database()
2369
{
2370
	global $incontext, $txt;
2371
2372
	echo '
2373
	<form action="', $incontext['form_url'], '" method="post">
2374
		<p>', !empty($incontext['was_refresh']) ? $txt['user_refresh_install_desc'] : $txt['db_populate_info'], '</p>';
2375
2376
	if (!empty($incontext['sql_results']))
2377
	{
2378
		echo '
2379
		<ul>
2380
			<li>', implode('</li><li>', $incontext['sql_results']), '</li>
2381
		</ul>';
2382
	}
2383
2384
	if (!empty($incontext['failures']))
2385
	{
2386
		echo '
2387
		<div class="red">', $txt['error_db_queries'], '</div>
2388
		<ul>';
2389
2390
		foreach ($incontext['failures'] as $line => $fail)
2391
			echo '
2392
			<li><strong>', $txt['error_db_queries_line'], $line + 1, ':</strong> ', nl2br(htmlspecialchars($fail)), '</li>';
2393
2394
		echo '
2395
		</ul>';
2396
	}
2397
2398
	echo '
2399
		<p>', $txt['db_populate_info2'], '</p>';
2400
2401
	template_warning_divs();
2402
2403
	echo '
2404
		<input type="hidden" name="pop_done" value="1">';
2405
}
2406
2407
// Create the admin account.
2408
function template_admin_account()
2409
{
2410
	global $incontext, $txt;
2411
2412
	echo '
2413
	<form action="', $incontext['form_url'], '" method="post">
2414
		<p>', $txt['user_settings_info'], '</p>';
2415
2416
	template_warning_divs();
2417
2418
	echo '
2419
		<dl class="settings">
2420
			<dt>
2421
				<label for="username">', $txt['user_settings_username'], ':</label>
2422
			</dt>
2423
			<dd>
2424
				<input type="text" name="username" id="username" value="', $incontext['username'], '" size="40">
2425
				<div class="smalltext">', $txt['user_settings_username_info'], '</div>
2426
			</dd>
2427
			<dt>
2428
				<label for="password1">', $txt['user_settings_password'], ':</label>
2429
			</dt>
2430
			<dd>
2431
				<input type="password" name="password1" id="password1" size="40">
2432
				<div class="smalltext">', $txt['user_settings_password_info'], '</div>
2433
			</dd>
2434
			<dt>
2435
				<label for="password2">', $txt['user_settings_again'], ':</label>
2436
			</dt>
2437
			<dd>
2438
				<input type="password" name="password2" id="password2" size="40">
2439
				<div class="smalltext">', $txt['user_settings_again_info'], '</div>
2440
			</dd>
2441
			<dt>
2442
				<label for="email">', $txt['user_settings_admin_email'], ':</label>
2443
			</dt>
2444
			<dd>
2445
				<input type="email" name="email" id="email" value="', $incontext['email'], '" size="40">
2446
				<div class="smalltext">', $txt['user_settings_admin_email_info'], '</div>
2447
			</dd>
2448
			<dt>
2449
				<label for="server_email">', $txt['user_settings_server_email'], ':</label>
2450
			</dt>
2451
			<dd>
2452
				<input type="text" name="server_email" id="server_email" value="', $incontext['server_email'], '" size="40">
2453
				<div class="smalltext">', $txt['user_settings_server_email_info'], '</div>
2454
			</dd>
2455
		</dl>';
2456
2457
	if ($incontext['require_db_confirm'])
2458
		echo '
2459
		<h2>', $txt['user_settings_database'], '</h2>
2460
		<p>', $txt['user_settings_database_info'], '</p>
2461
2462
		<div class="lefttext">
2463
			<input type="password" name="password3" size="30">
2464
		</div>';
2465
}
2466
2467
// Tell them it's done, and to delete.
2468
function template_delete_install()
2469
{
2470
	global $incontext, $installurl, $txt, $boardurl;
2471
2472
	echo '
2473
		<p>', $txt['congratulations_help'], '</p>';
2474
2475
	template_warning_divs();
2476
2477
	// Install directory still writable?
2478
	if ($incontext['dir_still_writable'])
2479
		echo '
2480
		<p><em>', $txt['still_writable'], '</em></p>';
2481
2482
	// Don't show the box if it's like 99% sure it won't work :P.
2483
	if ($incontext['probably_delete_install'])
2484
		echo '
2485
		<label>
2486
			<input type="checkbox" id="delete_self" onclick="doTheDelete();">
2487
			<strong>', $txt['delete_installer'], !isset($_SESSION['installer_temp_ftp']) ? ' ' . $txt['delete_installer_maybe'] : '', '</strong>
2488
		</label>
2489
		<script>
2490
			function doTheDelete()
2491
			{
2492
				var theCheck = document.getElementById ? document.getElementById("delete_self") : document.all.delete_self;
2493
				var tempImage = new Image();
2494
2495
				tempImage.src = "', $installurl, '?delete=1&ts_" + (new Date().getTime());
2496
				tempImage.width = 0;
2497
				theCheck.disabled = true;
2498
			}
2499
		</script>';
2500
2501
	echo '
2502
		<p>', sprintf($txt['go_to_your_forum'], $boardurl . '/index.php'), '</p>
2503
		<br>
2504
		', $txt['good_luck'];
2505
}
2506
2507
?>