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