forked from SimpleMachines/SMF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upgrade.php
4869 lines (4155 loc) · 165 KB
/
upgrade.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines http://www.simplemachines.org
* @copyright 2018 Simple Machines and individual contributors
* @license http://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.1 Beta 4
*/
// Version information...
define('SMF_VERSION', '2.1 Beta 4');
define('SMF_LANG_VERSION', '2.1 Beta 4');
/**
* The minimum required PHP version.
* @var string
*/
$GLOBALS['required_php_version'] = '5.4.0';
/**
* A list of supported database systems.
* @var array
*/
$databases = array(
'mysql' => array(
'name' => 'MySQL',
'version' => '5.0.22',
'version_check' => 'global $db_connection; return min(mysqli_get_server_info($db_connection), mysqli_get_client_info());',
'utf8_support' => true,
'utf8_version' => '5.0.22',
'utf8_version_check' => 'global $db_connection; return mysqli_get_server_info($db_connection);',
'alter_support' => true,
),
'postgresql' => array(
'name' => 'PostgreSQL',
'version' => '9.2',
'version_check' => '$version = pg_version(); return $version[\'client\'];',
'always_has_db' => true,
),
);
/**
* The maximum time a single substep may take, in seconds.
* @var int
*/
$timeLimitThreshold = 3;
/**
* The current path to the upgrade.php file.
* @var string
*/
$upgrade_path = dirname(__FILE__);
/**
* The URL of the current page.
* @var string
*/
$upgradeurl = $_SERVER['PHP_SELF'];
/**
* Flag to disable the required administrator login.
* @var bool
*/
$disable_security = false;
/**
* The amount of seconds allowed between logins.
* If the first user to login is inactive for this amount of seconds, a second login is allowed.
* @var int
*/
$upcontext['inactive_timeout'] = 10;
// The helper is crucial. Include it first thing.
if (!file_exists($upgrade_path . '/upgrade-helper.php'))
die('upgrade-helper.php not found where it was expected: ' . $upgrade_path . '/upgrade-helper.php! Make sure you have uploaded ALL files from the upgrade package. The upgrader cannot continue.');
require_once($upgrade_path . '/upgrade-helper.php');
global $txt;
// Initialize everything and load the language files.
initialize_inputs();
load_lang_file();
// All the steps in detail.
// Number,Name,Function,Progress Weight.
$upcontext['steps'] = array(
0 => array(1, $txt['upgrade_step_login'], 'WelcomeLogin', 2),
1 => array(2, $txt['upgrade_step_options'], 'UpgradeOptions', 2),
2 => array(3, $txt['upgrade_step_backup'], 'BackupDatabase', 10),
3 => array(4, $txt['upgrade_step_database'], 'DatabaseChanges', 50),
4 => array(5, $txt['upgrade_step_convertutf'], 'ConvertUtf8', 20),
5 => array(6, $txt['upgrade_step_convertjson'], 'serialize_to_json', 10),
6 => array(7, $txt['upgrade_step_delete'], 'DeleteUpgrade', 1),
);
// Just to remember which one has files in it.
$upcontext['database_step'] = 3;
@set_time_limit(600);
if (!ini_get('safe_mode'))
{
ini_set('mysql.connect_timeout', -1);
ini_set('default_socket_timeout', 900);
}
// Clean the upgrade path if this is from the client.
if (!empty($_SERVER['argv']) && php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR']))
for ($i = 1; $i < $_SERVER['argc']; $i++)
{
if (preg_match('~^--path=(.+)$~', $_SERVER['argv'][$i], $match) != 0)
$upgrade_path = substr($match[1], -1) == '/' ? substr($match[1], 0, -1) : $match[1];
}
// Are we from the client?
if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR']))
{
$command_line = true;
$disable_security = true;
}
else
$command_line = false;
// Load this now just because we can.
require_once($upgrade_path . '/Settings.php');
// We don't use "-utf8" anymore... Tweak the entry that may have been loaded by Settings.php
if (isset($language))
$language = str_ireplace('-utf8', '', $language);
// Are we logged in?
if (isset($upgradeData))
{
$upcontext['user'] = json_decode(base64_decode($upgradeData), true);
// Check for sensible values.
if (empty($upcontext['user']['started']) || $upcontext['user']['started'] < time() - 86400)
$upcontext['user']['started'] = time();
if (empty($upcontext['user']['updated']) || $upcontext['user']['updated'] < time() - 86400)
$upcontext['user']['updated'] = 0;
$upcontext['started'] = $upcontext['user']['started'];
$upcontext['updated'] = $upcontext['user']['updated'];
$is_debug = !empty($upcontext['user']['debug']) ? true : false;
}
// Nothing sensible?
if (empty($upcontext['updated']))
{
$upcontext['started'] = time();
$upcontext['updated'] = 0;
$upcontext['user'] = array(
'id' => 0,
'name' => 'Guest',
'pass' => 0,
'started' => $upcontext['started'],
'updated' => $upcontext['updated'],
);
}
// Load up some essential data...
loadEssentialData();
// Are we going to be mimic'ing SSI at this point?
if (isset($_GET['ssi']))
{
require_once($sourcedir . '/Errors.php');
require_once($sourcedir . '/Logging.php');
require_once($sourcedir . '/Load.php');
require_once($sourcedir . '/Security.php');
require_once($sourcedir . '/Subs-Package.php');
// SMF isn't started up properly, but loadUserSettings calls our cookies.
if (!isset($smcFunc['json_encode']))
{
$smcFunc['json_encode'] = 'json_encode';
$smcFunc['json_decode'] = 'smf_json_decode';
}
loadUserSettings();
loadPermissions();
}
// Include our helper functions.
require_once($sourcedir . '/Subs.php');
require_once($sourcedir . '/LogInOut.php');
// This only exists if we're on SMF ;)
if (isset($modSettings['smfVersion']))
{
$request = $smcFunc['db_query']('', '
SELECT variable, value
FROM {db_prefix}themes
WHERE id_theme = {int:id_theme}
AND variable IN ({string:theme_url}, {string:theme_dir}, {string:images_url})',
array(
'id_theme' => 1,
'theme_url' => 'theme_url',
'theme_dir' => 'theme_dir',
'images_url' => 'images_url',
'db_error_skip' => true,
)
);
while ($row = $smcFunc['db_fetch_assoc']($request))
$modSettings[$row['variable']] = $row['value'];
$smcFunc['db_free_result']($request);
}
if (!isset($modSettings['theme_url']))
{
$modSettings['theme_dir'] = $boarddir . '/Themes/default';
$modSettings['theme_url'] = 'Themes/default';
$modSettings['images_url'] = 'Themes/default/images';
}
if (!isset($settings['default_theme_url']))
$settings['default_theme_url'] = $modSettings['theme_url'];
if (!isset($settings['default_theme_dir']))
$settings['default_theme_dir'] = $modSettings['theme_dir'];
$upcontext['is_large_forum'] = (empty($modSettings['smfVersion']) || $modSettings['smfVersion'] <= '1.1 RC1') && !empty($modSettings['totalMessages']) && $modSettings['totalMessages'] > 75000;
// Default title...
$upcontext['page_title'] = 'Updating Your SMF Installation!';
// Have we got tracking data - if so use it (It will be clean!)
if (isset($_GET['data']))
{
global $is_debug;
$upcontext['upgrade_status'] = json_decode(base64_decode($_GET['data']), true);
$upcontext['current_step'] = $upcontext['upgrade_status']['curstep'];
$upcontext['language'] = $upcontext['upgrade_status']['lang'];
$upcontext['rid'] = $upcontext['upgrade_status']['rid'];
$support_js = $upcontext['upgrade_status']['js'];
// Only set this if the upgrader status says so.
if (empty($is_debug))
$is_debug = $upcontext['upgrade_status']['debug'];
// Load the language.
if (file_exists($modSettings['theme_dir'] . '/languages/Install.' . $upcontext['language'] . '.php'))
require_once($modSettings['theme_dir'] . '/languages/Install.' . $upcontext['language'] . '.php');
}
// Set the defaults.
else
{
$upcontext['current_step'] = 0;
$upcontext['rid'] = mt_rand(0, 5000);
$upcontext['upgrade_status'] = array(
'curstep' => 0,
'lang' => isset($_GET['lang']) ? $_GET['lang'] : basename($language, '.lng'),
'rid' => $upcontext['rid'],
'pass' => 0,
'debug' => 0,
'js' => 0,
);
$upcontext['language'] = $upcontext['upgrade_status']['lang'];
}
// If this isn't the first stage see whether they are logging in and resuming.
if ($upcontext['current_step'] != 0 || !empty($upcontext['user']['step']))
checkLogin();
if ($command_line)
cmdStep0();
// Don't error if we're using xml.
if (isset($_GET['xml']))
$upcontext['return_error'] = true;
// Loop through all the steps doing each one as required.
$upcontext['overall_percent'] = 0;
foreach ($upcontext['steps'] as $num => $step)
{
if ($num >= $upcontext['current_step'])
{
// The current weight of this step in terms of overall progress.
$upcontext['step_weight'] = $step[3];
// Make sure we reset the skip button.
$upcontext['skip'] = false;
// We cannot proceed if we're not logged in.
if ($num != 0 && !$disable_security && $upcontext['user']['pass'] != $upcontext['upgrade_status']['pass'])
{
$upcontext['steps'][0][2]();
break;
}
// Call the step and if it returns false that means pause!
if (function_exists($step[2]) && $step[2]() === false)
break;
elseif (function_exists($step[2])) {
//Start each new step with this unset, so the 'normal' template is called first
unset($_GET['xml']);
//Clear out warnings at the start of each step
unset($upcontext['custom_warning']);
$_GET['substep'] = 0;
$upcontext['current_step']++;
}
}
$upcontext['overall_percent'] += $step[3];
}
upgradeExit();
// Exit the upgrade script.
function upgradeExit($fallThrough = false)
{
global $upcontext, $upgradeurl, $sourcedir, $command_line, $is_debug, $txt;
// Save where we are...
if (!empty($upcontext['current_step']) && !empty($upcontext['user']['id']))
{
$upcontext['user']['step'] = $upcontext['current_step'];
$upcontext['user']['substep'] = $_GET['substep'];
$upcontext['user']['updated'] = time();
$upcontext['debug'] = $is_debug;
$upgradeData = base64_encode(json_encode($upcontext['user']));
require_once($sourcedir . '/Subs-Admin.php');
updateSettingsFile(array('upgradeData' => '"' . $upgradeData . '"'));
updateDbLastError(0);
}
// Handle the progress of the step, if any.
if (!empty($upcontext['step_progress']) && isset($upcontext['steps'][$upcontext['current_step']]))
{
$upcontext['step_progress'] = round($upcontext['step_progress'], 1);
$upcontext['overall_percent'] += $upcontext['step_progress'] * ($upcontext['steps'][$upcontext['current_step']][3] / 100);
}
$upcontext['overall_percent'] = (int) $upcontext['overall_percent'];
// We usually dump our templates out.
if (!$fallThrough)
{
// This should not happen my dear... HELP ME DEVELOPERS!!
if (!empty($command_line))
{
if (function_exists('debug_print_backtrace'))
debug_print_backtrace();
echo "\n" . 'Error: Unexpected call to use the ' . (isset($upcontext['sub_template']) ? $upcontext['sub_template'] : '') . ' template. Please copy and paste all the text above and visit the SMF support forum to tell the Developers that they\'ve made a boo boo; they\'ll get you up and running again.';
flush();
die();
}
if (!isset($_GET['xml']))
template_upgrade_above();
else
{
header('content-type: text/xml; charset=UTF-8');
// Sadly we need to retain the $_GET data thanks to the old upgrade scripts.
$upcontext['get_data'] = array();
foreach ($_GET as $k => $v)
{
if (substr($k, 0, 3) != 'amp' && !in_array($k, array('xml', 'substep', 'lang', 'data', 'step', 'filecount')))
{
$upcontext['get_data'][$k] = $v;
}
}
template_xml_above();
}
// Call the template.
if (isset($upcontext['sub_template']))
{
$upcontext['upgrade_status']['curstep'] = $upcontext['current_step'];
$upcontext['form_url'] = $upgradeurl . '?step=' . $upcontext['current_step'] . '&substep=' . $_GET['substep'] . '&data=' . base64_encode(json_encode($upcontext['upgrade_status']));
// Custom stuff to pass back?
if (!empty($upcontext['query_string']))
$upcontext['form_url'] .= $upcontext['query_string'];
// Call the appropriate subtemplate
if (is_callable('template_' . $upcontext['sub_template']))
call_user_func('template_' . $upcontext['sub_template']);
else
die('Upgrade aborted! Invalid template: template_' . $upcontext['sub_template']);
}
// Was there an error?
if (!empty($upcontext['forced_error_message']))
echo $upcontext['forced_error_message'];
// Show the footer.
if (!isset($_GET['xml']))
template_upgrade_below();
else
template_xml_below();
}
if (!empty($command_line) && $is_debug)
{
$active = time() - $upcontext['started'];
$hours = floor($active / 3600);
$minutes = intval(($active / 60) % 60);
$seconds = intval($active % 60);
$totalTime = '';
if ($hours > 0)
$totalTime .= $hours . ' hour' . ($hours > 1 ? 's' : '') . ' ';
if ($minutes > 0)
$totalTime .= $minutes . ' minute' . ($minutes > 1 ? 's' : '') . ' ';
if ($seconds > 0)
$totalTime .= $seconds . ' second' . ($seconds > 1 ? 's' : '') . ' ';
if (!empty($totalTime))
echo "\n" . '', $txt['upgrade_completed_time'], ' ' . $totalTime . "\n";
}
// Bang - gone!
die();
}
// Load the list of language files, and the current language file.
function load_lang_file()
{
global $txt, $incontext, $user_info;
$incontext['detected_languages'] = array();
// Make sure the languages directory actually exists.
if (file_exists(dirname(__FILE__) . '/Themes/default/languages'))
{
// Find all the "Install" language files in the directory.
$dir = dir(dirname(__FILE__) . '/Themes/default/languages');
while ($entry = $dir->read())
{
if (substr($entry, 0, 8) == 'Install.' && substr($entry, -4) == '.php')
$incontext['detected_languages'][$entry] = ucfirst(substr($entry, 8, strlen($entry) - 12));
}
$dir->close();
}
// Didn't find any, show an error message!
if (empty($incontext['detected_languages']))
{
// Let's not cache this message, eh?
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-cache');
echo '<!DOCTYPE html>
<html>
<head>
<title>SMF Upgrader: Error!</title>
</head>
<body style="font-family: sans-serif;"><div style="width: 600px;">
<h1 style="font-size: 14pt;">A critical error has occurred.</h1>
<p>This upgrader was unable to find the upgrader\'s language file or files. They should be found under:</p>
<div style="margin: 1ex; font-family: monospace; font-weight: bold;">', dirname($_SERVER['PHP_SELF']) != '/' ? dirname($_SERVER['PHP_SELF']) : '', '/Themes/default/languages</div>
<p>In some cases, FTP clients do not properly upload files with this many folders. Please double check to make sure you <span style="font-weight: 600;">have uploaded all the files in the distribution</span>.</p>
<p>If that doesn\'t help, please make sure this install.php file is in the same place as the Themes folder.</p>
<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>
</div></body>
</html>';
die;
}
// Override the language file?
if (isset($_GET['lang_file']))
$_SESSION['installer_temp_lang'] = $_GET['lang_file'];
elseif (isset($GLOBALS['HTTP_GET_VARS']['lang_file']))
$_SESSION['installer_temp_lang'] = $GLOBALS['HTTP_GET_VARS']['lang_file'];
// Make sure it exists, if it doesn't reset it.
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']))
{
// Use the first one...
list ($_SESSION['installer_temp_lang']) = array_keys($incontext['detected_languages']);
// If we have english and some other language, use the other language. We Americans hate english :P.
if ($_SESSION['installer_temp_lang'] == 'Install.english.php' && count($incontext['detected_languages']) > 1)
list (, $_SESSION['installer_temp_lang']) = array_keys($incontext['detected_languages']);
}
// And now include the actual language file itself.
require_once(dirname(__FILE__) . '/Themes/default/languages/' . $_SESSION['installer_temp_lang']);
// Which language did we load? Assume that he likes his language.
preg_match('~^Install\.(.+[^-utf8])\.php$~', $_SESSION['installer_temp_lang'], $matches);
$user_info['language'] = $matches[1];
}
// Used to direct the user to another location.
function redirectLocation($location, $addForm = true)
{
global $upgradeurl, $upcontext, $command_line;
// Command line users can't be redirected.
if ($command_line)
upgradeExit(true);
// Are we providing the core info?
if ($addForm)
{
$upcontext['upgrade_status']['curstep'] = $upcontext['current_step'];
$location = $upgradeurl . '?step=' . $upcontext['current_step'] . '&substep=' . $_GET['substep'] . '&data=' . base64_encode(json_encode($upcontext['upgrade_status'])) . $location;
}
while (@ob_end_clean());
header('location: ' . strtr($location, array('&' => '&')));
// Exit - saving status as we go.
upgradeExit(true);
}
// Load all essential data and connect to the DB as this is pre SSI.php
function loadEssentialData()
{
global $db_server, $db_user, $db_passwd, $db_name, $db_connection, $db_prefix, $db_character_set, $db_type;
global $modSettings, $sourcedir, $smcFunc;
error_reporting(E_ALL);
define('SMF', 1);
// Start the session.
if (@ini_get('session.save_handler') == 'user')
@ini_set('session.save_handler', 'files');
@session_start();
if (empty($smcFunc))
$smcFunc = array();
// We need this for authentication and some upgrade code
require_once($sourcedir . '/Subs-Auth.php');
require_once($sourcedir . '/Class-Package.php');
$smcFunc['strtolower'] = 'smf_strtolower';
// Initialize everything...
initialize_inputs();
// Get the database going!
if (empty($db_type) || $db_type == 'mysqli')
{
$db_type = 'mysql';
// If overriding $db_type, need to set its settings.php entry too
$changes = array();
$changes['db_type'] = '\'mysql\'';
require_once($sourcedir . '/Subs-Admin.php');
updateSettingsFile($changes);
}
if (file_exists($sourcedir . '/Subs-Db-' . $db_type . '.php'))
{
require_once($sourcedir . '/Subs-Db-' . $db_type . '.php');
// Make the connection...
if (empty($db_connection))
$db_connection = smf_db_initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, array('non_fatal' => true));
else
// If we've returned here, ping/reconnect to be safe
$smcFunc['db_ping']($db_connection);
// Oh dear god!!
if ($db_connection === null)
die('Unable to connect to database - please check username and password are correct in Settings.php');
if ($db_type == 'mysql' && isset($db_character_set) && preg_match('~^\w+$~', $db_character_set) === 1)
$smcFunc['db_query']('', '
SET NAMES {string:db_character_set}',
array(
'db_error_skip' => true,
'db_character_set' => $db_character_set,
)
);
// Load the modSettings data...
$request = $smcFunc['db_query']('', '
SELECT variable, value
FROM {db_prefix}settings',
array(
'db_error_skip' => true,
)
);
$modSettings = array();
while ($row = $smcFunc['db_fetch_assoc']($request))
$modSettings[$row['variable']] = $row['value'];
$smcFunc['db_free_result']($request);
}
else
{
return throw_error('Cannot find ' . $sourcedir . '/Subs-Db-' . $db_type . '.php' . '. Please check you have uploaded all source files and have the correct paths set.');
}
require_once($sourcedir . '/Subs.php');
// If they don't have the file, they're going to get a warning anyway so we won't need to clean request vars.
if (file_exists($sourcedir . '/QueryString.php') && php_version_check())
{
require_once($sourcedir . '/QueryString.php');
cleanRequest();
}
if (!isset($_GET['substep']))
$_GET['substep'] = 0;
}
function initialize_inputs()
{
global $start_time, $db_type;
$start_time = time();
umask(0);
ob_start();
// Better to upgrade cleanly and fall apart than to screw everything up if things take too long.
ignore_user_abort(true);
// This is really quite simple; if ?delete is on the URL, delete the upgrader...
if (isset($_GET['delete']))
{
@unlink(__FILE__);
// And the extra little files ;).
@unlink(dirname(__FILE__) . '/upgrade_1-0.sql');
@unlink(dirname(__FILE__) . '/upgrade_1-1.sql');
@unlink(dirname(__FILE__) . '/upgrade_2-0_' . $db_type . '.sql');
@unlink(dirname(__FILE__) . '/upgrade_2-1_' . $db_type . '.sql');
@unlink(dirname(__FILE__) . '/upgrade-helper.php');
$dh = opendir(dirname(__FILE__));
while ($file = readdir($dh))
{
if (preg_match('~upgrade_\d-\d_([A-Za-z])+\.sql~i', $file, $matches) && isset($matches[1]))
@unlink(dirname(__FILE__) . '/' . $file);
}
closedir($dh);
// Legacy files while we're at it. NOTE: We only touch files we KNOW shouldn't be there.
// 1.1 Sources files not in 2.0+
@unlink(dirname(__FILE__) . '/Sources/ModSettings.php');
// 1.1 Templates that don't exist any more (e.g. renamed)
@unlink(dirname(__FILE__) . '/Themes/default/Combat.template.php');
@unlink(dirname(__FILE__) . '/Themes/default/Modlog.template.php');
// 1.1 JS files were stored in the main theme folder, but in 2.0+ are in the scripts/ folder
@unlink(dirname(__FILE__) . '/Themes/default/fader.js');
@unlink(dirname(__FILE__) . '/Themes/default/script.js');
@unlink(dirname(__FILE__) . '/Themes/default/spellcheck.js');
@unlink(dirname(__FILE__) . '/Themes/default/xml_board.js');
@unlink(dirname(__FILE__) . '/Themes/default/xml_topic.js');
// 2.0 Sources files not in 2.1+
@unlink(dirname(__FILE__) . '/Sources/DumpDatabase.php');
@unlink(dirname(__FILE__) . '/Sources/LockTopic.php');
header('location: http://' . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT']) . dirname($_SERVER['PHP_SELF']) . '/Themes/default/images/blank.png');
exit;
}
// Something is causing this to happen, and it's annoying. Stop it.
$temp = 'upgrade_php?step';
while (strlen($temp) > 4)
{
if (isset($_GET[$temp]))
unset($_GET[$temp]);
$temp = substr($temp, 1);
}
// Force a step, defaulting to 0.
$_GET['step'] = (int) @$_GET['step'];
$_GET['substep'] = (int) @$_GET['substep'];
}
// Step 0 - Let's welcome them in and ask them to login!
function WelcomeLogin()
{
global $boarddir, $sourcedir, $modSettings, $cachedir, $upgradeurl, $upcontext;
global $smcFunc, $db_type, $databases, $boardurl;
// We global $txt here so that the language files can add to them. This variable is NOT unused.
global $txt;
$upcontext['sub_template'] = 'welcome_message';
// Check for some key files - one template, one language, and a new and an old source file.
$check = @file_exists($modSettings['theme_dir'] . '/index.template.php')
&& @file_exists($sourcedir . '/QueryString.php')
&& @file_exists($sourcedir . '/Subs-Db-' . $db_type . '.php')
&& @file_exists(dirname(__FILE__) . '/upgrade_2-1_' . $db_type . '.sql');
// Need legacy scripts?
if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] < 2.1)
$check &= @file_exists(dirname(__FILE__) . '/upgrade_2-0_' . $db_type . '.sql');
if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] < 2.0)
$check &= @file_exists(dirname(__FILE__) . '/upgrade_1-1.sql');
if (!isset($modSettings['smfVersion']) || $modSettings['smfVersion'] < 1.1)
$check &= @file_exists(dirname(__FILE__) . '/upgrade_1-0.sql');
// We don't need "-utf8" files anymore...
$upcontext['language'] = str_ireplace('-utf8', '', $upcontext['language']);
// This needs to exist!
if (!file_exists($modSettings['theme_dir'] . '/languages/Install.' . $upcontext['language'] . '.php'))
return throw_error('The upgrader could not find the "Install" language file for the forum default language, ' . $upcontext['language'] . '.<br><br>Please make certain you uploaded all the files included in the package, even the theme and language files for the default theme.<br> [<a href="' . $upgradeurl . '?lang=english">Try English</a>]');
else
require_once($modSettings['theme_dir'] . '/languages/Install.' . $upcontext['language'] . '.php');
if (!$check)
// Don't tell them what files exactly because it's a spot check - just like teachers don't tell which problems they are spot checking, that's dumb.
return throw_error('The upgrader was unable to find some crucial files.<br><br>Please make sure you uploaded all of the files included in the package, including the Themes, Sources, and other directories.');
// Do they meet the install requirements?
if (!php_version_check())
return throw_error('Warning! You do not appear to have a version of PHP installed on your webserver that meets SMF\'s minimum installations requirements.<br><br>Please ask your host to upgrade.');
if (!db_version_check())
return throw_error('Your ' . $databases[$db_type]['name'] . ' version does not meet the minimum requirements of SMF.<br><br>Please ask your host to upgrade.');
// Do some checks to make sure they have proper privileges
db_extend('packages');
// CREATE
$create = $smcFunc['db_create_table']('{db_prefix}priv_check', array(array('name' => 'id_test', 'type' => 'int', 'size' => 10, 'unsigned' => true, 'auto' => true)), array(array('columns' => array('id_test'), 'type' => 'primary')), array(), 'overwrite');
// ALTER
$alter = $smcFunc['db_add_column']('{db_prefix}priv_check', array('name' => 'txt', 'type' => 'varchar', 'size' => 4, 'null' => false, 'default' => ''));
// DROP
$drop = $smcFunc['db_drop_table']('{db_prefix}priv_check');
// Sorry... we need CREATE, ALTER and DROP
if (!$create || !$alter || !$drop)
return throw_error('The ' . $databases[$db_type]['name'] . ' user you have set in Settings.php does not have proper privileges.<br><br>Please ask your host to give this user the ALTER, CREATE, and DROP privileges.');
// Do a quick version spot check.
$temp = substr(@implode('', @file($boarddir . '/index.php')), 0, 4096);
preg_match('~\*\s@version\s+(.+)[\s]{2}~i', $temp, $match);
if (empty($match[1]) || (trim($match[1]) != SMF_VERSION))
return throw_error('The upgrader found some old or outdated files.<br><br>Please make certain you uploaded the new versions of all the files included in the package.');
// What absolutely needs to be writable?
$writable_files = array(
$boarddir . '/Settings.php',
$boarddir . '/Settings_bak.php',
);
// Only check for minified writable files if we have it enabled or not set.
if (!empty($modSettings['minimize_files']) || !isset($modSettings['minimize_files']))
$writable_files += array(
$modSettings['theme_dir'] . '/css/minified.css',
$modSettings['theme_dir'] . '/scripts/minified.js',
$modSettings['theme_dir'] . '/scripts/minified_deferred.js',
);
// Do we need to add this setting?
$need_settings_update = empty($modSettings['custom_avatar_dir']);
$custom_av_dir = !empty($modSettings['custom_avatar_dir']) ? $modSettings['custom_avatar_dir'] : $GLOBALS['boarddir'] . '/custom_avatar';
$custom_av_url = !empty($modSettings['custom_avatar_url']) ? $modSettings['custom_avatar_url'] : $boardurl . '/custom_avatar';
// This little fellow has to cooperate...
quickFileWritable($custom_av_dir);
// Are we good now?
if (!is_writable($custom_av_dir))
return throw_error(sprintf('The directory: %1$s has to be writable to continue the upgrade. Please make sure permissions are correctly set to allow this.', $custom_av_dir));
elseif ($need_settings_update)
{
if (!function_exists('cache_put_data'))
require_once($sourcedir . '/Load.php');
updateSettings(array('custom_avatar_dir' => $custom_av_dir));
updateSettings(array('custom_avatar_url' => $custom_av_url));
}
require_once($sourcedir . '/Security.php');
// Check the cache directory.
$cachedir_temp = empty($cachedir) ? $boarddir . '/cache' : $cachedir;
if (!file_exists($cachedir_temp))
@mkdir($cachedir_temp);
if (!file_exists($cachedir_temp))
return throw_error('The cache directory could not be found.<br><br>Please make sure you have a directory called "cache" in your forum directory before continuing.');
if (!file_exists($modSettings['theme_dir'] . '/languages/index.' . $upcontext['language'] . '.php') && !isset($modSettings['smfVersion']) && !isset($_GET['lang']))
return throw_error('The upgrader was unable to find language files for the language specified in Settings.php.<br>SMF will not work without the primary language files installed.<br><br>Please either install them, or <a href="' . $upgradeurl . '?step=0;lang=english">use english instead</a>.');
elseif (!isset($_GET['skiplang']))
{
$temp = substr(@implode('', @file($modSettings['theme_dir'] . '/languages/index.' . $upcontext['language'] . '.php')), 0, 4096);
preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*index(?:[\s]{2}|\*/)~i', $temp, $match);
if (empty($match[1]) || $match[1] != SMF_LANG_VERSION)
return throw_error('The upgrader found some old or outdated language files, for the forum default language, ' . $upcontext['language'] . '.<br><br>Please make certain you uploaded the new versions of all the files included in the package, even the theme and language files for the default theme.<br> [<a href="' . $upgradeurl . '?skiplang">SKIP</a>] [<a href="' . $upgradeurl . '?lang=english">Try English</a>]');
}
if (!makeFilesWritable($writable_files))
return false;
// Check agreement.txt. (it may not exist, in which case $boarddir must be writable.)
if (isset($modSettings['agreement']) && (!is_writable($boarddir) || file_exists($boarddir . '/agreement.txt')) && !is_writable($boarddir . '/agreement.txt'))
return throw_error('The upgrader was unable to obtain write access to agreement.txt.<br><br>If you are using a linux or unix based server, please ensure that the file is chmod\'d to 777, or if it does not exist that the directory this upgrader is in is 777.<br>If your server is running Windows, please ensure that the internet guest account has the proper permissions on it or its folder.');
// Upgrade the agreement.
elseif (isset($modSettings['agreement']))
{
$fp = fopen($boarddir . '/agreement.txt', 'w');
fwrite($fp, $modSettings['agreement']);
fclose($fp);
}
// We're going to check that their board dir setting is right in case they've been moving stuff around.
if (strtr($boarddir, array('/' => '', '\\' => '')) != strtr(dirname(__FILE__), array('/' => '', '\\' => '')))
$upcontext['warning'] = '
It looks as if your board directory settings <em>might</em> be incorrect. Your board directory is currently set to "' . $boarddir . '" but should probably be "' . dirname(__FILE__) . '". Settings.php currently lists your paths as:<br>
<ul>
<li>Board Directory: ' . $boarddir . '</li>
<li>Source Directory: ' . $boarddir . '</li>
<li>Cache Directory: ' . $cachedir_temp . '</li>
</ul>
If these seem incorrect please open Settings.php in a text editor before proceeding with this upgrade. If they are incorrect due to you moving your forum to a new location please download and execute the <a href="https://download.simplemachines.org/?tools">Repair Settings</a> tool from the Simple Machines website before continuing.';
// Confirm mbstring is loaded...
if (!extension_loaded('mbstring'))
return throw_error($txt['install_no_mbstring']);
// Check for https stream support.
$supported_streams = stream_get_wrappers();
if (!in_array('https', $supported_streams))
$upcontext['custom_warning'] = $txt['install_no_https'];
// Either we're logged in or we're going to present the login.
if (checkLogin())
return true;
$upcontext += createToken('login');
return false;
}
// Step 0.5: Does the login work?
function checkLogin()
{
global $modSettings, $upcontext, $disable_security;
global $smcFunc, $db_type, $support_js;
// Don't bother if the security is disabled.
if ($disable_security)
return true;
// Are we trying to login?
if (isset($_POST['contbutt']) && (!empty($_POST['user'])))
{
// If we've disabled security pick a suitable name!
if (empty($_POST['user']))
$_POST['user'] = 'Administrator';
// Before 2.0 these column names were different!
$oldDB = false;
if (empty($db_type) || $db_type == 'mysql')
{
$request = $smcFunc['db_query']('', '
SHOW COLUMNS
FROM {db_prefix}members
LIKE {string:member_name}',
array(
'member_name' => 'memberName',
'db_error_skip' => true,
)
);
if ($smcFunc['db_num_rows']($request) != 0)
$oldDB = true;
$smcFunc['db_free_result']($request);
}
// Get what we believe to be their details.
if (!$disable_security)
{
if ($oldDB)
$request = $smcFunc['db_query']('', '
SELECT id_member, memberName AS member_name, passwd, id_group,
additionalGroups AS additional_groups, lngfile
FROM {db_prefix}members
WHERE memberName = {string:member_name}',
array(
'member_name' => $_POST['user'],
'db_error_skip' => true,
)
);
else
$request = $smcFunc['db_query']('', '
SELECT id_member, member_name, passwd, id_group, additional_groups, lngfile
FROM {db_prefix}members
WHERE member_name = {string:member_name}',
array(
'member_name' => $_POST['user'],
'db_error_skip' => true,
)
);
if ($smcFunc['db_num_rows']($request) != 0)
{
list ($id_member, $name, $password, $id_group, $addGroups, $user_language) = $smcFunc['db_fetch_row']($request);
$groups = explode(',', $addGroups);
$groups[] = $id_group;
foreach ($groups as $k => $v)
$groups[$k] = (int) $v;
$sha_passwd = sha1(strtolower($name) . un_htmlspecialchars($_REQUEST['passwrd']));
// We don't use "-utf8" anymore...
$user_language = str_ireplace('-utf8', '', $user_language);
}
else
$upcontext['username_incorrect'] = true;
$smcFunc['db_free_result']($request);
}
$upcontext['username'] = $_POST['user'];
// Track whether javascript works!
if (!empty($_POST['js_works']))
{
$upcontext['upgrade_status']['js'] = 1;
$support_js = 1;
}
else
$support_js = 0;
// Note down the version we are coming from.
if (!empty($modSettings['smfVersion']) && empty($upcontext['user']['version']))
$upcontext['user']['version'] = $modSettings['smfVersion'];
// Didn't get anywhere?
if (!$disable_security && (empty($sha_passwd) || (!empty($password) ? $password : '') != $sha_passwd) && !hash_verify_password((!empty($name) ? $name : ''), $_REQUEST['passwrd'], (!empty($password) ? $password : '')) && empty($upcontext['username_incorrect']))
{
// MD5?
$md5pass = md5_hmac($_REQUEST['passwrd'], strtolower($_POST['user']));
if ($md5pass != $password)
{
$upcontext['password_failed'] = true;
// Disable the hashing this time.
$upcontext['disable_login_hashing'] = true;
}
}
if ((empty($upcontext['password_failed']) && !empty($name)) || $disable_security)
{
// Set the password.
if (!$disable_security)
{
// Do we actually have permission?
if (!in_array(1, $groups))
{
$request = $smcFunc['db_query']('', '
SELECT permission
FROM {db_prefix}permissions
WHERE id_group IN ({array_int:groups})
AND permission = {string:admin_forum}',
array(
'groups' => $groups,
'admin_forum' => 'admin_forum',
'db_error_skip' => true,
)
);
if ($smcFunc['db_num_rows']($request) == 0)
return throw_error('You need to be an admin to perform an upgrade!');
$smcFunc['db_free_result']($request);
}
$upcontext['user']['id'] = $id_member;
$upcontext['user']['name'] = $name;
}
else
{
$upcontext['user']['id'] = 1;
$upcontext['user']['name'] = 'Administrator';
}
$upcontext['user']['pass'] = mt_rand(0, 60000);
// This basically is used to match the GET variables to Settings.php.
$upcontext['upgrade_status']['pass'] = $upcontext['user']['pass'];
// Set the language to that of the user?
if (isset($user_language) && $user_language != $upcontext['language'] && file_exists($modSettings['theme_dir'] . '/languages/index.' . basename($user_language, '.lng') . '.php'))
{
$user_language = basename($user_language, '.lng');
$temp = substr(@implode('', @file($modSettings['theme_dir'] . '/languages/index.' . $user_language . '.php')), 0, 4096);
preg_match('~(?://|/\*)\s*Version:\s+(.+?);\s*index(?:[\s]{2}|\*/)~i', $temp, $match);
if (empty($match[1]) || $match[1] != SMF_LANG_VERSION)
$upcontext['upgrade_options_warning'] = 'The language files for your selected language, ' . $user_language . ', have not been updated to the latest version. Upgrade will continue with the forum default, ' . $upcontext['language'] . '.';
elseif (!file_exists($modSettings['theme_dir'] . '/languages/Install.' . basename($user_language, '.lng') . '.php'))
$upcontext['upgrade_options_warning'] = 'The language files for your selected language, ' . $user_language . ', have not been uploaded/updated as the "Install" language file is missing. Upgrade will continue with the forum default, ' . $upcontext['language'] . '.';
else
{
// Set this as the new language.
$upcontext['language'] = $user_language;
$upcontext['upgrade_status']['lang'] = $upcontext['language'];
// Include the file.
require_once($modSettings['theme_dir'] . '/languages/Install.' . $user_language . '.php');
}