screwed head on and then fixed obvious conceptual error
[lhc/web/wiklou.git] / maintenance / convertLinks.php
1 <?php
2
3 # Convert from the old links schema (string->ID) to the new schema (ID->ID)
4 # This hasn't been tested yet, so expect bugs
5
6 # The wiki should be put into read-only mode while this script executes
7
8 include_once( "commandLine.inc" );
9
10 # Check if it's already done
11
12 $res = wfQuery( "SELECT * FROM links LIMIT 1", DB_WRITE );
13 if ( !wfNumRows( $res ) ) {
14 print "No rows to convert. Updating schema...\n";
15 createTable();
16 } else {
17 $row = wfFetchObject( $res );
18 if ( is_numeric( $row->l_from ) ) {
19 print "Schema already converted\n";
20 exit;
21 }
22
23 # Create a title -> cur_id map
24
25 print "Loading IDs...";
26
27 wfBufferSQLResults( false );
28 $res = wfQuery( "SELECT cur_namespace,cur_title,cur_id FROM cur", DB_WRITE );
29 $ids = array();
30
31 while ( $row = wfFetchObject( $res ) ) {
32 $title = $row->cur_title;
33 if ( $row->cur_namespace ) {
34 $title = $wgLang->getNsText( $row->cur_namespace ) . ":$title";
35 }
36 $ids[$title] = $row->cur_id;
37 }
38 wfFreeResult( $res );
39
40 print "done\n";
41
42 # Now, load in all the links and create a links table in RAM
43 print "Processing links...\n";
44 $res = wfQuery( "SELECT * FROM links", DB_WRITE );
45 $links = array();
46 $numBad = 0;
47
48 while ( $row = wfFetchObject( $res ) ) {
49 if ( array_key_exists( $row->l_from, $ids ) ) {
50 $links[$row->l_from][$row->l_to] = 1;
51 } else {
52 $numBad ++;
53 }
54 }
55
56 print "Done, $numBad invalid titles\n";
57
58 # Save it to a new table
59 createTable();
60 $sql = "INSERT INTO links_temp(l_from,l_to) VALUES ";
61
62 $first = true;
63 foreach( $links as $from => $toArray ) {
64 foreach ( $toArray as $to => $one ) {
65 if ( $first ) {
66 $first = false;
67 } else {
68 $sql .= ",";
69 }
70 $sql .= "($from,$to)";
71 }
72 }
73
74 wfQuery( $sql, DB_WRITE );
75 }
76
77 # Swap in the new table
78 wfQuery( "RENAME TABLE links TO links_backup, links_temp TO links" );
79
80 print "Conversion complete. The old table remains at links_backup, delete at your leisure.\n";
81
82 function createTable() {
83 wfQuery( "CREATE TABLE links_temp (
84 l_from int(8) unsigned NOT NULL default '0',
85 l_to int(8) unsigned NOT NULL default '0',
86 UNIQUE KEY l_from(l_from,l_to),
87 KEY (l_to))", DB_WRITE);
88 }
89
90 ?>