3 * @addtogroup Maintenance
8 if ( !defined( 'MEDIAWIKI' ) ) {
9 echo "This file is not a valid entry point\n";
13 require_once 'convertLinks.inc';
14 require_once 'userDupes.inc';
15 require_once 'deleteDefaultMessages.php';
17 $wgRenamedTables = array(
19 # array( 'group', 'groups', 'patch-rename-group.sql' ),
23 # table patch file (in maintenance/archives)
24 array( 'hitcounter', 'patch-hitcounter.sql' ),
25 array( 'querycache', 'patch-querycache.sql' ),
26 array( 'objectcache', 'patch-objectcache.sql' ),
27 array( 'categorylinks', 'patch-categorylinks.sql' ),
28 array( 'logging', 'patch-logging.sql' ),
29 array( 'user_newtalk', 'patch-usernewtalk2.sql' ),
30 array( 'transcache', 'patch-transcache.sql' ),
31 array( 'trackbacks', 'patch-trackbacks.sql' ),
32 array( 'externallinks', 'patch-externallinks.sql' ),
33 array( 'job', 'patch-job.sql' ),
34 array( 'langlinks', 'patch-langlinks.sql' ),
35 array( 'querycache_info', 'patch-querycacheinfo.sql' ),
36 array( 'filearchive', 'patch-filearchive.sql' ),
37 array( 'querycachetwo', 'patch-querycachetwo.sql' ),
41 # table field patch file (in maintenance/archives)
42 array( 'ipblocks', 'ipb_id', 'patch-ipblocks.sql' ),
43 array( 'ipblocks', 'ipb_expiry', 'patch-ipb_expiry.sql' ),
44 array( 'recentchanges', 'rc_type', 'patch-rc_type.sql' ),
45 array( 'recentchanges', 'rc_ip', 'patch-rc_ip.sql' ),
46 array( 'recentchanges', 'rc_id', 'patch-rc_id.sql' ),
47 array( 'recentchanges', 'rc_patrolled', 'patch-rc-patrol.sql' ),
48 array( 'recentchanges', 'rc_old_len', 'patch-rc_len.sql' ),
49 array( 'user', 'user_real_name', 'patch-user-realname.sql' ),
50 array( 'user', 'user_token', 'patch-user_token.sql' ),
51 array( 'user', 'user_email_token', 'patch-user_email_token.sql' ),
52 array( 'user', 'user_registration','patch-user_registration.sql' ),
53 array( 'logging', 'log_params', 'patch-log_params.sql' ),
54 array( 'archive', 'ar_rev_id', 'patch-archive-rev_id.sql' ),
55 array( 'archive', 'ar_text_id', 'patch-archive-text_id.sql' ),
56 array( 'page', 'page_len', 'patch-page_len.sql' ),
57 array( 'revision', 'rev_deleted', 'patch-rev_deleted.sql' ),
58 array( 'image', 'img_width', 'patch-img_width.sql' ),
59 array( 'image', 'img_metadata', 'patch-img_metadata.sql' ),
60 array( 'image', 'img_media_type', 'patch-img_media_type.sql' ),
61 array( 'site_stats', 'ss_total_pages', 'patch-ss_total_articles.sql' ),
62 array( 'interwiki', 'iw_trans', 'patch-interwiki-trans.sql' ),
63 array( 'ipblocks', 'ipb_range_start', 'patch-ipb_range_start.sql' ),
64 array( 'site_stats', 'ss_images', 'patch-ss_images.sql' ),
65 array( 'ipblocks', 'ipb_anon_only', 'patch-ipb_anon_only.sql' ),
66 array( 'ipblocks', 'ipb_enable_autoblock', 'patch-ipb_optional_autoblock.sql' ),
67 array( 'user', 'user_newpass_time','patch-user_newpass_time.sql' ),
68 array( 'user', 'user_editcount', 'patch-user_editcount.sql' ),
69 array( 'recentchanges', 'rc_deleted', 'patch-rc_deleted.sql' ),
70 array( 'logging', 'log_id', 'patch-log_id.sql' ),
71 array( 'logging', 'log_deleted', 'patch-log_deleted.sql' ),
72 array( 'archive', 'ar_deleted', 'patch-ar_deleted.sql' ),
73 array( 'ipblocks', 'ipb_deleted', 'patch-ipb_deleted.sql' ),
74 array( 'filearchive', 'fa_deleted', 'patch-fa_deleted.sql' ),
75 array( 'revision', 'rev_len', 'patch-rev_len.sql' ),
76 array( 'archive', 'ar_len', 'patch-ar_len.sql' ),
77 array( 'revision', 'rev_parent_id', 'patch-rev_parent_id.sql' ),
78 array( 'page_restrictions', 'pr_id', 'patch-page_restrictions_sortkey.sql' ),
79 array( 'ipblocks', 'ipb_block_email', 'patch-ipb_emailban.sql' ),
82 function rename_table( $from, $to, $patch ) {
84 if ( $wgDatabase->tableExists( $from ) ) {
85 if ( $wgDatabase->tableExists( $to ) ) {
86 echo "...can't move table $from to $to, $to already exists.\n";
88 echo "Moving table $from to $to...";
89 dbsource( archive($patch), $wgDatabase );
93 // Source table does not exist
94 // Renames are done before creations, so this is typical for a new installation
99 function add_table( $name, $patch ) {
101 if ( $wgDatabase->tableExists( $name ) ) {
102 echo "...$name table already exists.\n";
104 echo "Creating $name table...";
105 dbsource( archive($patch), $wgDatabase );
110 function add_field( $table, $field, $patch ) {
112 if ( !$wgDatabase->tableExists( $table ) ) {
113 echo "...$table table does not exist, skipping new field patch\n";
114 } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
115 echo "...have $field field in $table table.\n";
117 echo "Adding $field field to table $table...";
118 dbsource( archive($patch) , $wgDatabase );
123 function do_revision_updates() {
124 global $wgSoftwareRevision;
125 if ( $wgSoftwareRevision < 1001 ) {
130 function update_passwords() {
131 wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
134 $fname = "Update script: update_passwords()";
135 print "\nIt appears that you need to update the user passwords in your\n" .
136 "database. If you have already done this (if you've run this update\n" .
137 "script once before, for example), doing so again will make all your\n" .
138 "user accounts inaccessible, so be sure you only do this once.\n" .
139 "Update user passwords? (yes/no)";
141 $resp = readconsole();
142 if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
144 $sql = "SELECT user_id,user_password FROM user";
145 $source = $wgDatabase->query( $sql, $fname );
147 while ( $row = $wgDatabase->fetchObject( $source ) ) {
149 $oldpass = $row->user_password;
150 $newpass = md5( "{$id}-{$oldpass}" );
152 $sql = "UPDATE user SET user_password='{$newpass}' " .
153 "WHERE user_id={$id}";
154 $wgDatabase->query( $sql, $fname );
158 function do_interwiki_update() {
159 # Check that interwiki table exists; if it doesn't source it
160 global $wgDatabase, $IP;
161 if( $wgDatabase->tableExists( "interwiki" ) ) {
162 echo "...already have interwiki table\n";
165 echo "Creating interwiki table: ";
166 dbsource( archive("patch-interwiki.sql") );
168 echo "Adding default interwiki definitions: ";
169 dbsource( "$IP/maintenance/interwiki.sql" );
173 function do_index_update() {
174 # Check that proper indexes are in place
176 $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
177 if( !$meta->isMultipleKey() ) {
178 echo "Updating indexes to 20031107: ";
179 dbsource( archive("patch-indexes.sql") );
183 echo "...indexes seem up to 20031107 standards\n";
187 function do_image_index_update() {
190 $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
191 if( !$meta->isMultipleKey() ) {
192 echo "Updating indexes to 20050912: ";
193 dbsource( archive("patch-mimesearch-indexes.sql") );
197 echo "...indexes seem up to 20050912 standards\n";
201 function do_image_name_unique_update() {
203 if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
204 echo "...image primary key already set.\n";
206 echo "Making img_name the primary key... ";
207 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
212 function do_logging_timestamp_index() {
214 if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
215 echo "...timestamp key on logging already exists.\n";
217 echo "Adding timestamp key on logging table... ";
218 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
224 function do_watchlist_update() {
226 $fname = 'do_watchlist_update';
227 if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
228 echo "The watchlist table is already set up for email notification.\n";
230 echo "Adding wl_notificationtimestamp field for email notification management.";
231 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
232 dbsource( archive( 'patch-email-notification.sql' ), $wgDatabase );
235 # Check if we need to add talk page rows to the watchlist
236 $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
237 $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
238 if ( $talk != $nontalk ) {
239 echo "Adding missing watchlist talk page rows... ";
242 $wgDatabase->insertSelect( 'watchlist', 'watchlist',
244 'wl_user' => 'wl_user',
245 'wl_namespace' => 'wl_namespace | 1',
246 'wl_title' => 'wl_title',
247 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
248 ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
251 echo "...watchlist talk page rows already present\n";
255 function do_copy_newtalk_to_watchlist() {
257 global $wgCommandLineMode; # this needs to be saved while getID() and getName() are called
259 $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
260 $wgDatabase->tableName( 'user_newtalk' ) );
261 $num_newtalks=$wgDatabase->numRows($res);
262 echo "Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
265 for ( $i = 1; $i <= $num_newtalks; $i++ ) {
266 $wluser = $wgDatabase->fetchObject( $res );
267 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
268 if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
269 $wgDatabase->replace( 'watchlist',
270 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
271 array('wl_user' => 0,
272 'wl_namespace' => NS_USER_TALK,
273 'wl_title' => $wluser->user_ip,
274 'wl_notificationtimestamp' => '19700101000000'
275 ), 'updaters.inc::do_watchlist_update2'
278 } else { # normal users ... have user_ids
279 $user->setID($wluser->user_id);
280 $wgDatabase->replace( 'watchlist',
281 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
282 array('wl_user' => $user->getID(),
283 'wl_namespace' => NS_USER_TALK,
284 'wl_title' => $user->getName(),
285 'wl_notificationtimestamp' => '19700101000000'
286 ), 'updaters.inc::do_watchlist_update3'
294 function do_user_update() {
296 if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
297 echo "User table contains old email authentication field. Dropping... ";
298 dbsource( archive( 'patch-email-authentication.sql' ), $wgDatabase );
301 echo "...user table does not contain old email authentication field.\n";
306 * 1.4 betas were missing the 'binary' marker from logging.log_title,
307 * which causes a collation mismatch error on joins in MySQL 4.1.
309 function do_logging_encoding() {
310 global $wgDatabase, $wgDBtype;
311 if ($wgDBtype != 'mysql')
313 $logging = $wgDatabase->tableName( 'logging' );
314 $res = $wgDatabase->query( "SELECT log_title FROM $logging LIMIT 0" );
315 $flags = explode( ' ', mysql_field_flags( $res, 0 ) );
316 $wgDatabase->freeResult( $res );
318 if( in_array( 'binary', $flags ) ) {
319 echo "Logging table has correct title encoding.\n";
321 echo "Fixing title encoding on logging table... ";
322 dbsource( archive( 'patch-logging-title.sql' ), $wgDatabase );
327 function do_schema_restructuring() {
329 $fname="do_schema_restructuring";
330 if ( $wgDatabase->tableExists( 'page' ) ) {
331 echo "...page table already exists.\n";
333 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
334 echo wfTimestamp( TS_DB );
335 echo "......checking for duplicate entries.\n"; flush();
337 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
339 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
340 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
342 if ( $wgDatabase->numRows( $rows ) > 0 ) {
343 echo wfTimestamp( TS_DB );
344 echo "......<b>Found duplicate entries</b>\n";
345 echo ( sprintf( "<b> %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
346 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
347 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
348 $duplicate[$row->cur_namespace] = array();
350 $duplicate[$row->cur_namespace][] = $row->cur_title;
351 echo ( sprintf( " %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
353 $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
355 foreach ( $duplicate as $ns => $titles ) {
361 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
363 foreach ( $titles as $t ) {
365 $sql .= $wgDatabase->addQuotes( $t );
368 $sql .= ', ' . $wgDatabase->addQuotes( $t );
373 # By sorting descending, the most recent entry will be the first in the list.
374 # All following entries will be deleted by the next while-loop.
375 $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
377 $rows = $wgDatabase->query( $sql, $fname );
379 $prev_title = $prev_namespace = false;
382 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
383 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
384 $deleteId[] = $row->cur_id;
386 $prev_title = $row->cur_title;
387 $prev_namespace = $row->cur_namespace;
389 $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
390 $rows = $wgDatabase->query( $sql, $fname );
391 echo wfTimestamp( TS_DB );
392 echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
396 echo wfTimestamp( TS_DB );
397 echo "......Creating tables.\n";
398 $wgDatabase->query("CREATE TABLE $page (
399 page_id int(8) unsigned NOT NULL auto_increment,
400 page_namespace int NOT NULL,
401 page_title varchar(255) binary NOT NULL,
402 page_restrictions tinyblob NOT NULL,
403 page_counter bigint(20) unsigned NOT NULL default '0',
404 page_is_redirect tinyint(1) unsigned NOT NULL default '0',
405 page_is_new tinyint(1) unsigned NOT NULL default '0',
406 page_random real unsigned NOT NULL,
407 page_touched char(14) binary NOT NULL default '',
408 page_latest int(8) unsigned NOT NULL,
409 page_len int(8) unsigned NOT NULL,
411 PRIMARY KEY page_id (page_id),
412 UNIQUE INDEX name_title (page_namespace,page_title),
415 ) TYPE=InnoDB", $fname );
416 $wgDatabase->query("CREATE TABLE $revision (
417 rev_id int(8) unsigned NOT NULL auto_increment,
418 rev_page int(8) unsigned NOT NULL,
419 rev_comment tinyblob NOT NULL,
420 rev_user int(5) unsigned NOT NULL default '0',
421 rev_user_text varchar(255) binary NOT NULL default '',
422 rev_timestamp char(14) binary NOT NULL default '',
423 rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
424 rev_deleted tinyint(1) unsigned NOT NULL default '0',
425 rev_len int(8) unsigned,
426 rev_parent_id int(8) unsigned default NULL,
427 PRIMARY KEY rev_page_id (rev_page, rev_id),
428 UNIQUE INDEX rev_id (rev_id),
429 INDEX rev_timestamp (rev_timestamp),
430 INDEX page_timestamp (rev_page,rev_timestamp),
431 INDEX user_timestamp (rev_user,rev_timestamp),
432 INDEX usertext_timestamp (rev_user_text,rev_timestamp)
433 ) TYPE=InnoDB", $fname );
435 echo wfTimestamp( TS_DB );
436 echo "......Locking tables.\n";
437 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
439 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
440 echo wfTimestamp( TS_DB );
441 echo "......maxold is {$maxold}\n";
443 echo wfTimestamp( TS_DB );
444 global $wgLegacySchemaConversion;
445 if( $wgLegacySchemaConversion ) {
446 // Create HistoryBlobCurStub entries.
447 // Text will be pulled from the leftover 'cur' table at runtime.
448 echo "......Moving metadata from cur; using blob references to text in cur table.\n";
449 $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
450 $cur_flags = "'object'";
452 // Copy all cur text in immediately: this may take longer but avoids
453 // having to keep an extra table around.
454 echo "......Moving text from cur.\n";
455 $cur_text = 'cur_text';
458 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
459 old_timestamp, old_minor_edit, old_flags)
460 SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
461 FROM $cur", $fname );
463 echo wfTimestamp( TS_DB );
464 echo "......Setting up revision table.\n";
465 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
467 SELECT old_id, cur_id, old_comment, old_user, old_user_text,
468 old_timestamp, old_minor_edit
469 FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
471 echo wfTimestamp( TS_DB );
472 echo "......Setting up page table.\n";
473 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
474 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
475 SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
476 cur_random, cur_touched, rev_id, LENGTH(cur_text)
478 WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
480 echo wfTimestamp( TS_DB );
481 echo "......Unlocking tables.\n";
482 $wgDatabase->query( "UNLOCK TABLES", $fname );
484 echo wfTimestamp( TS_DB );
485 echo "......Renaming old.\n";
486 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
488 echo wfTimestamp( TS_DB );
493 function do_inverse_timestamp() {
495 if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
496 echo "Removing revision.inverse_timestamp and fixing indexes... ";
497 dbsource( archive( 'patch-inverse_timestamp.sql' ), $wgDatabase );
500 echo "revision timestamp indexes already up to 2005-03-13\n";
504 function do_text_id() {
506 if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
507 echo "...rev_text_id already in place.\n";
509 echo "Adding rev_text_id field... ";
510 dbsource( archive( 'patch-rev_text_id.sql' ), $wgDatabase );
515 function do_namespace_size() {
519 'recentchanges' => 'rc',
521 'querycache' => 'qc',
524 foreach( $tables as $table => $prefix ) {
525 do_namespace_size_on( $table, $prefix );
530 function do_namespace_size_on( $table, $prefix ) {
531 global $wgDatabase, $wgDBtype;
532 if ($wgDBtype != 'mysql')
534 $field = $prefix . '_namespace';
536 $tablename = $wgDatabase->tableName( $table );
537 $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
538 $info = $wgDatabase->fetchObject( $result );
539 $wgDatabase->freeResult( $result );
541 if( substr( $info->Type, 0, 3 ) == 'int' ) {
542 echo "...$field is already a full int ($info->Type).\n";
544 echo "Promoting $field from $info->Type to int... ";
546 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
547 $wgDatabase->query( $sql );
553 function do_pagelinks_update() {
555 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
556 echo "...already have pagelinks table.\n";
558 echo "Converting links and brokenlinks tables to pagelinks... ";
559 dbsource( archive( 'patch-pagelinks.sql' ), $wgDatabase );
563 global $wgCanonicalNamespaceNames;
564 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
566 do_pagelinks_namespace( $ns );
572 function do_pagelinks_namespace( $namespace ) {
573 global $wgDatabase, $wgContLang;
575 $ns = intval( $namespace );
576 echo "Cleaning up broken links for namespace $ns... ";
578 $pagelinks = $wgDatabase->tableName( 'pagelinks' );
579 $name = $wgContLang->getNsText( $ns );
580 $prefix = $wgDatabase->strencode( $name );
581 $likeprefix = str_replace( '_', '\\_', $prefix);
583 $sql = "UPDATE $pagelinks
584 SET pl_namespace=$ns,
585 pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
587 AND pl_title LIKE '$likeprefix:%'";
589 $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
593 function do_drop_img_type() {
596 if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
597 echo "Dropping unused img_type field in image table... ";
598 dbsource( archive( 'patch-drop_img_type.sql' ), $wgDatabase );
601 echo "No img_type field in image table; Good.\n";
605 function do_old_links_update() {
607 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
608 echo "Already have pagelinks; skipping old links table updates.\n";
610 convertLinks(); flush();
614 function do_user_unique_update() {
616 $duper = new UserDupes( $wgDatabase );
617 if( $duper->hasUniqueIndex() ) {
618 echo "Already have unique user_name index.\n";
620 if( !$duper->clearDupes() ) {
621 echo "WARNING: This next step will probably fail due to unfixed duplicates...\n";
623 echo "Adding unique index on user_name... ";
624 dbsource( archive( 'patch-user_nameindex.sql' ), $wgDatabase );
629 function do_user_groups_update() {
630 $fname = 'do_user_groups_update';
633 if( $wgDatabase->tableExists( 'user_groups' ) ) {
634 echo "...user_groups table already exists.\n";
635 return do_user_groups_reformat();
638 echo "Adding user_groups table... ";
639 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
642 if( !$wgDatabase->tableExists( 'user_rights' ) ) {
643 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
644 echo "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion...";
645 dbsource( archive( 'patch-user_rights.sql' ), $wgDatabase );
648 echo "*** WARNING: couldn't locate user_rights table or field for upgrade.\n";
649 echo "*** You may need to manually configure some sysops by manipulating\n";
650 echo "*** the user_groups table.\n";
655 echo "Converting user_rights table to user_groups... ";
656 $result = $wgDatabase->select( 'user_rights',
657 array( 'ur_user', 'ur_rights' ),
658 array( "ur_rights != ''" ),
661 while( $row = $wgDatabase->fetchObject( $result ) ) {
662 $groups = array_unique(
664 explode( ',', $row->ur_rights ) ) );
666 foreach( $groups as $group ) {
667 $wgDatabase->insert( 'user_groups',
669 'ug_user' => $row->ur_user,
670 'ug_group' => $group ),
674 $wgDatabase->freeResult( $result );
678 function do_user_groups_reformat() {
679 # Check for bogus formats from previous 1.5 alpha code.
681 $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
683 if( $info->type() == 'int' ) {
684 $oldug = $wgDatabase->tableName( 'user_groups' );
685 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
686 echo "user_groups is in bogus intermediate format. Renaming to $newug... ";
687 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
690 echo "Re-adding fresh user_groups table... ";
691 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
695 echo "*** WARNING: You will need to manually fix up user permissions in the user_groups\n";
696 echo "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n";
699 echo "...user_groups is in current format.\n";
704 function do_watchlist_null() {
705 # Make sure wl_notificationtimestamp can be NULL,
706 # and update old broken items.
708 $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
710 if( !$info->nullable() ) {
711 echo "Making wl_notificationtimestamp nullable... ";
712 dbsource( archive( 'patch-watchlist-null.sql' ), $wgDatabase );
715 echo "...wl_notificationtimestamp is already nullable.\n";
723 function do_page_random_update() {
726 echo "Setting page_random to a random value on rows where it equals 0...";
728 $page = $wgDatabase->tableName( 'page' );
729 $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
730 $rows = $wgDatabase->affectedRows();
732 echo "changed $rows rows\n";
735 function do_templatelinks_update() {
736 global $wgDatabase, $wgLoadBalancer;
737 $fname = 'do_templatelinks_update';
739 if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
740 echo "...templatelinks table already exists\n";
743 echo "Creating templatelinks table...\n";
744 dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
745 echo "Populating...\n";
746 if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
747 // Slow, replication-friendly update
748 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
749 array( 'pl_namespace' => NS_TEMPLATE ), $fname );
751 while ( $row = $wgDatabase->fetchObject( $res ) ) {
752 $count = ($count + 1) % 100;
754 if ( function_exists( 'wfWaitForSlaves' ) ) {
755 wfWaitForSlaves( 10 );
760 $wgDatabase->insert( 'templatelinks',
762 'tl_from' => $row->pl_from,
763 'tl_namespace' => $row->pl_namespace,
764 'tl_title' => $row->pl_title,
769 $wgDatabase->freeResult( $res );
772 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
774 'tl_from' => 'pl_from',
775 'tl_namespace' => 'pl_namespace',
776 'tl_title' => 'pl_title'
782 echo "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n";
786 # Add ( rc_namespace, rc_user_text ) index [R. Church]
787 function do_rc_indices_update() {
789 echo( "Checking for additional recent changes indices...\n" );
790 # See if we can find the index we want
791 $info = $wgDatabase->indexInfo( 'recentchanges', 'rc_ns_usertext', __METHOD__ );
794 echo( "...index on ( rc_namespace, rc_user_text ) not found; creating\n" );
795 dbsource( archive( 'patch-recentchanges-utindex.sql' ) );
797 # Index seems to exist
798 echo( "...index on ( rc_namespace, rc_user_text ) seems to be ok\n" );
801 #Add (rc_user_text, rc_timestamp) index [A. Garrett], November 2006
802 # See if we can find the index we want
803 $info = $wgDatabase->indexInfo( 'recentchanges', 'rc_user_text', __METHOD__ );
806 echo( "...index on ( rc_user_text, rc_timestamp ) not found; creating\n" );
807 dbsource( archive( 'patch-rc_user_text-index.sql' ) );
809 # Index seems to exist
810 echo( "...index on ( rc_user_text, rc_timestamp ) seems to be ok\n" );
814 function index_has_field($table, $index, $field) {
816 echo( "Checking if $table index $index includes field $field...\n" );
817 $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
819 foreach($info as $row) {
820 if($row->Column_name == $field) {
821 echo( "...index $index on table $table seems to be ok\n" );
826 echo( "...index $index on table $table has no field $field; adding\n" );
830 function do_backlinking_indices_update() {
831 echo( "Checking for backlinking indices...\n" );
832 if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
833 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
834 !index_has_field('imagelinks', 'il_to', 'il_from'))
836 dbsource( archive( 'patch-backlinkindexes.sql' ) );
840 function do_stats_init() {
841 // Sometimes site_stats table is not properly populated.
843 echo "Checking site_stats row...";
844 $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
845 if( $row === false ) {
846 echo "data is missing! rebuilding...\n";
849 require_once "$IP/maintenance/initStats.inc";
856 function purge_cache() {
858 # We can't guarantee that the user will be able to use TRUNCATE,
859 # but we know that DELETE is available to us
860 echo( "Purging caches..." );
861 $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
865 function do_all_updates( $shared = false, $purge = true ) {
866 global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgDatabase, $wgDBtype, $IP;
868 $doUser = !$wgSharedDB || $shared;
870 if ($wgDBtype === 'postgres') {
871 do_postgres_updates();
876 foreach ( $wgRenamedTables as $tableRecord ) {
877 rename_table( $tableRecord[0], $tableRecord[1], $tableRecord[2] );
881 foreach ( $wgNewTables as $tableRecord ) {
882 add_table( $tableRecord[0], $tableRecord[1] );
887 foreach ( $wgNewFields as $fieldRecord ) {
888 if ( $fieldRecord[0] != 'user' || $doUser ) {
889 add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2] );
894 # Do schema updates which require special handling
895 do_interwiki_update(); flush();
896 do_index_update(); flush();
897 do_old_links_update(); flush();
898 do_image_name_unique_update(); flush();
899 do_watchlist_update(); flush();
901 do_user_update(); flush();
903 ###### do_copy_newtalk_to_watchlist(); flush();
904 do_logging_encoding(); flush();
906 do_schema_restructuring(); flush();
907 do_inverse_timestamp(); flush();
908 do_text_id(); flush();
909 do_namespace_size(); flush();
911 do_pagelinks_update(); flush();
912 do_templatelinks_update(); flush(); // after pagelinks
914 do_drop_img_type(); flush();
917 do_user_unique_update(); flush();
919 do_user_groups_update(); flush();
921 do_watchlist_null(); flush();
923 //do_image_index_update(); flush();
925 do_logging_timestamp_index(); flush();
927 do_page_random_update(); flush();
929 do_rc_indices_update(); flush();
931 add_table( 'redirect', 'patch-redirect.sql' );
933 do_backlinking_indices_update(); flush();
935 do_restrictions_update(); flush ();
937 echo "Deleting old default messages (this may take a long time!)..."; flush();
938 deleteDefaultMessages();
939 echo "Done\n"; flush();
941 do_stats_init(); flush();
949 function archive($name) {
950 global $wgDBtype, $IP;
953 return "$IP/maintenance/postgres/archives/$name";
955 return "$IP/maintenance/archives/$name";
959 function do_restrictions_update() {
960 # Adding page_restrictions table, obsoleting page.page_restrictions.
961 # Migrating old restrictions to new table
962 # -- Andrew Garrett, January 2007.
966 $name = 'page_restrictions';
967 $patch = 'patch-page_restrictions.sql';
968 $patch2 = 'patch-page_restrictions_sortkey.sql';
970 if ( $wgDatabase->tableExists( $name ) ) {
971 echo "...$name table already exists.\n";
973 echo "Creating $name table...";
974 dbsource( archive($patch), $wgDatabase );
975 dbsource( archive($patch2), $wgDatabase );
978 echo "Migrating old restrictions to new table...";
980 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
984 while ($row = $wgDatabase->fetchObject($res) ) {
985 $count = ($count + 1) % 100;
988 if ( function_exists( 'wfWaitForSlaves' ) ) {
989 wfWaitForSlaves( 10 );
995 # Figure out what the restrictions are..
997 $flatrestrictions = explode( ':', $row->page_restrictions );
999 $restrictions = array ();
1000 foreach( $flatrestrictions as $restriction ) {
1001 $thisrestriction = explode( '=', $restriction, 2 );
1002 if( count( $thisrestriction ) == 1 ) {
1003 // Compatibility with old protections from before
1004 // separate move protection was added.
1005 list( $level ) = $thisrestriction;
1007 $restrictions['edit'] = $level;
1008 $restrictions['move'] = $level;
1011 list( $type, $level ) = $thisrestriction;
1013 $restrictions[$type] = $level;
1017 $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1021 foreach( $restrictions as $type => $level ) {
1022 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1024 'pr_level' => $level,
1026 'pr_expiry' => 'infinity' ),
1036 pg_describe_table($table)
1038 global $wgDatabase, $wgDBmwschema;
1040 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1041 WHERE pg_class.relnamespace = pg_namespace.oid
1042 AND attrelid=pg_class.oid AND attnum > 0
1043 AND relname=%s AND nspname=%s
1045 $res = $wgDatabase->query(sprintf($q,
1046 $wgDatabase->addQuotes($table),
1047 $wgDatabase->addQuotes($wgDBmwschema)));
1052 while ($r = $wgDatabase->fetchRow($res)) {
1062 pg_describe_index($idx)
1064 global $wgDatabase, $wgDBmwschema;
1066 // first fetch the key (which is a list of columns ords) and
1067 // the table the index applies to (an oid)
1069 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1071 AND pg_class.relnamespace = pg_namespace.oid
1073 AND indexrelid=pg_class.oid
1075 $res = $wgDatabase->query(sprintf($q,
1076 $wgDatabase->addQuotes($wgDBmwschema),
1077 $wgDatabase->addQuotes($idx)));
1080 if (!($r = $wgDatabase->fetchRow($res))) {
1081 $wgDatabase->freeResult($res);
1086 $relid = intval($r[1]);
1087 $indkeys = explode(" ", $indkey);
1088 $wgDatabase->freeResult($res);
1090 $colnames = array();
1091 foreach ($indkeys as $rid) {
1093 SELECT attname FROM pg_class, pg_attribute
1094 WHERE attrelid=$relid
1096 AND attrelid=pg_class.oid
1098 $r2 = $wgDatabase->query(sprintf($query, $rid));
1101 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1102 $wgDatabase->freeResult($r2);
1105 $colnames[] = $row2[0];
1106 $wgDatabase->freeResult($r2);
1113 pg_index_exists($table, $index)
1115 global $wgDatabase, $wgDBmwschema;
1116 $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1117 array( "indexname" => $index,
1118 "tablename" => $table,
1119 "schemaname" => $wgDBmwschema));
1120 return $exists === $index;
1124 pg_fkey_deltype($fkey)
1126 global $wgDatabase, $wgDBmwschema;
1128 SELECT confdeltype FROM pg_constraint, pg_namespace
1129 WHERE connamespace=pg_namespace.oid
1133 $r = $wgDatabase->query(sprintf($q,
1134 $wgDatabase->addQuotes($wgDBmwschema),
1135 $wgDatabase->addQuotes($fkey)));
1136 if (!($row = $wgDatabase->fetchRow($r)))
1142 pg_rule_def($table, $rule)
1144 global $wgDatabase, $wgDBmwschema;
1146 SELECT definition FROM pg_rules
1147 WHERE schemaname = %s
1151 $r = $wgDatabase->query(sprintf($q,
1152 $wgDatabase->addQuotes($wgDBmwschema),
1153 $wgDatabase->addQuotes($table),
1154 $wgDatabase->addQuotes($rule)));
1155 $row = $wgDatabase->fetchRow($r);
1159 $wgDatabase->freeResult($r);
1163 function do_postgres_updates() {
1164 global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1166 $wgShowExceptionDetails = 1;
1168 # Just in case their LocalSettings.php does not have this:
1169 if ( !isset( $wgDBmwschema ))
1170 $wgDBmwschema = 'mediawiki';
1172 # Verify that this user is configured correctly
1173 $safeuser = $wgDatabase->addQuotes($wgDBuser);
1174 $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_user WHERE usename = $safeuser";
1175 $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1177 foreach( explode( '*', $config ) as $c ) {
1178 list( $x,$y ) = explode( '=', $c );
1182 if( !array_key_exists( 'search_path', $conf ) or strpos( $conf['search_path'],$wgDBmwschema ) === false ) {
1183 print "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n";
1184 $newpath[$wgDBmwschema] = 1;
1186 if( !array_key_exists( 'search_path', $conf ) or strpos( $conf['search_path'],$wgDBts2schema ) === false ) {
1187 print "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n";
1188 $newpath[$wgDBts2schema] = 1;
1190 $searchpath = implode( ',', array_keys( $newpath ) );
1191 if( strlen( $searchpath ) ) {
1192 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $searchpath" );
1195 'client_min_messages' => 'error',
1196 'DateStyle' => 'ISO, YMD',
1199 foreach( array_keys( $goodconf ) AS $key ) {
1200 $value = $goodconf[$key];
1201 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1202 print "Setting $key to '$value' for user \"$wgDBuser\"\n";
1203 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1207 $newsequences = array(
1213 array("mediawiki_version", "patch-mediawiki_version.sql"),
1214 array("mwuser", "patch-mwuser.sql"),
1215 array("pagecontent", "patch-pagecontent.sql"),
1216 array("querycachetwo", "patch-querycachetwo.sql"),
1217 array("page_restrictions", "patch-page_restrictions.sql"),
1218 array("profiling", "patch-profiling.sql"),
1219 array("redirect", "patch-redirect.sql"),
1223 array("archive", "ar_len", "INTEGER"),
1224 array("ipblocks", "ipb_anon_only", "CHAR NOT NULL DEFAULT '0'"),
1225 array("ipblocks", "ipb_create_account", "CHAR NOT NULL DEFAULT '1'"),
1226 array("ipblocks", "ipb_deleted", "INTEGER NOT NULL DEFAULT 0"),
1227 array("ipblocks", "ipb_enable_autoblock", "CHAR NOT NULL DEFAULT '1'"),
1228 array("filearchive", "fa_deleted", "INTEGER NOT NULL DEFAULT 0"),
1229 array("logging", "log_deleted", "INTEGER NOT NULL DEFAULT 0"),
1230 array("logging", "log_id", "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1231 array("logging", "log_params", "TEXT"),
1232 array("mwuser", "user_editcount", "INTEGER"),
1233 array("mwuser", "user_newpass_time", "TIMESTAMPTZ"),
1234 array("page_restrictions", "pr_id", "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1235 array("recentchanges", "rc_deleted", "INTEGER NOT NULL DEFAULT 0"),
1236 array("recentchanges", "rc_log_action", "TEXT"),
1237 array("recentchanges", "rc_log_type", "TEXT"),
1238 array("recentchanges", "rc_logid", "INTEGER NOT NULL DEFAULT 0"),
1239 array("recentchanges", "rc_new_len", "INTEGER"),
1240 array("recentchanges", "rc_old_len", "INTEGER"),
1241 array("recentchanges", "rc_params", "TEXT"),
1242 array("revision", "rev_len", "INTEGER"),
1246 # table, column, desired type, USING clause if needed
1247 $typechanges = array(
1248 array("image", "img_size", "int4", ""),
1249 array("image", "img_width", "int4", ""),
1250 array("image", "img_height", "int4", ""),
1251 array("ipblocks", "ipb_address", "text", "ipb_address::text"),
1252 array("math", "math_inputhash", "bytea", "decode(math_inputhash,'escape')"),
1253 array("math", "math_outputhash", "bytea", "decode(math_outputhash,'escape')"),
1254 array("oldimage", "oi_size", "int4", ""),
1255 array("oldimage", "oi_width", "int4", ""),
1256 array("oldimage", "oi_height", "int4", ""),
1257 array("user_newtalk", "user_ip", "text", "host(user_ip)"),
1260 $newindexes = array(
1261 array("revision", "rev_text_id_idx", "patch-rev_text_id_idx.sql")
1267 foreach ($newsequences as $ns) {
1268 if ($wgDatabase->sequenceExists($ns)) {
1269 echo "... sequence $ns already exists\n";
1273 echo "... create sequence $ns\n";
1274 $wgDatabase->query("CREATE SEQUENCE $ns");
1277 foreach ($newtables as $nt) {
1278 if ($wgDatabase->tableExists($nt[0])) {
1279 echo "... table $nt[0] already exists\n";
1283 echo "... create table $nt[0]\n";
1284 dbsource(archive($nt[1]));
1287 ## Needed before newcols
1288 if ($wgDatabase->tableExists("archive2")) {
1289 echo "... convert archive2 back to normal archive table\n";
1290 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1291 echo "... drop rule archive_insert\n";
1292 $wgDatabase->query("DROP RULE archive_insert ON archive");
1294 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1295 echo "... drop rule archive_delete\n";
1296 $wgDatabase->query("DROP RULE archive_delete ON archive");
1299 dbsource(archive("patch-remove-archive2.sql"));
1301 echo "... obsolete archive2 not present\n";
1303 foreach ($newcols as $nc) {
1304 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1305 if (!is_null($fi)) {
1306 echo "... column $nc[0].$nc[1] already exists\n";
1310 echo "... add column $nc[0].$nc[1]\n";
1311 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1314 foreach ($typechanges as $tc) {
1315 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1317 echo "... error: expected column $tc[0].$tc[1] to exist\n";
1321 if ($fi->type() === $tc[2])
1322 echo "... $tc[0].$tc[1] is already $tc[2]\n";
1324 echo "... change $tc[0].$tc[1] from {$fi->type()} to $tc[2]\n";
1325 $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1326 if (strlen($tc[3])) {
1327 $sql .= " USING $tc[3]";
1329 $sql .= ";\nCOMMIT;\n";
1330 $wgDatabase->query($sql);
1334 foreach ($newindexes as $ni) {
1335 if (pg_index_exists($ni[0], $ni[1])) {
1336 echo "... index $ni[1] on $ni[0] already exists\n";
1339 dbsource(archive($ni[2]));
1342 foreach ($newrules as $nr) {
1343 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1344 echo "... rule $nr[1] on $nr[0] already exists\n";
1347 dbsource(archive($nr[2]));
1350 if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1351 echo "... create page_deleted trigger\n";
1352 dbsource(archive('patch-page_deleted.sql'));
1355 $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1356 if (!$fi->nullable()) {
1357 echo "... remove NOT NULL constraint on recentchanges.rc_cur_id\n";
1358 dbsource(archive('patch-rc_cur_id-not-null.sql'));
1361 $pu = pg_describe_index("pagelink_unique");
1362 if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1363 echo "... dropping obsolete pagelink_unique index\n";
1364 $wgDatabase->query("DROP INDEX pagelink_unique");
1367 echo "... obsolete pagelink_unique index not present\n";
1370 echo "... adding new pagelink_unique index\n";
1371 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1373 echo "... already have current pagelink_unique index\n";
1375 if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1376 echo "... revision_rev_user_fkey is already ON DELETE RESTRICT\n";
1378 echo "... change revision_rev_user_fkey to ON DELETE RESTRICT\n";
1379 dbsource(archive('patch-revision_rev_user_fkey.sql'));
1382 if (is_null($wgDatabase->fieldInfo("archive", "ar_deleted"))) {
1383 echo "... add archive.ar_deleted\n";
1384 dbsource(archive("patch-archive-ar_deleted.sql"));
1386 echo "... archive.ar_deleted already exists\n";