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