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