Copying .cvsignore and hoping to test notification mails...
[mediawiki.git] / maintenance / updaters.inc
blob6f33841d787916528117c2b6a5b800d299af1a02
1 <?php
2 /**
3  * @package MediaWiki
4  * @subpackage Maintenance
5  */
7  /** */
9 require_once 'convertLinks.inc';
10 require_once 'InitialiseMessages.inc';
11 require_once 'userDupes.inc';
13 $wgRenamedTables = array(
14 #           from             to                  patch file
15 #       array( 'group',         'groups',           'patch-rename-group.sql' ),
18 $wgNewTables = array(
19 #            table          patch file (in maintenance/archives)
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( 'validate',      'patch-validate.sql' ),
26         array( 'user_newtalk',  'patch-usernewtalk2.sql' ),
27         array( 'transcache',    'patch-transcache.sql' ),
28         array( 'trackbacks',    'patch-trackbacks.sql' ),
29         array( 'externallinks', 'patch-externallinks.sql' ),
30         array( 'job',           'patch-job.sql' ),
33 $wgNewFields = array(
34 #           table            field             patch file (in maintenance/archives)
35         array( 'ipblocks',      'ipb_id',           'patch-ipblocks.sql' ),
36         array( 'ipblocks',      'ipb_expiry',       'patch-ipb_expiry.sql' ),
37         array( 'recentchanges', 'rc_type',          'patch-rc_type.sql' ),
38         array( 'recentchanges', 'rc_ip',            'patch-rc_ip.sql' ),
39         array( 'recentchanges', 'rc_id',            'patch-rc_id.sql' ),
40         array( 'recentchanges', 'rc_patrolled',     'patch-rc-patrol.sql' ),
41         array( 'user',          'user_real_name',   'patch-user-realname.sql' ),
42         array( 'user',          'user_token',       'patch-user_token.sql' ),
43         array( 'user',          'user_email_token', 'patch-user_email_token.sql' ),
44         array( 'user',          'user_registration','patch-user_registration.sql' ),
45         array( 'logging',       'log_params',       'patch-log_params.sql' ),
46         array( 'archive',       'ar_rev_id',        'patch-archive-rev_id.sql' ),
47         array( 'archive',       'ar_text_id',       'patch-archive-text_id.sql' ),
48         array( 'page',          'page_len',         'patch-page_len.sql' ),
49         array( 'revision',      'rev_deleted',      'patch-rev_deleted.sql' ),
50         array( 'image',         'img_width',        'patch-img_width.sql' ),
51         array( 'image',         'img_metadata',     'patch-img_metadata.sql' ),
52         array( 'image',         'img_media_type',   'patch-img_media_type.sql' ),
53         array( 'validate',      'val_ip',           'patch-val_ip.sql' ),
54         array( 'site_stats',    'ss_total_pages',   'patch-ss_total_articles.sql' ),
55         array( 'interwiki',     'iw_trans',         'patch-interwiki-trans.sql' ),
56         array( 'ipblocks',      'ipb_range_start',  'patch-ipb_range_start.sql' ),
57         array( 'site_stats',    'ss_images',        'patch-ss_images.sql' ),
60 function rename_table( $from, $to, $patch ) {
61         global $wgDatabase;
62         if ( $wgDatabase->tableExists( $from ) ) {
63                 if ( $wgDatabase->tableExists( $to ) ) {
64                         echo "...can't move table $from to $to, $to already exists.\n";
65                 } else {
66                         echo "Moving table $from to $to...";
67                         dbsource( archive($patch), $wgDatabase );
68                         echo "ok\n";
69                 }
70         } else {
71                 // Source table does not exist
72                 // Renames are done before creations, so this is typical for a new installation
73                 // Ignore silently
74         }
77 function add_table( $name, $patch ) {
78         global $wgDatabase;
79         if ( $wgDatabase->tableExists( $name ) ) {
80                 echo "...$name table already exists.\n";
81         } else {
82                 echo "Creating $name table...";
83                 dbsource( archive($patch), $wgDatabase );
84                 echo "ok\n";
85         }
88 function add_field( $table, $field, $patch ) {
89         global $wgDatabase;
90         if ( !$wgDatabase->tableExists( $table ) ) {
91                 echo "...$table table does not exist, skipping new field patch\n";
92         } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
93                 echo "...have $field field in $table table.\n";
94         } else {
95                 echo "Adding $field field to table $table...";
96                 dbsource( archive($patch) , $wgDatabase );
97                 echo "ok\n";
98         }
101 function do_revision_updates() {
102         global $wgSoftwareRevision;
103         if ( $wgSoftwareRevision < 1001 ) {
104                 update_passwords();
105         }
108 function update_passwords() {
109         wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
111         global $wgDatabase;
112         $fname = "Update script: update_passwords()";
113         print "\nIt appears that you need to update the user passwords in your\n" .
114           "database. If you have already done this (if you've run this update\n" .
115           "script once before, for example), doing so again will make all your\n" .
116           "user accounts inaccessible, so be sure you only do this once.\n" .
117           "Update user passwords? (yes/no)";
119         $resp = readconsole();
120     if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
122         $sql = "SELECT user_id,user_password FROM user";
123         $source = $wgDatabase->query( $sql, $fname );
125         while ( $row = $wgDatabase->fetchObject( $source ) ) {
126                 $id = $row->user_id;
127                 $oldpass = $row->user_password;
128                 $newpass = md5( "{$id}-{$oldpass}" );
130                 $sql = "UPDATE user SET user_password='{$newpass}' " .
131                   "WHERE user_id={$id}";
132                 $wgDatabase->query( $sql, $fname );
133         }
136 function do_interwiki_update() {
137         # Check that interwiki table exists; if it doesn't source it
138         global $wgDatabase;
139         if( $wgDatabase->tableExists( "interwiki" ) ) {
140                 echo "...already have interwiki table\n";
141                 return true;
142         }
143         echo "Creating interwiki table: ";
144         dbsource( archive("patch-interwiki.sql") );
145         echo "ok\n";
146         echo "Adding default interwiki definitions: ";
147         dbsource( "maintenance/interwiki.sql" );
148         echo "ok\n";
151 function do_index_update() {
152         # Check that proper indexes are in place
153         global $wgDatabase;
154         $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
155         if( $meta->multiple_key == 0 ) {
156                 echo "Updating indexes to 20031107: ";
157                 dbsource( archive("patch-indexes.sql") );
158                 echo "ok\n";
159                 return true;
160         }
161         echo "...indexes seem up to 20031107 standards\n";
162         return false;
165 function do_image_index_update() {
166         global $wgDatabase;
168         $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
169         if( $meta->multiple_key == 0 ) {
170                 echo "Updating indexes to 20050912: ";
171                 dbsource( archive("patch-mimesearch-indexes.sql") );
172                 echo "ok\n";
173                 return true;
174         }
175         echo "...indexes seem up to 20050912 standards\n";
176         return false;
179 function do_image_name_unique_update() {
180         global $wgDatabase;
181         if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
182                 echo "...image primary key already set.\n";
183         } else {
184                 echo "Making img_name the primary key... ";
185                 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
186                 echo "ok\n";
187         }
190 function do_logging_timestamp_index() {
191         global $wgDatabase;
192         if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
193                 echo "...timestamp key on logging already exists.\n";
194         } else {
195                 echo "Adding timestamp key on logging table... ";
196                 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
197                 echo "ok\n";
198         }
202 function do_watchlist_update() {
203         global $wgDatabase;
204         $fname = 'do_watchlist_update';
205         if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
206                 echo "The watchlist table is already set up for email notification.\n";
207         } else {
208                 echo "Adding wl_notificationtimestamp field for email notification management.";
209                 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
210                 dbsource( "maintenance/archives/patch-email-notification.sql", $wgDatabase );
211                 echo "ok\n";
212         }
213         # Check if we need to add talk page rows to the watchlist
214         $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
215         $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
216         if ( $talk != $nontalk ) {
217                 echo "Adding missing watchlist talk page rows... ";
218                 flush();
220                 $wgDatabase->insertSelect( 'watchlist', 'watchlist', 
221                         array(
222                                 'wl_user' => 'wl_user',
223                                 'wl_namespace' => 'wl_namespace | 1',
224                                 'wl_title' => 'wl_title',
225                                 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
226                         ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
227                 echo "ok\n";
228         } else {
229                 echo "...watchlist talk page rows already present\n";
230         }
233 function do_copy_newtalk_to_watchlist() {
234         global $wgDatabase;
235         global $wgCommandLineMode;      # this needs to be saved while getID() and getName() are called
237         $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
238                 $wgDatabase->tableName( 'user_newtalk' ) );
239         $num_newtalks=$wgDatabase->numRows($res);
240         echo "Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
242         $user = new User();
243         for ( $i = 1; $i <= $num_newtalks; $i++ ) {
244                 $wluser = $wgDatabase->fetchObject( $res );
245                 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
246                         if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
247                                 $wgDatabase->replace( 'watchlist',
248                                         array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
249                                           array('wl_user'                       => 0,
250                                                 'wl_namespace'                  => NS_USER_TALK,
251                                                 'wl_title'                      => $wluser->user_ip,
252                                                 'wl_notificationtimestamp'      => '19700101000000'
253                                                 ), 'updaters.inc::do_watchlist_update2'
254                                         );
255                         }
256                 } else { # normal users ... have user_ids
257                         $user->setID($wluser->user_id);
258                         $wgDatabase->replace( 'watchlist',
259                                 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
260                                   array('wl_user'                       => $user->getID(),
261                                         'wl_namespace'                  => NS_USER_TALK,
262                                         'wl_title'                      => $user->getName(),
263                                         'wl_notificationtimestamp'      => '19700101000000'
264                                         ), 'updaters.inc::do_watchlist_update3'
265                                 );
266                 }
267         }
268         echo "Done.\n";
272 function do_user_update() {
273         global $wgDatabase;
274         if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
275                 echo "User table contains old email authentication field. Dropping... ";
276                 dbsource( "maintenance/archives/patch-email-authentication.sql", $wgDatabase );
277                 echo "ok\n";
278         } else {
279                 echo "...user table does not contain old email authentication field.\n";
280         }
284  * 1.4 betas were missing the 'binary' marker from logging.log_title,
285  * which causes a collation mismatch error on joins in MySQL 4.1.
286  */
287 function do_logging_encoding() {
288         global $wgDatabase, $wgDBtype;
289         if ($wgDBtype != 'mysql')
290                 return;
291         $logging = $wgDatabase->tableName( 'logging' );
292         $res = $wgDatabase->query( "SELECT log_title FROM $logging LIMIT 0" );
293         $flags = explode( ' ', mysql_field_flags( $res, 0 ) );
294         $wgDatabase->freeResult( $res );
296         if( in_array( 'binary', $flags ) ) {
297                 echo "Logging table has correct title encoding.\n";
298         } else {
299                 echo "Fixing title encoding on logging table... ";
300                 dbsource( 'maintenance/archives/patch-logging-title.sql', $wgDatabase );
301                 echo "ok\n";
302         }
305 function do_schema_restructuring() {
306         global $wgDatabase;
307         $fname="do_schema_restructuring";
308         if ( $wgDatabase->tableExists( 'page' ) ) {
309                 echo "...page table already exists.\n";
310         } else {
311                 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
312                 echo wfTimestamp();
313                 echo "......checking for duplicate entries.\n"; flush();
315                 extract( $wgDatabase->tableNames( 'cur', 'old', 'page', 'revision', 'text' ) );
317                 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
318                                 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
320                 if ( $wgDatabase->numRows( $rows ) > 0 ) {
321                         echo wfTimestamp();
322                         echo "......<b>Found duplicate entries</b>\n";
323                         echo ( sprintf( "<b>      %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
324                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
325                                 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
326                                         $duplicate[$row->cur_namespace] = array();
327                                 }
328                                 $duplicate[$row->cur_namespace][] = $row->cur_title;
329                                 echo ( sprintf( "      %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
330                         }
331                         $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
332                         $firstCond = true;
333                         foreach ( $duplicate as $ns => $titles ) {
334                                 if ( $firstCond ) {
335                                         $firstCond = false;
336                                 } else {
337                                         $sql .= ' OR ';
338                                 }
339                                 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
340                                 $first = true;
341                                 foreach ( $titles as $t ) {
342                                         if ( $first ) {
343                                                 $sql .= $wgDatabase->addQuotes( $t );
344                                                 $first = false;
345                                         } else {
346                                                 $sql .= ', ' . $wgDatabase->addQuotes( $t );
347                                         }
348                                 }
349                                 $sql .= ") ) \n";
350                         }
351                         # By sorting descending, the most recent entry will be the first in the list.
352                         # All following entries will be deleted by the next while-loop.
353                         $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
355                         $rows = $wgDatabase->query( $sql, $fname );
357                         $prev_title = $prev_namespace = false;
358                         $deleteId = array();
360                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
361                                 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
362                                         $deleteId[] = $row->cur_id;
363                                 }
364                                 $prev_title     = $row->cur_title;
365                                 $prev_namespace = $row->cur_namespace;
366                         }
367                         $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
368                         $rows = $wgDatabase->query( $sql, $fname );
369                         echo wfTimestamp();
370                         echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
371                 }
374                 echo wfTimestamp();
375                 echo "......Creating tables.\n";
376                 $wgDatabase->query("CREATE TABLE $page (
377                         page_id int(8) unsigned NOT NULL auto_increment,
378                         page_namespace int NOT NULL,
379                         page_title varchar(255) binary NOT NULL,
380                         page_restrictions tinyblob NOT NULL default '',
381                         page_counter bigint(20) unsigned NOT NULL default '0',
382                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
383                         page_is_new tinyint(1) unsigned NOT NULL default '0',
384                         page_random real unsigned NOT NULL,
385                         page_touched char(14) binary NOT NULL default '',
386                         page_latest int(8) unsigned NOT NULL,
387                         page_len int(8) unsigned NOT NULL,
389                         PRIMARY KEY page_id (page_id),
390                         UNIQUE INDEX name_title (page_namespace,page_title),
391                         INDEX (page_random),
392                         INDEX (page_len)
393                         ) ENGINE=InnoDB", $fname );
394                 $wgDatabase->query("CREATE TABLE $revision (
395                         rev_id int(8) unsigned NOT NULL auto_increment,
396                         rev_page int(8) unsigned NOT NULL,
397                         rev_comment tinyblob NOT NULL default '',
398                         rev_user int(5) unsigned NOT NULL default '0',
399                         rev_user_text varchar(255) binary NOT NULL default '',
400                         rev_timestamp char(14) binary NOT NULL default '',
401                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
402                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
404                         PRIMARY KEY rev_page_id (rev_page, rev_id),
405                         UNIQUE INDEX rev_id (rev_id),
406                         INDEX rev_timestamp (rev_timestamp),
407                         INDEX page_timestamp (rev_page,rev_timestamp),
408                         INDEX user_timestamp (rev_user,rev_timestamp),
409                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
410                         ) ENGINE=InnoDB", $fname );
412                 echo wfTimestamp();
413                 echo "......Locking tables.\n";
414                 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
416                 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
417                 echo wfTimestamp();
418                 echo "......maxold is {$maxold}\n";
420                 echo wfTimestamp();
421                 global $wgLegacySchemaConversion;
422                 if( $wgLegacySchemaConversion ) {
423                         // Create HistoryBlobCurStub entries.
424                         // Text will be pulled from the leftover 'cur' table at runtime.
425                         echo "......Moving metadata from cur; using blob references to text in cur table.\n";
426                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
427                         $cur_flags = "'object'";
428                 } else {
429                         // Copy all cur text in immediately: this may take longer but avoids
430                         // having to keep an extra table around.
431                         echo "......Moving text from cur.\n";
432                         $cur_text = 'cur_text';
433                         $cur_flags = "''";
434                 }
435                 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
436                                 old_timestamp, old_minor_edit, old_flags)
437                         SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
438                         FROM $cur", $fname );
440                 echo wfTimestamp();
441                 echo "......Setting up revision table.\n";
442                 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
443                                 rev_minor_edit)
444                         SELECT old_id, cur_id, old_comment, old_user, old_user_text,
445                                 old_timestamp, old_minor_edit
446                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
448                 echo wfTimestamp();
449                 echo "......Setting up page table.\n";
450                 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
451                                 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
452                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
453                                 cur_random, cur_touched, rev_id, LENGTH(cur_text)
454                         FROM $cur,$revision
455                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
457                 echo wfTimestamp();
458                 echo "......Unlocking tables.\n";
459                 $wgDatabase->query( "UNLOCK TABLES", $fname );
461                 echo wfTimestamp();
462                 echo "......Renaming old.\n";
463                 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
465                 echo wfTimestamp();
466                 echo "...done.\n";
467         }
470 function do_inverse_timestamp() {
471         global $wgDatabase;
472         $fname="do_schema_restructuring";
473         if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
474                 echo "Removing revision.inverse_timestamp and fixing indexes... ";
475                 dbsource( 'maintenance/archives/patch-inverse_timestamp.sql', $wgDatabase );
476                 echo "ok\n";
477         } else {
478                 echo "revision timestamp indexes already up to 2005-03-13\n";
479         }
482 function do_text_id() {
483         global $wgDatabase;
484         if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
485                 echo "...rev_text_id already in place.\n";
486         } else {
487                 echo "Adding rev_text_id field... ";
488                 dbsource( 'maintenance/archives/patch-rev_text_id.sql', $wgDatabase );
489                 echo "ok\n";
490         }
493 function do_namespace_size() {
494         $tables = array(
495                 'page'          => 'page',
496                 'archive'       => 'ar',
497                 'recentchanges' => 'rc',
498                 'watchlist'     => 'wl',
499                 'querycache'    => 'qc',
500                 'logging'       => 'log',
501         );
502         foreach( $tables as $table => $prefix ) {
503                 do_namespace_size_on( $table, $prefix );
504                 flush();
505         }
508 function do_namespace_size_on( $table, $prefix ) {
509         global $wgDatabase, $wgDBtype;
510         if ($wgDBtype != 'mysql')
511                 return;
512         $field = $prefix . '_namespace';
514         $tablename = $wgDatabase->tableName( $table );
515         $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
516         $info = $wgDatabase->fetchObject( $result );
517         $wgDatabase->freeResult( $result );
519         if( substr( $info->Type, 0, 3 ) == 'int' ) {
520                 echo "...$field is already a full int ($info->Type).\n";
521         } else {
522                 echo "Promoting $field from $info->Type to int... ";
524                 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
525                 $wgDatabase->query( $sql );
527                 echo "ok\n";
528         }
531 function do_pagelinks_update() {
532         global $wgDatabase;
533         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
534                 echo "...already have pagelinks table.\n";
535         } else {
536                 echo "Converting links and brokenlinks tables to pagelinks... ";
537                 dbsource( "maintenance/archives/patch-pagelinks.sql", $wgDatabase );
538                 echo "ok\n";
539                 flush();
541                 global $wgCanonicalNamespaceNames;
542                 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
543                         if( $ns != 0 ) {
544                                 do_pagelinks_namespace( $ns );
545                         }
546                 }
547         }
550 function do_pagelinks_namespace( $namespace ) {
551         global $wgDatabase, $wgContLang;
553         $ns = intval( $namespace );
554         echo "Cleaning up broken links for namespace $ns... ";
556         $pagelinks = $wgDatabase->tableName( 'pagelinks' );
557         $name = $wgContLang->getNsText( $ns );
558         $prefix = $wgDatabase->strencode( $name );
559         $likeprefix = str_replace( '_', '\\_', $prefix);
561         $sql = "UPDATE $pagelinks
562                    SET pl_namespace=$ns,
563                        pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
564                  WHERE pl_namespace=0
565                    AND pl_title LIKE '$likeprefix:%'";
567         $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
568         echo "ok\n";
571 function do_drop_img_type() {
572         global $wgDatabase;
574         if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
575                 echo "Dropping unused img_type field in image table... ";
576                 dbsource( "maintenance/archives/patch-drop_img_type.sql", $wgDatabase );
577                 echo "ok\n";
578         } else {
579                 echo "No img_type field in image table; Good.\n";
580         }
583 function do_old_links_update() {
584         global $wgDatabase;
585         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
586                 echo "Already have pagelinks; skipping old links table updates.\n";
587         } else {
588                 convertLinks(); flush();
589         }
592 function do_user_unique_update() {
593         global $wgDatabase;
594         $duper = new UserDupes( $wgDatabase );
595         if( $duper->hasUniqueIndex() ) {
596                 echo "Already have unique user_name index.\n";
597         } else {
598                 if( !$duper->clearDupes() ) {
599                         echo "WARNING: This next step will probably fail due to unfixed duplicates...\n";
600                 }
601                 echo "Adding unique index on user_name... ";
602                 dbsource( 'maintenance/archives/patch-user_nameindex.sql', $wgDatabase );
603                 echo "ok\n";
604         }
607 function do_user_groups_update() {
608         $fname = 'do_user_groups_update';
609         global $wgDatabase;
611         if( $wgDatabase->tableExists( 'user_groups' ) ) {
612                 echo "...user_groups table already exists.\n";
613                 return do_user_groups_reformat();
614         }
616         echo "Adding user_groups table... ";
617         dbsource( 'maintenance/archives/patch-user_groups.sql', $wgDatabase );
618         echo "ok\n";
620         if( !$wgDatabase->tableExists( 'user_rights' ) ) {
621                 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
622                         echo "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion...";
623                         dbsource( 'maintenance/archives/patch-user_rights.sql', $wgDatabase );
624                         echo "ok\n";
625                 } else {
626                         echo "*** WARNING: couldn't locate user_rights table or field for upgrade.\n";
627                         echo "*** You may need to manually configure some sysops by manipulating\n";
628                         echo "*** the user_groups table.\n";
629                         return;
630                 }
631         }
633         echo "Converting user_rights table to user_groups... ";
634         $result = $wgDatabase->select( 'user_rights',
635                 array( 'ur_user', 'ur_rights' ),
636                 array( "ur_rights != ''" ),
637                 $fname );
639         while( $row = $wgDatabase->fetchObject( $result ) ) {
640                 $groups = array_unique(
641                         array_map( 'trim',
642                                 explode( ',', $row->ur_rights ) ) );
644                 foreach( $groups as $group ) {
645                         $wgDatabase->insert( 'user_groups',
646                                 array(
647                                         'ug_user'  => $row->ur_user,
648                                         'ug_group' => $group ),
649                                 $fname );
650                 }
651         }
652         $wgDatabase->freeResult( $result );
653         echo "ok\n";
656 function do_user_groups_reformat() {
657         # Check for bogus formats from previous 1.5 alpha code.
658         global $wgDatabase;
659         $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
661         if( $info->type == 'int' ) {
662                 $oldug = $wgDatabase->tableName( 'user_groups' );
663                 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
664                 echo "user_groups is in bogus intermediate format. Renaming to $newug... ";
665                 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
666                 echo "ok\n";
668                 echo "Re-adding fresh user_groups table... ";
669                 dbsource( 'maintenance/archives/patch-user_groups.sql', $wgDatabase );
670                 echo "ok\n";
672                 echo "***\n";
673                 echo "*** WARNING: You will need to manually fix up user permissions in the user_groups\n";
674                 echo "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n";
675                 echo "***\n";
676         } else {
677                 echo "...user_groups is in current format.\n";
678         }
682 function do_watchlist_null() {
683         # Make sure wl_notificationtimestamp can be NULL,
684         # and update old broken items.
685         global $wgDatabase;
686         $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
688         if( $info->not_null ) {
689                 echo "Making wl_notificationtimestamp nullable... ";
690                 dbsource( 'maintenance/archives/patch-watchlist-null.sql', $wgDatabase );
691                 echo "ok\n";
692         } else {
693                 echo "...wl_notificationtimestamp is already nullable.\n";
694         }
699  * @bug 3946
700  */
701 function do_page_random_update() {
702         global $wgDatabase;
704         echo "Setting page_random to a random value on rows where it equals 0...";
706         $page = $wgDatabase->tableName( 'page' );
707         $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
708         $rows = $wgDatabase->affectedRows();
710         echo "changed $rows rows\n";
713 function do_templatelinks_update() {
714         global $wgDatabase, $wgLoadBalancer;
715         $fname = 'do_templatelinks_update';
717         if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
718                 echo "...templatelinks table already exists\n";
719                 return;
720         }
721         echo "Creating templatelinks table...\n";
722         dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
723         echo "Populating...\n";
724         if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
725                 // Slow, replication-friendly update
726                 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
727                         array( 'pl_namespace' => NS_TEMPLATE ), $fname );
728                 $count = 0;
729                 while ( $row = $wgDatabase->fetchObject( $res ) ) {
730                         $count = ($count + 1) % 100;
731                         if ( $count == 0 ) {
732                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
733                                         wfWaitForSlaves( 10 );
734                                 } else {
735                                         sleep( 1 );
736                                 }
737                         }
738                         $wgDatabase->insert( 'templatelinks',
739                                 array(
740                                         'tl_from' => $row->pl_from,
741                                         'tl_namespace' => $row->pl_namespace,
742                                         'tl_title' => $row->pl_title,
743                                 ), $fname
744                         );
746                 }
747                 $wgDatabase->freeResult( $res );
748         } else {
749                 // Fast update
750                 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
751                         array(
752                                 'tl_from' => 'pl_from',
753                                 'tl_namespace' => 'pl_namespace',
754                                 'tl_title' => 'pl_title'
755                         ), array(
756                                 'pl_namespace' => 10
757                         ), $fname
758                 );
759         }
760         echo "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n";
763 function do_all_updates( $doShared = false ) {
764         global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgDatabase;
766         $doUser = !$wgSharedDB || $doShared;
768         # Rename tables
769         foreach ( $wgRenamedTables as $tableRecord ) {
770                 rename_table( $tableRecord[0], $tableRecord[1], $tableRecord[2] );
771         }
773         # Add missing tables
774         foreach ( $wgNewTables as $tableRecord ) {
775                 add_table( $tableRecord[0], $tableRecord[1] );
776                 flush();
777         }
779         # Add missing fields
780         foreach ( $wgNewFields as $fieldRecord ) {
781                 if ( $fieldRecord[0] != 'user' || $doUser ) {
782                         add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2] );
783                 }
784                 flush();
785         }
787         # Do schema updates which require special handling
788         do_interwiki_update(); flush();
789         do_index_update(); flush();
790         do_old_links_update(); flush();
791         do_image_name_unique_update(); flush();
792         do_watchlist_update(); flush();
793         if ( $doUser ) {
794                 do_user_update(); flush();
795         }
796 ######  do_copy_newtalk_to_watchlist(); flush();
797         do_logging_encoding(); flush();
799         do_schema_restructuring(); flush();
800         do_inverse_timestamp(); flush();
801         do_text_id(); flush();
802         do_namespace_size(); flush();
804         do_pagelinks_update(); flush();
805         do_templatelinks_update(); flush(); // after pagelinks
807         do_drop_img_type(); flush();
809         if ( $doUser ) {
810                 do_user_unique_update(); flush();
811         }
812         do_user_groups_update(); flush();
814         do_watchlist_null(); flush();
816         //do_image_index_update(); flush();
818         do_logging_timestamp_index(); flush();
820         do_page_random_update(); flush();
822         initialiseMessages(); flush();
825 function archive($name) {
826         global $wgDBtype, $IP;
827         switch ($wgDBtype) {
828         case "oracle":
829                 return "$IP/maintenance/oracle/archives/$name";
830         default:
831                 return "$IP/maintenance/archives/$name";
832         }