Completed
Pull Request — release-2.1 (#6323)
by Mathias
05:12
created

DeleteInstall()   D

Complexity

Conditions 21

Size

Total Lines 154
Code Lines 84

Duplication

Lines 0
Ratio 0 %

Importance

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

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 2020 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', '2020');
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.4.0';
28
29
// Don't have PHP support, do you?
30
// ><html dir="ltr"><head><title>Error!</title></head><body>Sorry, this installer requires PHP!<div style="display: none;">
31
32
// Let's pull in useful classes
33
if (!defined('SMF'))
34
	define('SMF', 1);
35
36
require_once('Sources/Class-Package.php');
37
38
// Database info.
39
$databases = array(
40
	'mysql' => array(
41
		'name' => 'MySQL',
42
		'version' => '5.0.22',
43
		'version_check' => 'return min(mysqli_get_server_info($db_connection), mysqli_get_client_info());',
44
		'supported' => function_exists('mysqli_connect'),
45
		'default_user' => 'mysql.default_user',
46
		'default_password' => 'mysql.default_password',
47
		'default_host' => 'mysql.default_host',
48
		'default_port' => 'mysql.default_port',
49
		'utf8_support' => function()
50
		{
51
			return true;
52
		},
53
		'utf8_version' => '5.0.22',
54
		'utf8_version_check' => 'return mysqli_get_server_info($db_connection);',
55
		'utf8_default' => true,
56
		'utf8_required' => true,
57
		'alter_support' => true,
58
		'validate_prefix' => function(&$value)
59
		{
60
			$value = preg_replace('~[^A-Za-z0-9_\$]~', '', $value);
61
			return true;
62
		},
63
	),
64
	'postgresql' => array(
65
		'name' => 'PostgreSQL',
66
		'version' => '9.4',
67
		'function_check' => 'pg_connect',
68
		'version_check' => '$request = pg_query(\'SELECT version()\'); list ($version) = pg_fetch_row($request); list($pgl, $version) = explode(" ", $version); return $version;',
69
		'supported' => function_exists('pg_connect'),
70
		'always_has_db' => true,
71
		'utf8_default' => true,
72
		'utf8_required' => true,
73
		'utf8_support' => function()
74
		{
75
			$request = pg_query('SHOW SERVER_ENCODING');
0 ignored issues
show
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
It seems like timezone_identifiers_list() can also be of type false; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

265
		if (!in_array($timezone_id, /** @scrutinizer ignore-type */ timezone_identifiers_list()))
Loading history...
266
		{
267
			$server_offset = @mktime(0, 0, 0, 1, 1, 1970);
268
			$timezone_id = timezone_name_from_abbr('', $server_offset, 0);
269
		}
270
271
		date_default_timezone_set($timezone_id);
272
	}
273
	header('X-Frame-Options: SAMEORIGIN');
274
	header('X-XSS-Protection: 1');
275
	header('X-Content-Type-Options: nosniff');
276
277
	// Force an integer step, defaulting to 0.
278
	$_GET['step'] = (int) @$_GET['step'];
279
}
280
281
// Load the list of language files, and the current language file.
282
function load_lang_file()
283
{
284
	global $incontext, $user_info, $txt;
285
286
	$incontext['detected_languages'] = array();
287
288
	// Make sure the languages directory actually exists.
289
	if (file_exists(dirname(__FILE__) . '/Themes/default/languages'))
290
	{
291
		// Find all the "Install" language files in the directory.
292
		$dir = dir(dirname(__FILE__) . '/Themes/default/languages');
293
		while ($entry = $dir->read())
294
		{
295
			if (substr($entry, 0, 8) == 'Install.' && substr($entry, -4) == '.php')
296
				$incontext['detected_languages'][$entry] = ucfirst(substr($entry, 8, strlen($entry) - 12));
297
		}
298
		$dir->close();
299
	}
300
301
	// Didn't find any, show an error message!
302
	if (empty($incontext['detected_languages']))
303
	{
304
		// Let's not cache this message, eh?
305
		header('expires: Mon, 26 Jul 1997 05:00:00 GMT');
306
		header('last-modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
307
		header('cache-control: no-cache');
308
309
		echo '<!DOCTYPE html>
310
<html>
311
	<head>
312
		<title>SMF Installer: Error!</title>
313
		<style>
314
			body {
315
				font-family: sans-serif;
316
				max-width: 700px; }
317
318
			h1 {
319
				font-size: 14pt; }
320
321
			.directory {
322
				margin: 0.3em;
323
				font-family: monospace;
324
				font-weight: bold; }
325
		</style>
326
	</head>
327
	<body>
328
		<h1>A critical error has occurred.</h1>
329
330
		<p>This installer was unable to find the installer\'s language file or files. They should be found under:</p>
331
332
		<div class="directory">', dirname($_SERVER['PHP_SELF']) != '/' ? dirname($_SERVER['PHP_SELF']) : '', '/Themes/default/languages</div>
333
334
		<p>In some cases, FTP clients do not properly upload files with this many folders. Please double check to make sure you <strong>have uploaded all the files in the distribution</strong>.</p>
335
		<p>If that doesn\'t help, please make sure this install.php file is in the same place as the Themes folder.</p>
336
		<p>If you continue to get this error message, feel free to <a href="https://support.simplemachines.org/">look to us for support</a>.</p>
337
	</div></body>
338
</html>';
339
		die;
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 $handle of fclose() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

595
			@fclose(/** @scrutinizer ignore-type */ $fp);
Loading history...
596
		}
597
		foreach ($extra_files as $file)
598
			@chmod(dirname(__FILE__) . (empty($file) ? '' : '/' . $file), 0777);
599
	}
600
601
	$failure = count($failed_files) >= 1;
602
603
	if (!isset($_SERVER))
604
		return !$failure;
605
606
	// Put the list into context.
607
	$incontext['failed_files'] = $failed_files;
608
609
	// It's not going to be possible to use FTP on windows to solve the problem...
610
	if ($failure && substr(__FILE__, 1, 2) == ':\\')
611
	{
612
		$incontext['error'] = $txt['error_windows_chmod'] . '
613
					<ul class="error_content">
614
						<li>' . implode('</li>
615
						<li>', $failed_files) . '</li>
616
					</ul>';
617
618
		return false;
619
	}
620
	// We're going to have to use... FTP!
621
	elseif ($failure)
622
	{
623
		// Load any session data we might have...
624
		if (!isset($_POST['ftp_username']) && isset($_SESSION['installer_temp_ftp']))
625
		{
626
			$_POST['ftp_server'] = $_SESSION['installer_temp_ftp']['server'];
627
			$_POST['ftp_port'] = $_SESSION['installer_temp_ftp']['port'];
628
			$_POST['ftp_username'] = $_SESSION['installer_temp_ftp']['username'];
629
			$_POST['ftp_password'] = $_SESSION['installer_temp_ftp']['password'];
630
			$_POST['ftp_path'] = $_SESSION['installer_temp_ftp']['path'];
631
		}
632
633
		$incontext['ftp_errors'] = array();
634
		require_once('Sources/Class-Package.php');
635
		if (isset($_POST['ftp_username']))
636
		{
637
			$ftp = new ftp_connection($_POST['ftp_server'], $_POST['ftp_port'], $_POST['ftp_username'], $_POST['ftp_password']);
638
639
			if ($ftp->error === false)
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));
0 ignored issues
show
Bug introduced by
It seems like file(dirname(__FILE__) ..... '_' . $type . '.sql') can also be of type false; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

1210
	$sql_lines = explode("\n", strtr(implode(' ', /** @scrutinizer ignore-type */ file(dirname(__FILE__) . '/install_' . DB_SCRIPT_VERSION . '_' . $type . '.sql')), $replaces));
Loading history...
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
	// Auto-detect local & global cookie settings
1295
	$url_parts = parse_url($boardurl);
1296
	if ($url_parts !== false)
1297
	{
1298
		unset($globalCookies, $globalCookiesDomain, $localCookies);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $globalCookiesDomain seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $globalCookies does not exist. Did you maybe mean $globalCookiesDomain?
Loading history...
Comprehensibility Best Practice introduced by
The variable $localCookies seems to be never defined.
Loading history...
1299
1300
		// Look for subdomain, if found, set globalCookie settings
1301
		// Don't bother looking if you have an ip address for host
1302
		if (!empty($url_parts['host']) && (filter_var($url_parts['host'], FILTER_VALIDATE_IP) === false))
1303
		{
1304
			// www isn't really a subdomain in this sense, so strip it out
1305
			$url_parts['host'] = str_ireplace('www.', '', $url_parts['host']);
1306
			$pos1 = strrpos($url_parts['host'], '.');
1307
			if ($pos1 !== false)
1308
			{
1309
				// 2nd period from the right indicates you have a subdomain
1310
				$pos2 = strrpos(substr($url_parts['host'], 0, $pos1 - 1), '.');
1311
				if ($pos2 !== false)
1312
				{
1313
					$globalCookies = '1';
1314
					$globalCookiesDomain = substr($url_parts['host'], $pos2 + 1);
1315
				}
1316
			}
1317
		}
1318
1319
		// Look for subfolder, if found, set localCookie
1320
		// Checking for len > 1 ensures you don't have just a slash...
1321
		if (!empty($url_parts['path']) && strlen($url_parts['path']) > 1)
1322
			$localCookies = '1';
1323
1324
		if (isset($globalCookies))
1325
			$newSettings[] = array('globalCookies', $globalCookies);
1326
		if (isset($globalCookiesDomain))
1327
			$newSettings[] = array('globalCookiesDomain', $globalCookiesDomain);
1328
		if (isset($localCookies))
1329
			$newSettings[] = array('localCookies', $localCookies);
1330
	}
1331
1332
	// Are we allowing stat collection?
1333
	if (!empty($_POST['stats']) && substr($boardurl, 0, 16) != 'http://localhost' && empty($modSettings['allow_sm_stats']) && empty($modSettings['enable_sm_stats']))
1334
	{
1335
		$incontext['allow_sm_stats'] = true;
1336
1337
		// Attempt to register the site etc.
1338
		$fp = @fsockopen('www.simplemachines.org', 80, $errno, $errstr);
1339
		if ($fp)
0 ignored issues
show
introduced by
$fp is of type false|resource, thus it always evaluated to false.
Loading history...
1340
		{
1341
			$out = 'GET /smf/stats/register_stats.php?site=' . base64_encode($boardurl) . ' HTTP/1.1' . "\r\n";
1342
			$out .= 'Host: www.simplemachines.org' . "\r\n";
1343
			$out .= 'Connection: Close' . "\r\n\r\n";
1344
			fwrite($fp, $out);
1345
1346
			$return_data = '';
1347
			while (!feof($fp))
1348
				$return_data .= fgets($fp, 128);
1349
1350
			fclose($fp);
1351
1352
			// Get the unique site ID.
1353
			preg_match('~SITE-ID:\s(\w{10})~', $return_data, $ID);
1354
1355
			if (!empty($ID[1]))
1356
				$smcFunc['db_insert']('replace',
1357
					$db_prefix . 'settings',
1358
					array('variable' => 'string', 'value' => 'string'),
1359
					array(
1360
						array('sm_stats_key', $ID[1]),
1361
						array('enable_sm_stats', 1),
1362
					),
1363
					array('variable')
1364
				);
1365
		}
1366
	}
1367
	// Don't remove stat collection unless we unchecked the box for real, not from the loop.
1368
	elseif (empty($_POST['stats']) && empty($incontext['allow_sm_stats']))
1369
		$smcFunc['db_query']('', '
1370
			DELETE FROM {db_prefix}settings
1371
			WHERE variable = {string:enable_sm_stats}',
1372
			array(
1373
				'enable_sm_stats' => 'enable_sm_stats',
1374
				'db_error_skip' => true,
1375
			)
1376
		);
1377
1378
	// Are we enabling SSL?
1379
	if (!empty($_POST['force_ssl']))
1380
		$newSettings[] = array('force_ssl', 1);
1381
1382
	// Setting a timezone is required.
1383
	if (!isset($modSettings['default_timezone']) && function_exists('date_default_timezone_set'))
1384
	{
1385
		// Get PHP's default timezone, if set
1386
		$ini_tz = ini_get('date.timezone');
1387
		if (!empty($ini_tz))
1388
			$timezone_id = $ini_tz;
1389
		else
1390
			$timezone_id = '';
1391
1392
		// If date.timezone is unset, invalid, or just plain weird, make a best guess
1393
		if (!in_array($timezone_id, timezone_identifiers_list()))
0 ignored issues
show
Bug introduced by
It seems like timezone_identifiers_list() can also be of type false; however, parameter $haystack of in_array() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

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

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

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