aboutsummaryrefslogtreecommitdiffstats
path: root/phpBB/upgrade.php
blob: 7474a429594c9f93e124507054dc450841a07fa8 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
<?php
/***************************************************************************
*                                  upgrade.php
*                              -------------------
*     begin                : Wed Sep 05 2001
*     copyright            : (C) 2001 The phpBB Group
*     email                : support@phpbb.com
*
*     $Id$
*
****************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

if ( !defined('INSTALLING') )
{
	error_reporting  (E_ERROR | E_WARNING | E_PARSE); // This will NOT report uninitialized variables
	set_magic_quotes_runtime(0); // Disable magic_quotes_runtime

	//
	// If we are being called from the install script then we don't need these
	// as they are already included.
	//
	include('extension.inc');
	include('config.'.$phpEx);
	include('includes/constants.'.$phpEx);
	include('includes/functions.'.$phpEx);

	if( defined("PHPBB_INSTALLED") )
	{
		header("Location: index.$phpEx");
		exit;
	}
}

//
// Force the DB type to be MySQL
//
$dbms = 'mysql';

include('includes/db.'.$phpEx);
include('includes/bbcode.'.$phpEx);
include('includes/search.'.$phpEx);

set_time_limit(0); // Unlimited execution time

$months = array(
	'Jan' => 1,
	'Feb' => 2,
	'Mar' => 3,
	'Apr' => 4,
	'May' => 5,
	'Jun' => 6,
	'Jul' => 7,
	'Aug' => 8,
	'Sep' => 9,
	'Sept' => 9,
	'Oct' => 10,
	'Nov' => 11,
	'Dec' => 12
);


// ---------------
// Begin functions
//
function common_header()
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css">
<!--
/* Specifiy background images for selected styles
   This can't be done within the external style sheet as NS4 sees image paths relative to
   the page which called the style sheet (i.e. this page in the root phpBB directory)
   whereas all other browsers see image paths relative to the style sheet. Stupid NS again!
*/
TH			{ background-image: url(templates/subSilver/images/cellpic3.gif) }
TD.cat		{ background-image: url(templates/subSilver/images/cellpic1.gif) }
TD.rowpic	{ background-image: url(templates/subSilver/images/cellpic2.jpg); background-repeat: repeat-y }
td.icqback	{ background-image: url(templates/subSilver/images/icon_icq_add.gif); background-repeat: no-repeat }
TD.catHead,TD.catSides,TD.catLeft,TD.catRight,TD.catBottom { background-image: url(templates/subSilver/images/cellpic1.gif) }

