* Fixed a typo
[mediawiki.git] / maintenance / updaters.inc
blobce2935e26e34ada74bce6eabe44548b4500c0bf5
1 <?php
2 /**
3  * @package MediaWiki
4  * @subpackage Maintenance
5  */
6  
7  /** */
9 require_once 'convertLinks.inc';
10 require_once 'InitialiseMessages.inc';
12 $wgRenamedTables = array(
13 #           from             to                  patch file
14         array( 'group',         'groups',           'patch-rename-group.sql' ),
17 $wgNewTables = array(
18 #            table          patch file (in maintenance/archives)
19         array( 'linkscc',       'patch-linkscc.sql' ),
20         array( 'hitcounter',    'patch-hitcounter.sql' ),
21         array( 'querycache',    'patch-querycache.sql' ),
22         array( 'objectcache',   'patch-objectcache.sql' ),
23         array( 'categorylinks', 'patch-categorylinks.sql' ),
24         array( 'logging',       'patch-logging.sql' ),
25         array( 'user_rights',   'patch-user_rights.sql' ),
26         array( 'groups',        'patch-userlevels.sql' ),
29 $wgNewFields = array(
30 #           table            field             patch file (in maintenance/archives)
31         array( 'ipblocks',      'ipb_id',           'patch-ipblocks.sql' ),
32         array( 'ipblocks',      'ipb_expiry',       'patch-ipb_expiry.sql' ),
33         array( 'recentchanges', 'rc_type',          'patch-rc_type.sql' ),
34         array( 'recentchanges', 'rc_ip',            'patch-rc_ip.sql' ),
35         array( 'recentchanges', 'rc_id',            'patch-rc_id.sql' ),
36         array( 'recentchanges', 'rc_patrolled',     'patch-rc-patrol.sql' ),
37         array( 'user',          'user_real_name',   'patch-user-realname.sql' ),
38         array( 'user',          'user_token',       'patch-user_token.sql' ),
39         array( 'user',          'user_email_token', 'patch-user_email_token.sql' ),
40         array( 'user_rights',   'ur_user',          'patch-rename-user_groups-and_rights.sql' ),
41         array( 'groups',        'gr_rights',        'patch-userlevels-rights.sql' ),
42         array( 'logging',       'log_params',       'patch-log_params.sql' ),
43         array( 'archive',       'ar_rev_id',        'patch-archive-rev_id.sql' ),
44         array( 'archive',       'ar_text_id',       'patch-archive-text_id.sql' ),
45         array( 'page',          'page_len',         'patch-page_len.sql' ),
46         array( 'revision',      'rev_deleted',      'patch-rev_deleted.sql' ),
47         array( 'image',         'img_width',        'patch-img_width.sql' ),
48         array( 'image',         'img_metadata',     'patch-img_metadata.sql' ),
49         array( 'image',         'img_media_type',   'patch-img_media_type.sql' ),
52 function rename_table( $from, $to, $patch ) {
53         global $wgDatabase;
54         if ( $wgDatabase->tableExists( $from ) ) {
55                 if ( $wgDatabase->tableExists( $to ) ) {
56                         echo "...can't move table $from to $to, $to already exists.\n";
57                 } else {
58                         echo "Moving table $from to $to...";
59                         dbsource( "maintenance/archives/$patch", $wgDatabase );
60                         echo "ok\n";
61                 }
62         } else {
63                 // Source table does not exist
64                 // Renames are done before creations, so this is typical for a new installation
65                 // Ignore silently
66         }
69 function add_table( $name, $patch ) {
70         global $wgDatabase;
71         if ( $wgDatabase->tableExists( $name ) ) {
72                 echo "...$name table already exists.\n";
73         } else {
74                 echo "Creating $name table...";
75                 dbsource( "maintenance/archives/$patch", $wgDatabase );
76                 echo "ok\n";
77         }
80 function add_field( $table, $field, $patch ) {
81         global $wgDatabase;
82         if ( !$wgDatabase->tableExists( $table ) ) {
83                 echo "...$table table does not exist, skipping new field patch\n";
84         } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
85                 echo "...have $field field in $table table.\n";
86         } else {
87                 echo "Adding $field field to table $table...";
88                 dbsource( "maintenance/archives/$patch" , $wgDatabase );
89                 echo "ok\n";
90         }
93 function do_revision_updates() {
94         global $wgSoftwareRevision;
95         if ( $wgSoftwareRevision < 1001 ) {
96                 update_passwords();
97         }
100 function update_passwords() {
101         wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
102         
103         global $wgDatabase;
104         $fname = "Update script: update_passwords()";
105         print "\nIt appears that you need to update the user passwords in your\n" .
106           "database. If you have already done this (if you've run this update\n" .
107           "script once before, for example), doing so again will make all your\n" .
108           "user accounts inaccessible, so be sure you only do this once.\n" .
109           "Update user passwords? (yes/no)";
111         $resp = readconsole();
112     if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
114         $sql = "SELECT user_id,user_password FROM user";
115         $source = $wgDatabase->query( $sql, $fname );
117         while ( $row = $wgDatabase->fetchObject( $source ) ) {
118                 $id = $row->user_id;
119                 $oldpass = $row->user_password;
120                 $newpass = md5( "{$id}-{$oldpass}" );
122                 $sql = "UPDATE user SET user_password='{$newpass}' " .
123                   "WHERE user_id={$id}";
124                 $wgDatabase->query( $sql, $fname );
125         }
128 function do_interwiki_update() {
129         # Check that interwiki table exists; if it doesn't source it
130         global $wgDatabase;
131         if( $wgDatabase->tableExists( "interwiki" ) ) {
132                 echo "...already have interwiki table\n";
133                 return true;
134         }
135         echo "Creating interwiki table: ";
136         dbsource( "maintenance/archives/patch-interwiki.sql" );
137         echo "ok\n";
138         echo "Adding default interwiki definitions: ";
139         dbsource( "maintenance/interwiki.sql" );
140         echo "ok\n";
143 function do_index_update() {
144         # Check that proper indexes are in place
145         global $wgDatabase;
146         $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
147         if( $meta->multiple_key == 0 ) {
148                 echo "Updating indexes to 20031107: ";
149                 dbsource( "maintenance/archives/patch-indexes.sql" );
150                 echo "ok\n";
151                 return true;
152         }
153         echo "...indexes seem up to 20031107 standards\n";
154         return false;
157 function do_linkscc_1_3_update() {
158         // Update linkscc table to 1.3 schema if necessary
159         global $wgDatabase, $wgVersion;
160         if( $wgDatabase->tableExists( "linkscc" )
161                 && $wgDatabase->fieldExists( "linkscc", "lcc_title" ) ) {
162                 echo "Altering lcc_title field from linkscc table... ";
163                 dbsource( "maintenance/archives/patch-linkscc-1.3.sql", $wgDatabase );
164                 echo "ok\n";
165         } else {
166                 echo "...linkscc is up to date, or does not exist. Good.\n";
167         }
170 function do_image_name_unique_update() {
171         global $wgDatabase;
172         if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
173                 echo "...image primary key already set.\n";
174         } else {
175                 echo "Making img_name the primary key... ";
176                 dbsource( "maintenance/archives/patch-image_name_primary.sql", $wgDatabase );
177                 echo "ok\n";
178         }
181 function do_watchlist_update() {
182         global $wgDatabase;
183         if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
184                 echo "ENOTIF: The watchlist table is already set up for email notification.\n";
185         } else {
186                 echo "ENOTIF: Adding wl_notificationtimestamp field for email notification management.";
187                 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
188                 dbsource( "maintenance/archives/patch-email-notification.sql", $wgDatabase );
189                 echo "ok\n";
190         }
193 function do_copy_newtalk_to_watchlist() {
194         global $wgDatabase;
195         global $wgCommandLineMode;      # this needs to be saved while getID() and getName() are called
197         if ( $wgDatabase->tableExists( 'user_newtalk' ) ) {
198                 $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
199                         $wgDatabase->tableName( 'user_newtalk' ) );
200                 $num_newtalks=$wgDatabase->numRows($res);
201                 echo "ENOTIF: Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
203                 $user = new User();
204                 for ( $i = 1; $i <= $num_newtalks; $i++ ) {
205                         $wluser = $wgDatabase->fetchObject( $res );
206                         echo 'ENOTIF: <= user_newtalk: user_id='.$wluser->user_id.' user_ip='.$wluser->user_ip."\n";
207                         if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
208                                 if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
209                                         $wgDatabase->replace( 'watchlist',
210                                                 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
211                                                   array('wl_user'                       => 0,
212                                                         'wl_namespace'                  => NS_USER_TALK,
213                                                         'wl_title'                      => $wluser->user_ip,
214                                                         'wl_notificationtimestamp'      => '19700101000000'
215                                                         ), 'updaters.inc::do_watchlist_update2'
216                                                 );
217                                         echo 'ENOTIF: ====> watchlist: user_id=0 '.$wluser->user_ip."\n";
218                                 }
219                         } else { # normal users ... have user_ids
220                                 $user->setID($wluser->user_id);
221                                 $wgDatabase->replace( 'watchlist',
222                                         array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
223                                           array('wl_user'                       => $user->getID(),
224                                                 'wl_namespace'                  => NS_USER_TALK,
225                                                 'wl_title'                      => $user->getName(),
226                                                 'wl_notificationtimestamp'      => '19700101000000'
227                                                 ), 'updaters.inc::do_watchlist_update3'
228                                         );
229                                 echo 'ENOTIF: ====> watchlist: user_id='.$user->getID().' '.$user->getName()."\n";
230                         }
231                 }
232                 echo "ENOTIF: The watchlist table has got the former user_newtalk entries.\n";
233                 dbsource( "maintenance/archives/patch-drop-user_newtalk.sql", $wgDatabase );
234                 echo "ENOTIF: Deleting the user_newtalk table as its entries are now in the watchlist table.\n";
235         } else {
236                 echo "ENOTIF: No user_newtalk table found. Nothing to convert to watchlist table entries.\n";
237         }
241 function do_user_update() {
242         global $wgDatabase;
243         if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
244                 echo "User table contains old email authentication field. Dropping... ";
245                 dbsource( "maintenance/archives/patch-email-authentication.sql", $wgDatabase );
246                 echo "ok\n";
247         } else {
248                 echo "...user table does not contain old email authentication field.\n";
249         }
252 # Assumes that the groups table has been added.
253 function do_group_update() {
254         global $wgDatabase;
255         $res = $wgDatabase->safeQuery( 'SELECT COUNT(*) AS c FROM !',
256                 $wgDatabase->tableName( 'groups' ) );
257         $row = $wgDatabase->fetchObject( $res );
258         $wgDatabase->freeResult( $res );
259         if( $row->c == 0 ) {
260                 echo "Adding default group definitions... ";
261                 dbsource( "maintenance/archives/patch-userlevels-defaultgroups.sql", $wgDatabase );
262                 echo "ok\n";
263         }
267  * 1.4 betas were missing the 'binary' marker from logging.log_title,
268  * which causes a collation mismatch error on joins in MySQL 4.1.
269  */
270 function do_logging_encoding() {
271         global $wgDatabase;
272         $logging = $wgDatabase->tableName( 'logging' );
273         $res = $wgDatabase->query( "SELECT log_title FROM $logging LIMIT 0" );
274         $flags = explode( ' ', mysql_field_flags( $res, 0 ) );
275         $wgDatabase->freeResult( $res );
276         
277         if( in_array( 'binary', $flags ) ) {
278                 echo "Logging table has correct title encoding.\n";
279         } else {
280                 echo "Fixing title encoding on logging table... ";
281                 dbsource( 'maintenance/archives/patch-logging-title.sql', $wgDatabase );
282                 echo "ok\n";
283         }
286 function do_schema_restructuring() {
287         global $wgDatabase;
288         $fname="do_schema_restructuring";
289         if ( $wgDatabase->tableExists( 'page' ) ) {
290                 echo "...page table already exists.\n";
291         } else {
292                 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
293                 echo wfTimestamp();
294                 echo "......checking for duplicate entries.\n"; flush();
295                 
296                 extract( $wgDatabase->tableNames( 'cur', 'old', 'page', 'revision', 'text' ) );
298                 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
299                                 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
301                 if ( $wgDatabase->numRows( $rows ) > 0 ) {
302                         echo wfTimestamp();
303                         echo "......<b>Found duplicate entries</b>\n";
304                         echo ( sprintf( "<b>      %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
305                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
306                                 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
307                                         $duplicate[$row->cur_namespace] = array();
308                                 }
309                                 $duplicate[$row->cur_namespace][] = $row->cur_title;
310                                 echo ( sprintf( "      %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
311                         }
312                         $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
313                         $firstCond = true; 
314                         foreach ( $duplicate as $ns => $titles ) {
315                                 if ( $firstCond ) {
316                                         $firstCond = false;
317                                 } else {
318                                         $sql .= ' OR ';
319                                 }
320                                 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
321                                 $first = true;
322                                 foreach ( $titles as $t ) {
323                                         if ( $first ) {
324                                                 $sql .= $wgDatabase->addQuotes( $t );
325                                                 $first = false;
326                                         } else {
327                                                 $sql .= ', ' . $wgDatabase->addQuotes( $t );
328                                         }
329                                 }
330                                 $sql .= ") ) \n";
331                         }
332                         # By sorting descending, the most recent entry will be the first in the list.
333                         # All following entries will be deleted by the next while-loop.
334                         $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
336                         $rows = $wgDatabase->query( $sql, $fname );
338                         $prev_title = $prev_namespace = false;
339                         $deleteId = array();
341                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
342                                 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
343                                         $deleteId[] = $row->cur_id;
344                                 }
345                                 $prev_title     = $row->cur_title;
346                                 $prev_namespace = $row->cur_namespace;
347                         }
348                         $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
349                         $rows = $wgDatabase->query( $sql, $fname );
350                         echo wfTimestamp();
351                         echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
352                 }
353                 
355                 echo wfTimestamp();
356                 echo "......Creating tables.\n";
357                 $wgDatabase->query("CREATE TABLE $page (
358                         page_id int(8) unsigned NOT NULL auto_increment,
359                         page_namespace int NOT NULL,
360                         page_title varchar(255) binary NOT NULL,
361                         page_restrictions tinyblob NOT NULL default '',
362                         page_counter bigint(20) unsigned NOT NULL default '0',
363                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
364                         page_is_new tinyint(1) unsigned NOT NULL default '0',
365                         page_random real unsigned NOT NULL,
366                         page_touched char(14) binary NOT NULL default '',
367                         page_latest int(8) unsigned NOT NULL,
368                         page_len int(8) unsigned NOT NULL,
370                         PRIMARY KEY page_id (page_id),
371                         UNIQUE INDEX name_title (page_namespace,page_title),
372                         INDEX (page_random),
373                         INDEX (page_len)
374                         ) TYPE=InnoDB", $fname );
375                 $wgDatabase->query("CREATE TABLE $revision (
376                         rev_id int(8) unsigned NOT NULL auto_increment,
377                         rev_page int(8) unsigned NOT NULL,
378                         rev_comment tinyblob NOT NULL default '',
379                         rev_user int(5) unsigned NOT NULL default '0',
380                         rev_user_text varchar(255) binary NOT NULL default '',
381                         rev_timestamp char(14) binary NOT NULL default '',
382                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
383                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
384   
385                         PRIMARY KEY rev_page_id (rev_page, rev_id),
386                         UNIQUE INDEX rev_id (rev_id),
387                         INDEX rev_timestamp (rev_timestamp),
388                         INDEX page_timestamp (rev_page,rev_timestamp),
389                         INDEX user_timestamp (rev_user,rev_timestamp),
390                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
391                         ) TYPE=InnoDB", $fname );
393                 echo wfTimestamp();
394                 echo "......Locking tables.\n";
395                 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
397                 $maxold = $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname );
398                 echo wfTimestamp();
399                 echo "......maxold is {$maxold}\n";
401                 echo wfTimestamp();
402                 global $wgLegacySchemaConversion;
403                 if( $wgLegacySchemaConversion ) {
404                         // Create HistoryBlobCurStub entries.
405                         // Text will be pulled from the leftover 'cur' table at runtime.
406                         echo "......Moving metadata from cur; using blob references to text in cur table.\n";
407                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
408                         $cur_flags = "'object'";
409                 } else {
410                         // Copy all cur text in immediately: this may take longer but avoids
411                         // having to keep an extra table around.
412                         echo "......Moving text from cur.\n";
413                         $cur_text = 'cur_text';
414                         $cur_flags = "''";
415                 }
416                 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
417                                 old_timestamp, old_minor_edit, old_flags)
418                         SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
419                         FROM $cur", $fname );
421                 echo wfTimestamp();
422                 echo "......Setting up revision table.\n";
423                 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
424                                 rev_minor_edit)
425                         SELECT old_id, cur_id, old_comment, old_user, old_user_text,
426                                 old_timestamp, old_minor_edit
427                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
429                 echo wfTimestamp();
430                 echo "......Setting up page table.\n";
431                 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
432                                 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
433                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
434                                 cur_random, cur_touched, rev_id, LENGTH(cur_text)
435                         FROM $cur,$revision
436                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
438                 echo wfTimestamp();
439                 echo "......Unlocking tables.\n";
440                 $wgDatabase->query( "UNLOCK TABLES", $fname );
442                 echo wfTimestamp();
443                 echo "......Renaming old.\n";
444                 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
445                 
446                 echo wfTimestamp();
447                 echo "...done.\n";
448         }
451 function do_inverse_timestamp() {
452         global $wgDatabase;
453         $fname="do_schema_restructuring";
454         if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
455                 echo "Removing revision.inverse_timestamp and fixing indexes... ";
456                 dbsource( 'maintenance/archives/patch-inverse_timestamp.sql', $wgDatabase );
457                 echo "ok\n";
458         } else {
459                 echo "revision timestamp indexes already up to 2005-03-13\n";
460         }
463 function do_text_id() {
464         global $wgDatabase;
465         if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
466                 echo "...rev_text_id already in place.\n";
467         } else {
468                 echo "Adding rev_text_id field... ";
469                 dbsource( 'maintenance/archives/patch-rev_text_id.sql', $wgDatabase );
470                 echo "ok\n";
471         }
474 function do_namespace_size() {
475         $tables = array(
476                 'page'          => 'page',
477                 'archive'       => 'ar',
478                 'recentchanges' => 'rc',
479                 'watchlist'     => 'wl',
480                 'querycache'    => 'qc',
481                 'logging'       => 'log',
482         );
483         foreach( $tables as $table => $prefix ) {
484                 do_namespace_size_on( $table, $prefix );
485                 flush();
486         }
489 function do_namespace_size_on( $table, $prefix ) {
490         global $wgDatabase;
491         $field = $prefix . '_namespace';
492         
493         $tablename = $wgDatabase->tableName( $table );
494         $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
495         $info = $wgDatabase->fetchObject( $result );
496         $wgDatabase->freeResult( $result );
497         
498         if( substr( $info->Type, 0, 3 ) == 'int' ) {
499                 echo "...$field is already a full int ($info->Type).\n";
500         } else {
501                 echo "Promoting $field from $info->Type to int... ";
502                 
503                 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
504                 $wgDatabase->query( $sql );
505                 
506                 echo "ok\n";
507         }
510 function do_all_updates() {
511         global $wgNewTables, $wgNewFields, $wgRenamedTables;
512         
513         # Rename tables
514         foreach ( $wgRenamedTables as $tableRecord ) {
515                 rename_table( $tableRecord[0], $tableRecord[1], $tableRecord[2] );
516         }
518         # Add missing tables
519         foreach ( $wgNewTables as $tableRecord ) {
520                 add_table( $tableRecord[0], $tableRecord[1] );
521                 flush();
522         }
524         # Add missing fields
525         foreach ( $wgNewFields as $fieldRecord ) {
526                 add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2] );
527                 flush();
528         }
529         
530         # Add default group data
531         do_group_update(); flush();
533         # Do schema updates which require special handling
534         do_interwiki_update(); flush();
535         do_index_update(); flush();
536         do_linkscc_1_3_update(); flush();
537         convertLinks(); flush();
538         do_image_name_unique_update(); flush();
539         do_watchlist_update(); flush();
540         do_user_update(); flush();
541         do_copy_newtalk_to_watchlist(); flush();
542         do_logging_encoding(); flush();
543         
544         do_schema_restructuring(); flush();
545         do_inverse_timestamp(); flush();
546         do_text_id(); flush();
547         do_namespace_size(); flush();
549         initialiseMessages(); flush();