font,th,td,p,body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 11pt }
a:link,a:active,a:visited { font-family: Verdana, Arial, Helvetica, sans-serif; color : #006699; font-size:11pt }
a:hover		{ font-family: Verdana, Arial, Helvetica, sans-serif;  text-decoration: underline; color : #DD6900; font-size:11pt }
hr	{ height: 0px; border: solid #D1D7DC 0px; border-top-width: 1px;}

.maintitle,h1,h2	{font-weight: bold; font-size: 22px; font-family: "Trebuchet MS",Verdana, Arial, Helvetica, sans-serif; text-decoration: none; line-height : 120%; color : #000000;}

.ok {color:green}

/* Import the fancy styles for IE only (NS4.x doesn't use the @import function) */
@import url("templates/subSilver/formIE.css"); 
-->
</style>
</head>
<body bgcolor="#FFFFFF" text="#000000" link="#006699" vlink="#5584AA">

<table width="100%" border="0" cellspacing="0" cellpadding="10" align="center"> 
	<tr>
		<td><table width="100%" border="0" cellspacing="0" cellpadding="0">
			<tr>
				<td><img src="templates/subSilver/images/logo_phpBB.gif" border="0" alt="Forum Home" vspace="1" /></td>
				<td align="center" width="100%" valign="middle"><span class="maintitle">Upgrading to phpBB 2.0</span></td>
			</tr>
		</table></td>
	</tr>
</table>

<br clear="all" />

<?
	return;
}

function common_footer()
{
?>

<br clear="all" />

</body>
</html>
<?
	return;
}

function query($sql, $errormsg)
{
	global $db;

	if ( !($result = $db->sql_query($sql)) )
	{
		print "<br><font color=\"red\">\n";
		print "$errormsg<br>";

		$sql_error = $db->sql_error();
		print $sql_error['code'] .": ". $sql_error['message']. "<br>\n";

		print "<pre>$sql</pre>";
		print "</font>\n";

		return FALSE;
	}
	else
	{
		return $result;
	}
}

function smiley_replace($text = "")
{
	global $db;

	static $search, $replace;

	// Did we get the smiley info in a previous call?
	if ( !is_array($search) )
	{
		$sql = "SELECT code, smile_url
			FROM smiles";
		$result = query($sql, "Unable to get list of smilies from the DB");

		$smilies = $db->sql_fetchrowset($result);
		@usort($smilies, 'smiley_sort');

		$search = array();
		$replace = array();
		for($i = 0; $i < count($smilies); $i++)
		{
			$search[] = '/<IMG SRC=".*?\/' . phpbb_preg_quote($smilies[$i]['smile_url'], '/') .'">/i';
			$replace[] = $smilies[$i]['code'];
		}
	}

	return ( $text != "" ) ? preg_replace($search, $replace, $text) : "";
	
}

function get_schema()
{
	global $table_prefix;

	$schemafile = file('db/schemas/mysql_schema.sql');
	$tabledata = 0;

	for($i=0; $i < count($schemafile); $i++)
	{
		$line = $schemafile[$i];

		if ( preg_match("/^CREATE TABLE (\w+)/i", $line, $matches) )
		{
			// Start of a new table definition, set some variables and go to the next line.
			$tabledata = 1;
			// Replace the 'phpbb_' prefix by the user defined prefix.
			$table = str_replace("phpbb_", $table_prefix, $matches[1]);
			$table_def[$table] = "CREATE TABLE $table (\n";
			continue;
		}

		if ( preg_match("/^\);/", $line) )
		{
			// End of the table definition
			// After this we will skip everything until the next 'CREATE' line
			$tabledata = 0;
			$table_def[$table] .= ")"; // We don't need the closing semicolon
		}

		if ( $tabledata == 1 )
		{
			// We are inside a table definition, parse this line.
			// Add the current line to the complete table definition:
			$table_def[$table] .= $line;
			if ( preg_match("/^\s*(\w+)\s+(\w+)\((\d+)\)(.*)$/", $line, $matches) )
			{
				// This is a column definition
				$field = $matches[1];
				$type = $matches[2];
				$size = $matches[3];

				preg_match("/DEFAULT (NULL|\'.*?\')[,\s](.*)$/i", $matches[4], $match);
				$default = $match[1];

				$notnull = ( preg_match("/NOT NULL/i", $matches[4]) ) ? 1 : 0;
				$auto_increment = ( preg_match("/auto_increment/i", $matches[4]) ) ? 1 : 0;

				$field_def[$table][$field] = array(
					'type' => $type,
					'size' => $size,
					'default' => $default,
					'notnull' => $notnull,
					'auto_increment' => $auto_increment
				);
			}
			
			if ( preg_match("/\s*PRIMARY\s+KEY\s*\((.*)\).*/", $line, $matches) )
			{
				// Primary key
				$key_def[$table]['PRIMARY'] = $matches[1];
			}
			else if ( preg_match("/\s*KEY\s+(\w+)\s*\((.*)\)/", $line, $matches) )
			{
				// Normal key
				$key_def[$table][$matches[1]] = $matches[2];
			}
			else if ( preg_match("/^\s*(\w+)\s*(.*?),?\s*$/", $line, $matches) )
			{
				// Column definition
				$create_def[$table][$matches[1]] = $matches[2];
			}
			else
			{
				// It's a bird! It's a plane! It's something we didn't expect ;(
			}
		}
	}

	$schema['field_def'] = $field_def;
	$schema['table_def'] = $table_def;
	$schema['create_def'] = $create_def;
	$schema['key_def'] = $key_def;

	return $schema;
}

function get_inserts()
{
	global $table_prefix;

	$insertfile = file("db/schemas/mysql_basic.sql");

	for($i = 0; $i < count($insertfile); $i++)
	{
		if ( preg_match("/(INSERT INTO (\w+)\s.*);/i", str_replace("phpbb_", $table_prefix, $insertfile[$i]), $matches) )
		{
			$returnvalue[$matches[2]][] = $matches[1];
		}
	}

	return $returnvalue;
}

function lock_tables($state, $tables= '')
{
	if ( $state == 1 )
	{
		if ( is_array($tables) )
		{
			$tables = join(' WRITE, ', $tables);
		}

		query("LOCK TABLES $tables WRITE", "Couldn't do: $sql");
	}
	else
	{
		query("UNLOCK TABLES", "Couldn't unlock all tables");
	}
}

function output_table_content($content)
{
	echo $content . "\n";

	return;
}

//
// Nathan's bbcode2 conversion routines
//
function bbdecode($message)
{
	// Undo [code]
	$code_start_html = "<!-- BBCode Start --><TABLE BORDER=0 ALIGN=CENTER WIDTH=85%><TR><TD><font size=-1>Code:</font><HR></TD></TR><TR><TD><FONT SIZE=-1><PRE>";
	$code_end_html = "</PRE></FONT></TD></TR><TR><TD><HR></TD></TR></TABLE><!-- BBCode End -->";
	$message = str_replace($code_start_html, "[code]", $message);
	$message = str_replace($code_end_html, "[/code]", $message);

	// Undo [quote]
	$quote_start_html = "<!-- BBCode Quote Start --><TABLE BORDER=0 ALIGN=CENTER WIDTH=85%><TR><TD><font size=-1>Quote:</font><HR></TD></TR><TR><TD><FONT SIZE=-1><BLOCKQUOTE>";
	$quote_end_html = "</BLOCKQUOTE></FONT></TD></TR><TR><TD><HR></TD></TR></TABLE><!-- BBCode Quote End -->";
	$message = str_replace($quote_start_html, "[quote]", $message);
	$message = str_replace($quote_end_html, "[/quote]", $message);

	// Undo [b] and [i]
	$message = preg_replace("#<!-- BBCode Start --><B>(.*?)</B><!-- BBCode End -->#s", "[b]\\1[/b]", $message);
	$message = preg_replace("#<!-- BBCode Start --><I>(.*?)</I><!-- BBCode End -->#s", "[i]\\1[/i]", $message);

	// Undo [url] (long form)
	$message = preg_replace("#<!-- BBCode u2 Start --><A HREF=\"([a-z]+?://)(.*?)\" TARGET=\"_blank\">(.*?)</A><!-- BBCode u2 End -->#s", "[url=\\1\\2]\\3[/url]", $message);

	// Undo [url] (short form)
	$message = preg_replace("#<!-- BBCode u1 Start --><A HREF=\"([a-z]+?://)(.*?)\" TARGET=\"_blank\">(.*?)</A><!-- BBCode u1 End -->#s", "[url]\\3[/url]", $message);

	// Undo [email]
	$message = preg_replace("#<!-- BBCode Start --><A HREF=\"mailto:(.*?)\">(.*?)</A><!-- BBCode End -->#s", "[email]\\1[/email]", $message);

	// Undo [img]
	$message = preg_replace("#<!-- BBCode Start --><IMG SRC=\"(.*?)\" BORDER=\"0\"><!-- BBCode End -->#s", "[img]\\1[/img]", $message);

	// Undo lists (unordered/ordered)

	// <li> tags:
	$message = str_replace("<!-- BBCode --><LI>", "[*]", $message);

	// [list] tags:
	$message = str_replace("<!-- BBCode ulist Start --><UL>", "[list]", $message);

	// [list=x] tags:
	$message = preg_replace("#<!-- BBCode olist Start --><OL TYPE=([A1])>#si", "[list=\\1]", $message);

	// [/list] tags:
	$message = str_replace("</UL><!-- BBCode ulist End -->", "[/list]", $message);
	$message = str_replace("</OL><!-- BBCode olist End -->", "[/list]", $message);

	return $message;
}

//
// Alternative for in_array() which is only available in PHP4
//
function inarray($needle, $haystack)
{ 
	for( $i = 0 ; $i < sizeof($haystack) ; $i++ )
	{ 
		if ( $haystack[$i] == $needle )
		{ 
			return true; 
		} 
	} 

	return false; 
}

function end_step($next)
{
	global $debug;

	print "<hr /><a href=\"$PHP_SELF?next=$next\">Next step: <b>$next</b></a><br /><br />\n";
}
//
// End functions
// -------------


//
// Start at the beginning if the user hasn't specified a specific starting point.
//
$next = ( isset($HTTP_GET_VARS['next']) ) ? $HTTP_GET_VARS['next'] : 'start';

// If debug is set we'll do all steps in one go.
$debug = 1;

// Parse the MySQL schema file into some arrays.
$schema = get_schema();

$table_def = $schema['table_def'];
$field_def = $schema['field_def'];
$key_def = $schema['key_def'];
$create_def = $schema['create_def'];

//
// Get mysql_basic data
//
$inserts = get_inserts();

//
// Get smiley data
//
smiley_replace();

common_header();

if ( !empty($next) )
{
	switch($next)
	{
		case 'start':
			end_step('initial_drops');

		case 'initial_drops':
			print " * Dropping sessions and themes tables :: ";
			flush();

			query("DROP TABLE sessions", "Couldn't drop table 'sessions'");
			query("DROP TABLE themes", "Couldn't drop table 'themes'");   

			print "<span class=\"ok\"><b>OK</b></span><br />\n";

			end_step('mod_old_tables');

		case 'mod_old_tables':
			$modtables = array(
				"banlist" => "banlist",
				"catagories" => "categories",
				"config" => "old_config",
				"forums" => "forums",
				"disallow" => "disallow",
				"posts" => "posts",
				"posts_text" => "posts_text",
				"priv_msgs" => "privmsgs",
				"ranks" => "ranks",
				"smiles" => "smilies",
				"topics" => "topics",
				"users" => "users",
				"words" => "words"
			);

			while( list($old, $new) = each($modtables) )
			{
				$result = query("SHOW INDEX FROM $old", "Couldn't get list of indices for table $old");

				while( $row = $db->sql_fetchrow($result) )
				{
					$index = $row['Key_name'];
					if ( $index != 'PRIMARY' )
					{
						query("ALTER TABLE $old DROP INDEX $index", "Couldn't DROP INDEX $old.$index");
					}
				}

				// Rename table
				$new = $table_prefix . $new;

				print " * Renaming '$old' to '$new' :: ";
				flush();
				query("ALTER TABLE $old RENAME $new", "Failed to rename $old to $new");
				print "<span class=\"ok\"><b>OK</b></span><br />\n";
				
			}
			end_step('create_tables');
			
		case 'create_tables':
			// Create array with tables in 'old' database
			$result = query('SHOW TABLES', "Couldn't get list of current tables");

			while( $table = $db->sql_fetchrow($result) )
			{
				$currenttables[] = $table[0];
			}
			
			// Check what tables we need to CREATE
			while( list($table, $definition) = each($table_def) )
			{
				if ( !inarray($table, $currenttables) )
				{
					print " * Creating $table :: ";

					query($definition, "Couldn't create table $table");

					print "<span class=\"ok\"><b>OK</b></span><br />\n";
				}
			}
			
			end_step('create_config');
			
		case 'create_config':
			print " * Inserting new values into new layout config table :: ";

			@reset($inserts);
			while( list($table, $inserts_table) = each($inserts) )
			{
				if ( $table == CONFIG_TABLE )
				{
					$per_pct = ceil( count($inserts_table) / 40 );
					$inc = 0;

					while( list($nr, $insert) = each($inserts_table) )
					{
						query($insert, "Couldn't insert value into config table");

						$inc++;
						if ( $inc == $per_pct )
						{
							print ".";
							flush();
							$inc = 0;
						}
					}
				}
			}

			print " <span class=\"ok\"><b>OK</b></span><br />\n";

			end_step('convert_config');
			
		case 'convert_config':
			print " * Converting configuration table :: ";

			$sql = "SELECT * 
				FROM $table_prefix" . "old_config";
			$result = query($sql, "Couldn't get info from old config table");

			$oldconfig = $db->sql_fetchrow($result);

			//
			// We don't need several original config types and two others
			// have changed name ... so take account of this.
			//
			$ignore_configs = array("selected", "admin_passwd", "override_themes", "allow_sig");
			$rename_configs = array(
				"email_from" => "board_email",
				"email_sig" => "board_email_sig"
			);

			while( list($name, $value) = each($oldconfig) )
			{
				if ( is_int($name) )
				{
					continue;
				}

				if ( !inarray($name, $ignore_configs) )
				{
					$name = ( !empty($rename_configs[$name]) ) ? $rename_configs[$name] : $name;

					$sql = "REPLACE INTO " . CONFIG_TABLE . " (config_name, config_value) 
						VALUES ('$name', '" . stripslashes($value) . "')";
					query($sql, "Couldn't update config table with values from old config table");
				}
			}
			
			print "<span class=\"ok\"><b>OK</b></span><br />\n";
			end_step('convert_ips');

		case 'convert_ips':
			$names = array( 
				POSTS_TABLE => array(
					'id' => 'post_id',
					'field' => 'poster_ip'
				), 
				PRIVMSGS_TABLE => array( 
					'id' => 'msg_id', 
					'field' => 'poster_ip'
				), 
				BANLIST_TABLE => array( 
					'id' => 'ban_id', 
					'field' => 'ban_ip'
				)
			);

			lock_tables(1, array(POSTS_TABLE, PRIVMSGS_TABLE, BANLIST_TABLE));

			$batchsize = 2000;
			while( list($table, $data_array) = each($names) )
			{
				$sql = "SELECT MAX(" . $data_array['id'] . ") AS max_id 
					FROM $table";
				$result = query($sql, "Couldn't obtain ip data from $table (" . $fields . ")");

				$row = $db->sql_fetchrow($result);

				$maxid = $row['max_id'];

				for($i = 0; $i <= $maxid; $i += $batchsize)
				{
					$batchstart = $i;
					$batchend = $i + $batchsize;

					$field_id = $data_array['id'];
					$field = $data_array['field'];

					print " * Converting IP format '" . $field . "' / '$table' ( $batchstart to $batchend ) :: ";
					flush();

					$sql = "SELECT $field_id, $field 
						FROM $table 
						WHERE $field_id 
							BETWEEN $batchstart 
								AND $batchend";
					$result = query($sql, "Couldn't obtain ip data from $table (" . $fields . ")");

					$per_pct = ceil( $db->sql_numrows($result) / 40 );
					$inc = 0;

					while( $row = $db->sql_fetchrow($result) )
					{
						$sql = "UPDATE $table 
							SET $field = '" . encode_ip($row[$field]) . "' 
							WHERE $field_id = " . $row[$field_id];
						query($sql, "Couldn't convert IP format of $field in $table with $field_id of " . $rowset[$field_id]);

						$inc++;
						if ( $inc == $per_pct )
						{
							print ".";
							flush();
							$inc = 0;
						}
					}

					print " <span class=\"ok\"><b>OK</b></span><br />\n";
				}
			}

			lock_tables(0);
			end_step('convert_dates');

		case 'convert_dates':
			$names = array(
				POSTS_TABLE => array('post_time'),
				TOPICS_TABLE => array('topic_time'), 
				PRIVMSGS_TABLE => array('msg_time')
			);

			lock_tables(1, array(POSTS_TABLE, TOPICS_TABLE, PRIVMSGS_TABLE));

			while( list($table, $fields) = each($names) )
			{
				print " * Converting date format of $fields[$i] in $table :: ";
				flush();

				for($i = 0; $i < count($fields); $i++)
				{
					$sql = "UPDATE $table 
						SET " . $fields[$i] . " = UNIX_TIMESTAMP(" . $fields[$i] . ")";
					query($sql, "Couldn't convert date format of $table(" . $fields[$i] . ")");
				}

				print "<span class=\"ok\"><b>OK</b></span><br />\n";
			}

			lock_tables(0);
			end_step('fix_addslashes');

		case 'fix_addslashes':
			$slashfields[TOPICS_TABLE] = array('topic_title');
			$slashfields[FORUMS_TABLE] = array('forum_desc', 'forum_name');
			$slashfields[CATEGORIES_TABLE] = array('cat_title');
			$slashfields[WORDS_TABLE] = array('word', 'replacement');
			$slashfields[RANKS_TABLE] = array('rank_title');
			$slashfields[DISALLOW_TABLE] = array('disallow_username');

			//convert smilies?
			$slashes = array(
				"\\'" => "'",
				"\\\"" => "\"",
				"\\\\" => "\\");
			$slashes = array(
				"\\'" => "'",
				"\\\"" => "\"",
				"\\\\" => "\\");

			lock_tables(1, array(TOPICS_TABLE, FORUMS_TABLE, CATEGORIES_TABLE, WORDS_TABLE, RANKS_TABLE, DISALLOW_TABLE, SMILIES_TABLE));

			while( list($table, $fields) = each($slashfields) )
			{
				print " * Removing slashes from $table table :: ";
				flush();

				while( list($nr, $field) = each($fields) )
				{
					@reset($slashes);
					while( list($search, $replace) = each($slashes) )
					{
						$sql = "UPDATE $table 
							SET $field = REPLACE($field, '" . addslashes($search) . "', '" . addslashes($replace) . "')";
						query($sql, "Couldn't remove extraneous slashes from the old data.");
					}
				}

				print "<span class=\"ok\"><b>OK</b></span><br />\n";
			}

			lock_tables(0);
			end_step('remove_topics');

		case 'remove_topics':
			print " * Removing posts with no corresponding topics :: ";
			flush();

			$sql = "SELECT p.post_id 
				FROM " . POSTS_TABLE . " p 
				LEFT JOIN " . TOPICS_TABLE . " t ON p.topic_id = t.topic_id  
				WHERE t.topic_id IS NULL";
			$result = query($sql, "Couldn't obtain list of deleted topics");
			
			$post_total = $db->sql_numrows($result);

			if ( $post_total )
			{
				$post_id_ary = array();
				while( $row = $db->sql_fetchrow($result) )
				{
					$post_id_ary[] = $row['post_id'];
				}

				$sql = "DELETE FROM " . POSTS_TABLE . "  
					WHERE post_id IN (" . implode(", ", $post_id_ary) . ")";
				query($sql, "Couldn't update posts to remove deleted user poster_id values");

				$sql = "DELETE FROM " . POSTS_TEXT_TABLE . "
					WHERE post_id IN (" . implode(", ", $post_id_ary) . ")";
				query($sql, "Couldn't update posts to remove deleted user poster_id values");
			}

			echo "<span class=\"ok\"><b>OK</b></span> ( Removed $post_total posts )<br />\n";
			end_step('convert_users');

		case 'convert_users':
			//
			// Completely remove old soft-deleted users
			//
			$sql = "DELETE FROM " . USERS_TABLE . " 
				WHERE user_level = -1";
			query($sql, "Couldn't delete old soft-deleted users");

			$sql = "SELECT COUNT(*) AS total, MAX(user_id) AS maxid 
				FROM " . USERS_TABLE;
			$result = query($sql, "Couldn't get max post_id.");

			$maxid = $db->sql_fetchrow($result);

			$totalposts = $maxid['total'];
			$maxid = $maxid['maxid'];

			$sql = "ALTER TABLE " . USERS_TABLE . " 
				ADD user_sig_bbcode_uid CHAR(10),
				MODIFY user_sig text";
			query($sql, "Couldn't add user_sig_bbcode_uid field to users table");

			$super_mods = array();
			$first_admin = -2;

			$batchsize = 1000;
			for($i = -1; $i <= $maxid; $i += $batchsize)
			{
				$batchstart = $i;
				$batchend = $i + $batchsize;
				
				print " * Converting Users ( $batchstart to $batchend ) :: ";
				flush();

				$sql = "SELECT * 
					FROM " . USERS_TABLE . " 
					WHERE user_id 
						BETWEEN $batchstart 
							AND $batchend";
				$result = query($sql, "Couldn't get ". USERS_TABLE .".user_id $batchstart to $batchend");

				// Array with user fields that we want to check for invalid data (to few characters)
				$checklength = array(
					'user_occ',
					'user_website',
					'user_email',
					'user_from',
					'user_intrest',
					'user_aim',
					'user_yim',
					'user_msnm');

				lock_tables(1, array(USERS_TABLE, GROUPS_TABLE, USER_GROUP_TABLE, POSTS_TABLE));

				$per_pct = ceil( $db->sql_numrows($result) / 40 );
				$inc = 0;

				while( $row = $db->sql_fetchrow($result) )
				{
					$sql = "INSERT INTO " . GROUPS_TABLE . " (group_name, group_description, group_single_user) 
						VALUES ('" . addslashes($row['username']) . "', 'Personal User', 1)";
					query($sql, "Wasn't able to insert user ".$row['user_id']." into table ".GROUPS_TABLE);

					$group_id = $db->sql_nextid();

					if ( $group_id != 0 )
					{
						$sql = "INSERT INTO " . USER_GROUP_TABLE . " (group_id, user_id, user_pending)	
							VALUES ($group_id, " . $row['user_id'] . ", 0)";
						query($sql, "Wasn't able to insert user ".$row['user_id']." into table ".USER_GROUP_TABLE);
					}
					else
					{
						print "Couldn't get insert ID for " . GROUPS_TABLE . " table<br>\n";
					}

					if ( is_int($row['user_regdate']) )
					{
						// We already converted this post to the new style BBcode, skip this post.
						continue;
					}

					//
					// Nathan's bbcode2 conversion
					//

					// undo 1.2.x encoding..
					$row['user_sig'] = bbdecode(stripslashes($row['user_sig']));
					$row['user_sig'] = undo_make_clickable($row['user_sig']);
					$row['user_sig'] = str_replace("<BR>", "\n", $row['user_sig']);

					// make a uid
					$uid = make_bbcode_uid();

					// do 2.x first-pass encoding..
					$row['user_sig'] = bbencode_first_pass($row['user_sig'], $uid);
					$row['user_sig'] = addslashes($row['user_sig']);

					// Check for invalid info like '-' and '?' for a lot of fields
					@reset($checklength);
					while($field = each($checklength))
					{
						$row[$field[1]] = strlen($row[$field[1]]) < 3 ? '' : $row[$field[1]];
					}

					preg_match('/(.*?) (\d{1,2}), (\d{4})/', $row['user_regdate'], $parts);
					$row['user_regdate'] = gmmktime(0, 0, 0, $months[$parts[1]], $parts[2], $parts[3]);

					$website = $row['user_website'];
					if ( substr(strtolower($website), 0, 7) != "http://" )
					{
						$website = "http://" . $website;
					}
					if( strtolower($website) == 'http://' )
					{
						$website = '';
					}
					$row['user_website'] = addslashes($website);
					
					$row['user_icq'] = (ereg("^[0-9]+$", $row['user_icq'])) ? $row['user_icq'] : '';
					reset($checklength);

					while($field = each($checklength))
					{
						if ( strlen($row[$field[1]]) < 3 )
						{
							$row[$field[1]] = '';
						}
						$row[$field[1]] = addslashes($row[$field[1]]);
					}
					
					//
					// Is user a super moderator?
					//
					if( $row['user_level'] == 3 )
					{
						$super_mods[] = $row['user_id'];
					}

					$row['user_level'] = ( $row['user_level'] == 4 ) ? ADMIN : USER;

					//
					// Used to define a 'practical' group moderator user_id
					// for super mods a little latter.
					//
					if( $first_admin == -2 && $row['user_level'] == ADMIN )
					{
						$first_admin = $row['user_id'];
					}

					$sql = "UPDATE " . USERS_TABLE . " 
						SET 
							user_sig = '" . $row['user_sig'] . "',
							user_sig_bbcode_uid = '$uid', 
							user_regdate = '" . $row['user_regdate'] . "',
							user_website = '" . $row['user_website'] . "',
							user_occ = '" . $row['user_occ'] . "',
							user_email = '" . $row['user_email'] . "',
							user_from = '" . $row['user_from'] . "',
							user_intrest = '" . $row['user_intrest'] . "', 
							user_aim = '" . $row['user_aim'] . "',
							user_yim = '" . $row['user_yim'] . "',
							user_msnm = '" . $row['user_msnm'] . "',
							user_level = '" . $row['user_level'] . "', 
							user_desmile = NOT(user_desmile), 
							user_bbcode = 1, 
							user_theme = 1 
						WHERE user_id = " . $row['user_id'];
					query($sql, "Couldn't update ".USERS_TABLE." table with new BBcode and regdate for user_id ".$row['user_id']);

					$inc++;
					if ( $inc == $per_pct )
					{
						print ".";
						flush();
						$inc = 0;
					}
				}

				print " <span class=\"ok\"><b>OK</b></span><br />\n";

				lock_tables(0);
			}

			//
			// Handle super-mods, create hidden group for them
			//
			// Iterate trough access table
			if( count($super_mods) && $first_admin != -2 )
			{
				print "\n<br />\n * Creating new group for super moderators :: ";
				flush();

				$sql = "INSERT INTO " . GROUPS_TABLE . " (group_type, group_name, group_description, group_moderator, group_single_user)
					VALUES (" . GROUP_HIDDEN . ", 'Super Moderators', 'Converted super moderators', $first_admin, 0)";
				$result = query($sql, "Couldn't create group for ".$row['forum_name']);

				$group_id = $db->sql_nextid();

				if ( $group_id <= 0 )
				{
					print "<font color=\"red\">Group creation failed. Aborting creation of groups...<br></font>\n";
					continue 2;
				}

				print "<span class=\"ok\"><b>OK</b></span><br />\n";

				print " * Updating auth_access for super moderator group :: ";
				flush();

				$sql = "SELECT forum_id 
					FROM " . FORUMS_TABLE;
				$result = query($sql, "Couldn't obtain forum_id list");

				while( $row = $db->sql_fetchrow($result) )
				{
					$sql = "INSERT INTO " . AUTH_ACCESS_TABLE . " (group_id, forum_id, auth_mod)
						VALUES ($group_id, " . $row['forum_id'] . ", 1)";
					$result_insert = query($sql, "Unable to set group auth access for super mods.");
				}

				for($i = 0; $i < count($super_mods); $i++)
				{
					$sql = "INSERT INTO " . USER_GROUP_TABLE . " (group_id, user_id, user_pending)
						VALUES ($group_id, " . $super_mods[$i] . ", 0)";
					query($sql, "Unable to add user_id $user_id to group_id $group_id (super mods)<br>\n");
				}
			
				print "<span class=\"ok\"><b>OK</b></span><br />\n";
			}

			end_step('convert_posts');

		case 'convert_posts':
			print " * Adding enable_sig field to " . POSTS_TABLE . " :: ";
			flush();
			$sql = "ALTER TABLE " . POSTS_TABLE . " 
				ADD enable_sig tinyint(1) DEFAULT '1' NOT NULL";
			$result = query($sql, "Couldn't add enable_sig field to " . POSTS_TABLE . ".");
			print "<span class=\"ok\"><b>OK</b></span><br />\n";
			
			print " * Adding enable_bbcode field to " . POSTS_TEXT_TABLE . " :: ";
			flush();
			$sql = "ALTER TABLE " . POSTS_TEXT_TABLE . "  
				ADD enable_bbcode tinyint(1) DEFAULT '1' NOT NULL";
			$result = query($sql, "Couldn't add enable_bbcode field to " . POSTS_TABLE . ".");
			print "<span class=\"ok\"><b>OK</b></span><br />\n";

			print " * Adding bbcode_uid field to " . POSTS_TEXT_TABLE . " :: ";
			flush();
			$sql = "ALTER TABLE " . POSTS_TEXT_TABLE . "  
				ADD bbcode_uid char(10) NOT NULL";
			$result = query($sql, "Couldn't add bbcode_uid field to " . POSTS_TABLE . ".");
			print "<span class=\"ok\"><b>OK</b></span><br />\n";
			
			print " * Adding post_edit_time field to " . POSTS_TABLE . " :: ";
			flush();
			$sql = "ALTER TABLE " . POSTS_TABLE . "  
				ADD post_edit_time int(11)";
			$result = query($sql, "Couldn't add post_edit_time field to " . POSTS_TABLE . ".");
			print "<span class=\"ok\"><b>OK</b></span><br />\n";

			print " * Adding post_edit_count field to " . POSTS_TABLE . " :: ";
			flush();
			$sql = "ALTER TABLE " . POSTS_TABLE . "  
				ADD post_edit_count smallint(5) UNSIGNED DEFAULT '0' NOT NULL";
			$result = query($sql, "Couldn't add post_edit_count field to " . POSTS_TABLE . ".");
			print "<span class=\"ok\"><b>OK</b></span><br />\n<br />\n";

			$sql = "SELECT COUNT(*) as total, MAX(post_id) as maxid 
				FROM " . POSTS_TEXT_TABLE;
			$result = query($sql, "Couldn't get max post_id.");

			$maxid = $db->sql_fetchrow($result);

			$totalposts = $maxid['total'];
			$maxid = $maxid['maxid'];

			$batchsize = 2000;
			for($i = 0; $i <= $maxid; $i += $batchsize)
			{
				$batchstart = $i + 1;
				$batchend = $i + $batchsize;
				
				print " * Converting BBcode ( $batchstart to $batchend ) :: ";
				flush();

				$sql = "SELECT * 
					FROM " . POSTS_TEXT_TABLE . "
					WHERE post_id 
						BETWEEN $batchstart 
							AND $batchend";
				$result = query($sql, "Couldn't get ". POSTS_TEXT_TABLE .".post_id $batchstart to $batchend");

				lock_tables(1, array(POSTS_TEXT_TABLE, POSTS_TABLE));

				$per_pct = ceil( $db->sql_numrows($result) / 40 );
				$inc = 0;

				while( $row = $db->sql_fetchrow($result) )
				{
					if ( $row['bbcode_uid'] != '' )
					{
						// We already converted this post to the new style BBcode, skip this post.
						continue;
					}

					//
					// Nathan's bbcode2 conversion
					//
					// undo 1.2.x encoding..
					$row['post_text'] = bbdecode(stripslashes($row['post_text']));
					$row['post_text'] = undo_make_clickable($row['post_text']);
					$row['post_text'] = str_replace("<BR>", "\n", $row['post_text']);

					// make a uid
					$uid = make_bbcode_uid();

					// do 2.x first-pass encoding..
					$row['post_text'] = smiley_replace($row['post_text']);
					$row['post_text'] = bbencode_first_pass($row['post_text'], $uid);
					$row['post_text'] = addslashes($row['post_text']);

					$edited_sql = "";
					if ( preg_match("/^(.*?)([\n]+<font size=\-1>\[ This message was .*?)$/s", $row['post_text'], $matches) )
					{
						$row['post_text'] = $matches[1];
						$edit_info = $matches[2];

						$edit_times = count(explode(" message ", $edit_info)) - 1; // Taken from example for substr_count in annotated PHP manual

						if ( preg_match("/^.* by: (.*?) on (....)-(..)-(..) (..):(..) \]<\/font>/s", $edit_info, $matches) )
						{
							$edited_user = $matches[1];
							$edited_time = gmmktime($matches[5], $matches[6], 0, $matches[3], $matches[4], $matches[2]);

							//
							// This isn't strictly correct since 2.0 won't include and edit
							// statement if the edit wasn't by the user who posted ...
							//
							$edited_sql = ", post_edit_time = $edited_time, post_edit_count = $edit_times";
						}
					}
	
					if ( preg_match("/^(.*?)\n-----------------\n.*$/is", $row['post_text'], $matches) )
					{
						$row['post_text'] = $matches[1];
						$enable_sig = 1;
					}
					else
					{
						$checksig = preg_replace('/\[addsig\]$/', '', $row['post_text']);
						$enable_sig = ( strlen($checksig) == strlen($row['post_text']) ) ? 0 : 1;
					}

					$sql = "UPDATE " . POSTS_TEXT_TABLE . " 
						SET post_text = '$checksig', bbcode_uid = '$uid'
						WHERE post_id = " . $row['post_id'];
					query($sql, "Couldn't update " . POSTS_TEXT_TABLE . " table with new BBcode for post_id :: " . $row['post_id']);

					$sql = "UPDATE " . POSTS_TABLE . " 
						SET enable_sig = $enable_sig" . $edited_sql . " 
						WHERE post_id = " . $row['post_id'];
					query($sql, "Couldn't update " . POSTS_TABLE . " table with signature status for post with post_id :: " . $row['post_id']);

					$inc++;
					if ( $inc == $per_pct )
					{
						print ".";
						flush();
						$inc = 0;
					}
				}

				print " <span class=\"ok\"><b>OK</b></span><br />\n";

				lock_tables(0);
			}

			print "<br />\n * Updating poster_id for deleted users :: ";
			flush();

			$sql = "SELECT DISTINCT p.post_id 
				FROM " . POSTS_TABLE . " p 
				LEFT JOIN " . USERS_TABLE . " u ON p.poster_id = u.user_id 
				WHERE u.user_id IS NULL";
			$result = query($sql, "Couldn't obtain list of deleted users");
			
			$users_removed = $db->sql_numrows($result);

			if ( $users_removed )
			{
				$post_id_ary = array();
				while( $row = $db->sql_fetchrow($result) )
				{
					$post_id_ary[] = $row['post_id'];
				}

				$sql = "UPDATE " . POSTS_TABLE . " 
					SET poster_id = " . ANONYMOUS . ", enable_sig = 0 
					WHERE post_id IN (" . implode(", ", $post_id_ary) . ")";
				query($sql, "Couldn't update posts to remove deleted user poster_id values");
			}

			print "<span class=\"ok\"><b>OK</b></span> ( Removed $users_removed non-existent user references )<br />\n";

			end_step('convert_privmsgs');

		case 'convert_privmsgs':
			$sql = "SELECT COUNT(*) as total, max(msg_id) as maxid 
				FROM " . PRIVMSGS_TABLE;
			$result = query($sql, "Couldn't get max privmsgs_id.");

			$maxid = $db->sql_fetchrow($result);

			$totalposts = $maxid['total'];
			$maxid = $maxid['maxid'];

			$sql = "ALTER TABLE " . PRIVMSGS_TABLE . " 
				ADD privmsgs_subject VARCHAR(255),
				ADD privmsgs_attach_sig TINYINT(1) DEFAULT 1";
			query($sql, "Couldn't add privmsgs_subject field to " . PRIVMSGS_TABLE . " table");

			$batchsize = 2000;
			for($i = 0; $i <= $maxid; $i += $batchsize)
			{
				$batchstart = $i + 1;
				$batchend = $i + $batchsize;
				
				print " * Converting Private Message ( $batchstart to $batchend ) :: ";
				flush();

				$sql = "SELECT * 
					FROM " . PRIVMSGS_TABLE . "
					WHERE msg_id 
						BETWEEN $batchstart 
							AND $batchend";
				$result = query($sql, "Couldn't get " . POSTS_TEXT_TABLE . " post_id $batchstart to $batchend");

				lock_tables(1, array(PRIVMSGS_TABLE, PRIVMSGS_TEXT_TABLE));

				$per_pct = ceil( $db->sql_numrows($result) / 40 );
				$inc = 0;

				while( $row = $db->sql_fetchrow($result) )
				{
					if ( $row['msg_text'] == NULL )
					{
						// We already converted this post to the new style BBcode, skip this post.
						continue;
					}
					//
					// Nathan's bbcode2 conversion
					//
					// undo 1.2.x encoding..
					$row['msg_text'] = bbdecode(stripslashes($row['msg_text']));
					$row['msg_text'] = undo_make_clickable($row['msg_text']);
					$row['msg_text'] = str_replace("<BR>", "\n", $row['msg_text']);

					// make a uid
					$uid = make_bbcode_uid();

					// do 2.x first-pass encoding..
					$row['msg_text'] = smiley_replace($row['msg_text']);
					$row['msg_text'] = bbencode_first_pass($row['msg_text'], $uid);
					
					$checksig = preg_replace('/\[addsig\]$/', '', $row['msg_text']);
					$enable_sig = (strlen($checksig) == strlen($row['msg_text'])) ? 0 : 1;

					if ( preg_match("/^(.*?)\n-----------------\n.*$/is", $checksig, $matches) )
					{
						$checksig = $matches[1];
						$enable_sig = 1;
					}

					$row['msg_text'] = $checksig;
					
					$row['msg_status'] = ($row['msg_status'] == 1) ? PRIVMSGS_READ_MAIL : PRIVMSGS_NEW_MAIL;

					// Subject contains first 60 characters of msg, remove any BBCode tags
					$subject = addslashes(strip_tags(substr($row['msg_text'], 0, 60)));
					$subject = preg_replace("/\[.*?\:(([a-z0-9]:)?)$uid.*?\]/si", "", $subject);
					
					$row['msg_text'] = addslashes($row['msg_text']);

					$sql = "INSERT INTO " . PRIVMSGS_TEXT_TABLE . " (privmsgs_text_id, privmsgs_bbcode_uid, privmsgs_text)
						VALUES ('" . $row['msg_id'] . "', '$uid', '" . $row['msg_text'] . "')";
					query($sql, "Couldn't insert PrivMsg text into " . PRIVMSGS_TEXT_TABLE . " table msg_id " . $row['msg_id']);

					$sql = "UPDATE " . PRIVMSGS_TABLE . " 
						SET msg_text = NULL, msg_status = " . $row['msg_status'] . ", privmsgs_subject = '$subject', privmsgs_attach_sig = $enable_sig
						WHERE msg_id = " . $row['msg_id'];
					query($sql, "Couldn't update " . PRIVMSGS_TABLE . " table for msg_id " . $row['post_id']);

					$inc++;
					if ( $inc == $per_pct )
					{
						print ".";
						flush();
						$inc = 0;
					}
				}

				print " <span class=\"ok\"><b>OK</b></span><br />\n";
			}

			lock_tables(0);
			end_step('convert_moderators');

		case 'convert_moderators';
			$sql = "SELECT * 
				FROM forum_mods";
			$result = query($sql, "Couldn't get list with all forum moderators");

			while( $row = $db->sql_fetchrow($result) )
			{
				// Check if this moderator and this forum still exist
				$sql = "SELECT NULL 
					FROM " . USERS_TABLE . ", " . FORUMS_TABLE . " 
					WHERE user_id = " . $row['user_id'] . " 
						AND forum_id = " . $row['forum_id'];
				$check_data = query($sql, "Couldn't check if user " . $row['user_id'] . " and forum " . $row['forum_id'] . " exist");

				if ( !($rowtest = $db->sql_fetchrow($check_data)) )
				{
					// Either the moderator or the forum have been deleted, this line in forum_mods was redundant, skip it.
					continue;
				}

				$sql = "SELECT g.group_id 
					FROM " . GROUPS_TABLE . " g, " . USER_GROUP_TABLE . " ug 
					WHERE g.group_id = ug.group_id 
						AND ug.user_id = " . $row['user_id'] . "
						AND g.group_single_user = 1";
				$insert_group = query($sql, "Couldn't get group number for user " . $row['user_id'] . ".");

				$group_id = $db->sql_fetchrow($insert_group);
				$group_id = $group_id['group_id'];

				print " * Adding moderator for forum " . $row['forum_id'] . " :: ";
				flush();

				$sql = "INSERT INTO " . AUTH_ACCESS_TABLE . " (group_id, forum_id, auth_mod) VALUES ($group_id, ".$row['forum_id'].", 1)";
				query($sql, "Couldn't set moderator (user_id = " . $row['user_id'] . ") for forum " . $row['forum_id'] . ".");

				print "<span class=\"ok\"><b>OK</b></span><br />\n";
			}
			
			end_step('convert_privforums');

		case 'convert_privforums':
			$sql = "SELECT fa.*, f.forum_name 
					FROM forum_access fa 
					LEFT JOIN " . FORUMS_TABLE . " f ON fa.forum_id = f.forum_id  
					ORDER BY fa.forum_id, fa.user_id";
			$forum_access = query($sql, "Couldn't get list with special forum access (forum_access)");

			$forum_id = -1;
			while( $row = $db->sql_fetchrow($forum_access) )
			{
				// Iterate trough access table
				if ( $row['forum_id'] != $forum_id )
				{
					// This is a new forum, create new group.
					$forum_id = $row['forum_id'];

					print " * Creating new group for forum $forum_id :: ";
					flush();

					$sql = "INSERT INTO " . GROUPS_TABLE . " (group_type, group_name, group_description, group_moderator, group_single_user)
						VALUES (" . GROUP_HIDDEN . ", '" . addslashes($row['forum_name']) . " Group', 'Converted Private Forum Group', " . $row['user_id'] . ", 0)";
					$result = query($sql, "Couldn't create group for ".$row['forum_name']);

					$group_id = $db->sql_nextid();

					if ( $group_id <= 0 )
					{
						print "<font color=\"red\">Group creation failed. Aborting creation of groups...<br></font>\n";
						continue 2;
					}

					print "<span class=\"ok\"><b>OK</b></span><br />\n";

					print " * Creating auth_access group for forum $forum_id :: ";
					flush();

					$sql = "INSERT INTO " . AUTH_ACCESS_TABLE . " (group_id, forum_id, auth_view, auth_read, auth_post, auth_reply, auth_edit, auth_delete)
						VALUES ($group_id, $forum_id, 1, 1, 1, 1, 1, 1)";
					$result = query($sql, "Unable to set group auth access.");

					if ( $db->sql_affectedrows($result) <= 0 )
					{
						print "<font color=\"red\">Group creation failed. Aborting creation of groups...</font><br>\n";
						continue 2;
					}

					print "<span class=\"ok\"><b>OK</b></span><br />\n";
				}

				// Add user to the group
				$user_id = $row['user_id'];

				$sql = "INSERT INTO " . USER_GROUP_TABLE . " (group_id, user_id, user_pending)
					VALUES ($group_id, $user_id, 0)";
				query($sql, "Unable to add user_id $user_id to group_id $group_id <br>\n");
			}

			end_step('update_schema');

		case 'update_schema':
			$rename = array(
				$table_prefix . "users" => array(
					"user_interests" => "user_intrest",
					"user_allowsmile" => "user_desmile",
					"user_allowhtml" => "user_html",
					"user_allowbbcode" => "user_bbcode", 
					"user_style" => "user_theme" 
				),
				$table_prefix . "privmsgs" => array(
					 "privmsgs_id" => "msg_id",
					 "privmsgs_from_userid" => "from_userid",
					 "privmsgs_to_userid" => "to_userid",
					 "privmsgs_date" => "msg_time",
					 "privmsgs_ip" => "poster_ip",
					 "privmsgs_type" => "msg_status" 
				),
				$table_prefix . "smilies" => array(
					"smilies_id" => "id"
				)
			);

			$schema = get_schema();

			$table_def = $schema['table_def'];
			$field_def = $schema['field_def'];

			// Loop tables in schema
			while (list($table, $table_def) = @each($field_def))
			{
				// Loop fields in table
				print " * Updating table '$table' :: ";
				flush();
				
				$sql = "SHOW FIELDS 
					FROM $table";
				$result = query($sql, "Can't get definition of current $table table");

				while( $row = $db->sql_fetchrow($result) )
				{
					$current_fields[] = $row['Field'];
				}
				
				$alter_sql = "ALTER TABLE $table ";
				while (list($field, $definition) = each($table_def))
				{
					if ( $field == '' )
					{
						// Skip empty fields if any (shouldn't be needed)
						continue;
					}

					$type = $definition['type'];
					$size = $definition['size'];

					$default = isset($definition['default']) ? "DEFAULT " . $definition['default'] : '';

					$notnull = $definition['notnull'] == 1 ? 'NOT NULL' : '';

					$auto_increment = $definition['auto_increment'] == 1 ? 'auto_increment' : '';

					$oldfield = isset($rename[$table][$field]) ? $rename[$table][$field] : $field;

					if ( !inarray($field, $current_fields) && $oldfield == $field )
					{
						// If the current is not a key of $current_def and it is not a field that is 
						// to be renamed then the field doesn't currently exist.
						$changes[] = " ADD $field " . $create_def[$table][$field];
					}
					else
					{
						$changes[] = " CHANGE $oldfield $field " . $create_def[$table][$field];
					}
				}
				
				$alter_sql .= join(',', $changes);
				unset($changes);
				unset($current_fields);
				
				$sql = "SHOW INDEX 
					FROM $table";
				$result = query($sql, "Couldn't get list of indices for table $table");

				unset($indices);

				while( $row = $db->sql_fetchrow($result) )
				{
					$indices[] = $row['Key_name'];
				}
				
				while ( list($key_name, $key_field) = each($key_def[$table]) )
				{
					if ( !inarray($key_name, $indices) )
					{
						$alter_sql .= ($key_name == 'PRIMARY') ? ", ADD PRIMARY KEY ($key_field)" : ", ADD INDEX $key_name ($key_field)";
					}
				}
				query($alter_sql, "Couldn't alter table $table");

				print "<span class=\"ok\"><b>OK</b></span><br />\n";
				flush();
			}

			end_step('convert_forums');

		case 'convert_forums':
			$sql = "SELECT * 
				FROM " . FORUMS_TABLE;
			$result = query($sql, "Couldn't get list with all forums");

			while( $row = $db->sql_fetchrow($result) )
			{
				print " * Converting forum '" . $row['forum_name'] . "' :: ";
				flush();

				// Old auth structure:
				// forum_type: (only concerns viewing)
				//		0 = Public
				//		1 = Private
				switch( $row['forum_type'] )
				{
					case 0:
						$auth_view			= AUTH_ALL;
						$auth_read			= AUTH_ALL;
						break;
					default:
						$auth_view			= AUTH_ALL;
						$auth_read			= AUTH_ALL;
						break;
				}
			
				// forum_access: (only concerns posting)
				//		1 = Registered users only
				//		2 = Anonymous Posting
				//		3 = Moderators/Administrators only
				switch( $row['forum_access'] )
				{
					case 1:
						// Public forum, no anonymous posting
						$auth_post			= AUTH_REG;
						$auth_reply			= AUTH_REG;
						$auth_edit			= AUTH_REG;
						$auth_delete		= AUTH_REG;
						$auth_vote			= AUTH_REG;
						$auth_pollcreate	= AUTH_REG;
						$auth_sticky		= AUTH_MOD;
						$auth_announce		= AUTH_MOD;
						break;
					case 2:
						$auth_post			= AUTH_ALL;
						$auth_reply			= AUTH_ALL;
						$auth_edit			= AUTH_ALL;
						$auth_delete		= AUTH_ALL;
						$auth_vote			= AUTH_ALL;
						$auth_pollcreate	= AUTH_ALL;
						$auth_sticky		= AUTH_MOD;
						$auth_announce		= AUTH_MOD;
						break;
					default:
						$auth_post			= AUTH_MOD;
						$auth_reply			= AUTH_MOD;
						$auth_edit			= AUTH_MOD;
						$auth_delete		= AUTH_MOD;
						$auth_vote			= AUTH_MOD;
						$auth_pollcreate	= AUTH_MOD;
						$auth_sticky		= AUTH_MOD;
						$auth_announce		= AUTH_MOD;
						break;
				}
				
				$sql = "UPDATE " . FORUMS_TABLE . " SET
					auth_view = $auth_view,
					auth_read = $auth_read,
					auth_post = $auth_post,
					auth_reply = $auth_reply,
					auth_edit = $auth_edit,
					auth_delete = $auth_delete,
					auth_vote = $auth_vote,
					auth_pollcreate = $auth_pollcreate,
					auth_sticky = $auth_sticky,
					auth_announce = $auth_announce
					WHERE forum_id = ". $row['forum_id'];
				query($sql, "Was unable to update forum permissions!");

				print "<span class=\"ok\"><b>OK</b></span><br />\n";
			}

			end_step('insert_themes');

		case 'insert_themes':
			print " * Inserting new values into themes table :: ";

			@reset($inserts);
			while( list($table, $inserts_table) = each($inserts) )
			{
				if ( $table == THEMES_TABLE )
				{
					$per_pct = ceil( count($inserts_table) / 40 );
					$inc = 0;

					while( list($nr, $insert) = each($inserts_table) )
					{
						query($insert, "Couldn't insert value into " . THEMES_TABLE);

						$inc++;
						if ( $inc == $per_pct )
						{
							print ".";
							flush();
							$inc = 0;
						}
					}
				}
			}

			print " <span class=\"ok\"><b>OK</b></span><br />\n";
			end_step('fulltext_search_indexing');

		case 'fulltext_search_indexing':
			//
			// Generate search word list
			//
			// Fetch a batch of posts_text entries
			//
			$sql = "SELECT COUNT(*) as total, MAX(post_id) as max_post_id 
				FROM " . POSTS_TEXT_TABLE;
			$result = query($sql, "Couldn't get post count totals");

			$max_post_id = $db->sql_fetchrow($result);

			$totalposts = $max_post_id['total'];
			$max_post_id = $max_post_id['max_post_id'];
			$per_percent = round(( $totalposts / 500 ) * 10);

			$postcounter = ( !isset($HTTP_GET_VARS['batchstart']) ) ? 0 : $HTTP_GET_VARS['batchstart'];

			$batchsize = 150; // Process this many posts per loop
			$batchcount = 0;
			$total_percent = 0;

			for(;$postcounter <= $max_post_id; $postcounter += $batchsize)
			{
				$batchstart = $postcounter + 1;
				$batchend = $postcounter + $batchsize;
				$batchcount++;

				print " * Fulltext Indexing ( $batchstart to $batchend ) :: ";
				flush();
				
				$sql = "SELECT *
					FROM " . POSTS_TEXT_TABLE ."
					WHERE post_id 
						BETWEEN $batchstart 
							AND $batchend";
				$posts_result = query($sql, "Couldn't obtain post_text");

				$per_pct = ceil( $db->sql_numrows($posts_result) / 40 );
				$inc = 0;

				if ( $row = $db->sql_fetchrow($posts_result) )
				{ 
					do
					{
						add_search_words($row['post_id'], $row['post_text'], $row['post_subject']);

						$inc++;
						if ( $inc == $per_pct )
						{
							print ".";
							flush();
							$inc = 0;
						}
					}
					while( $row = $db->sql_fetchrow($posts_result) );
				}

				$db->sql_freeresult($posts_result);
				
				// Remove common words after the first 2 batches and after every 4th batch after that.
				if ( $batchcount % 4 == 3 )
				{
					remove_common('global', 0.4);
				}

				print " <span class=\"ok\"><b>OK</b></span><br />\n";
			}

			end_step('update_topics');

		case 'update_topics':
			$sql = "SELECT MAX(topic_id) AS max_topic 
				FROM " . TOPICS_TABLE;
			$result = query($sql, "Couldn't get max topic id");

			$row = $db->sql_fetchrow($result);

			$maxid = $row['max_topic'];

			lock_tables(1, array(TOPICS_TABLE, POSTS_TABLE));

			$batchsize = 1000;
			for($i = 0; $i <= $maxid; $i += $batchsize)
			{
				$batchstart = $i + 1;
				$batchend = $i + $batchsize;
				
				print " * Setting topic first post_id ( $batchstart to $batchend ) :: ";
				flush();

				$sql = "SELECT MIN(post_id) AS first_post_id, topic_id
					FROM " . POSTS_TABLE . "
					WHERE topic_id 
						BETWEEN $batchstart 
							AND $batchend 
					GROUP BY topic_id 
					ORDER BY topic_id ASC";
				$result = query($sql, "Couldn't get post id data");

				$per_pct = ceil( $db->sql_numrows($result) / 40 );
				$inc = 0;

				if ( $row = $db->sql_fetchrow($result) )
				{
					do
					{
						$sql = "UPDATE " . TOPICS_TABLE . " 
							SET topic_first_post_id = " . $row['first_post_id'] . " 
							WHERE topic_id = " . $row['topic_id'];
						query($sql, "Couldn't update topic first post id in topic :: $topic_id");

						$inc++;
						if ( $inc == $per_pct )
						{
							print ".";
							flush();
							$inc = 0;
						}
					}
					while ( $row = $db->sql_fetchrow($result) );
				}

				print " <span class=\"ok\"><b>OK</b></span><br />\n";
			}

			lock_tables(0);
			end_step('final_configuration');

		case 'final_configuration':
			//
			// Update forum last post information
			//
			$sql = "SELECT forum_id, forum_name 
				FROM " . FORUMS_TABLE;
			$f_result = query($sql, "Couldn't obtain forum_ids");

			while( $forum_row = $db->sql_fetchrow($f_result) )
			{
				print " * Updating '" . $forum_row['forum_name'] . "' post info :: ";
				flush();

				$id = $forum_row['forum_id'];

				$sql = "SELECT MIN(p.post_id) AS first_post, MAX(p.post_id) AS last_post
					FROM " . POSTS_TABLE . " p, " . TOPICS_TABLE . " t
					WHERE p.forum_id = $id
						AND p.topic_id = t.topic_id";
				$result = query($sql, "Could not get post ID forum post information :: $id");

				if ( $row = $db->sql_fetchrow($result) )
				{
					$first_post = ( $row['first_post'] ) ? $row['first_post'] : 0;
					$last_post = ($row['last_post']) ? $row['last_post'] : 0;
				}
				else
				{
					$first_post = 0;
					$last_post = 0;
				}

				$sql = "SELECT COUNT(post_id) AS total
					FROM " . POSTS_TABLE . "
					WHERE forum_id = $id";
				$result = query($sql, "Could not get post count forum post information :: $id");

				if ( $row = $db->sql_fetchrow($result) )
				{
					$total_posts = ($row['total']) ? $row['total'] : 0;
				}
				else
				{
					$total_posts = 0;
				}

				$sql = "SELECT COUNT(topic_id) AS total
					FROM " . TOPICS_TABLE . "
					WHERE forum_id = $id 
						AND topic_status <> " . TOPIC_MOVED;
				$result = query($sql, "Could not get topic count forum post information :: $id");

				if ( $row = $db->sql_fetchrow($result) )
				{
					$total_topics = ($row['total']) ? $row['total'] : 0;
				}
				else
				{
					$total_topics = 0;
				}

				$sql = "UPDATE " . FORUMS_TABLE . "
					SET forum_last_post_id = $last_post, forum_posts = $total_posts, forum_topics = $total_topics
					WHERE forum_id = $id";
				query($sql, "Could not update forum post information :: $id");

				print "<span class=\"ok\"><b>OK</b></span><br />\n";
			}

			print "<br />\n * Update default user and finalise configuration :: ";
			flush();

			//
			// Update the default admin user with their information.
			//
			$sql = "SELECT MIN(user_regdate) AS oldest_time 
				FROM " . USERS_TABLE . " 
				WHERE user_regdate > 0";
			$result = query($sql, "Couldn't obtain oldest post time");

			$row = $db->sql_fetchrow($result);

			$sql = "INSERT INTO " . $table_prefix . "config (config_name, config_value) 
				VALUES ('board_startdate', " . $row['oldest_time']  . ")";
			query($sql, "Couldn't insert board_startdate");

			//
			// Change session table to HEAP if MySQL version matches
			//
			$sql = "SELECT VERSION() AS mysql_version";
			$result = query($sql, "Couldn't obtain MySQL Version");

			$row = $db->sql_fetchrow($result);

			$version = $row['mysql_version'];

			if ( preg_match("/^(3\.23)|(4\.)/", $version) )
			{
				$sql = "ALTER TABLE " . $table_prefix . "sessions 
					TYPE=HEAP";
				$db->sql_query($sql);
			}

			echo "<span class=\"ok\"><b>OK</b></span><br />\n";
			end_step('drop_fields');

		case 'drop_fields':
			$fields = array(
				BANLIST_TABLE => array("ban_start", "ban_end", "ban_time_type"),
				FORUMS_TABLE => array("forum_access", "forum_moderator", "forum_type"), 
				PRIVMSGS_TABLE => array("msg_text"), 
				RANKS_TABLE => array("rank_max"), 
				SMILIES_TABLE => array("emotion")
			);

			while( list($table, $field_data) = each($fields) )
			{
				for($i = 0; $i < count($field_data); $i++)
				{
					print " * Drop field '" . $field_data[$i] . "' in '$table' :: ";
					flush();

					$sql = "ALTER TABLE $table 
						DROP COLUMN " . $field_data[$i];
					query($sql, "Couldn't drop field :: " . $field_data[$i] . " from table :: $table");

					print "<span class=\"ok\"><b>OK</b></span><br />\n";

				}
			}

			end_step('drop_tables');

		case 'drop_tables':
			$drop_tables = array('access', 'forum_access', 'forum_mods', 'headermetafooter', 'whosonline', $table_prefix . 'old_config');

			for($i = 0; $i < count($drop_tables); $i++)
			{
				print " * Dropping table '" . $drop_tables[$i] . "' :: ";
				flush();

				$sql = "DROP TABLE " . $drop_tables[$i];
				query($sql, "Couldn't drop table :: " . $drop_tables[$i]);

				print "<span class=\"ok\"><b>OK</b></span><br />\n";
			}

			echo "\n<br /><br />\n\n<font size=\"+3\"><b>UPGRADE COMPLETED</b></font><br />\n";
	}
}

print "<br />If the upgrade completed without error you may click <a href=\"index.$phpEx\">Here</a> to proceed to the index<br />";

common_footer();

?>