CategoriesPage no more
[mediawiki.git] / maintenance / updaters.inc
blob99cd39c5d089068c8e76888e0ee52ad0ed408932
1 <?php
2 /**
3  * @addtogroup Maintenance
4  */
6  /** */
8 if ( !defined( 'MEDIAWIKI' ) ) {
9         echo "This file is not a valid entry point\n";
10         exit( 1 );
13 require_once 'convertLinks.inc';
14 require_once 'userDupes.inc';
15 require_once 'deleteDefaultMessages.php';
17 $wgRenamedTables = array(
18 #           from             to                  patch file
19 #       array( 'group',         'groups',           'patch-rename-group.sql' ),
22 $wgNewTables = array(
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' ),
40 $wgNewFields = array(
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( 'logging',       'log_id',               'patch-log_id.sql' ),
72 function rename_table( $from, $to, $patch ) {
73         global $wgDatabase;
74         if ( $wgDatabase->tableExists( $from ) ) {
75                 if ( $wgDatabase->tableExists( $to ) ) {
76                         echo "...can't move table $from to $to, $to already exists.\n";
77                 } else {
78                         echo "Moving table $from to $to...";
79                         dbsource( archive($patch), $wgDatabase );
80                         echo "ok\n";
81                 }
82         } else {
83                 // Source table does not exist
84                 // Renames are done before creations, so this is typical for a new installation
85                 // Ignore silently
86         }
89 function add_table( $name, $patch ) {
90         global $wgDatabase;
91         if ( $wgDatabase->tableExists( $name ) ) {
92                 echo "...$name table already exists.\n";
93         } else {
94                 echo "Creating $name table...";
95                 dbsource( archive($patch), $wgDatabase );
96                 echo "ok\n";
97         }
100 function add_field( $table, $field, $patch ) {
101         global $wgDatabase;
102         if ( !$wgDatabase->tableExists( $table ) ) {
103                 echo "...$table table does not exist, skipping new field patch\n";
104         } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
105                 echo "...have $field field in $table table.\n";
106         } else {
107                 echo "Adding $field field to table $table...";
108                 dbsource( archive($patch) , $wgDatabase );
109                 echo "ok\n";
110         }
113 function do_revision_updates() {
114         global $wgSoftwareRevision;
115         if ( $wgSoftwareRevision < 1001 ) {
116                 update_passwords();
117         }
120 function update_passwords() {
121         wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
123         global $wgDatabase;
124         $fname = "Update script: update_passwords()";
125         print "\nIt appears that you need to update the user passwords in your\n" .
126           "database. If you have already done this (if you've run this update\n" .
127           "script once before, for example), doing so again will make all your\n" .
128           "user accounts inaccessible, so be sure you only do this once.\n" .
129           "Update user passwords? (yes/no)";
131         $resp = readconsole();
132     if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
134         $sql = "SELECT user_id,user_password FROM user";
135         $source = $wgDatabase->query( $sql, $fname );
137         while ( $row = $wgDatabase->fetchObject( $source ) ) {
138                 $id = $row->user_id;
139                 $oldpass = $row->user_password;
140                 $newpass = md5( "{$id}-{$oldpass}" );
142                 $sql = "UPDATE user SET user_password='{$newpass}' " .
143                   "WHERE user_id={$id}";
144                 $wgDatabase->query( $sql, $fname );
145         }
148 function do_interwiki_update() {
149         # Check that interwiki table exists; if it doesn't source it
150         global $wgDatabase, $IP;
151         if( $wgDatabase->tableExists( "interwiki" ) ) {
152                 echo "...already have interwiki table\n";
153                 return true;
154         }
155         echo "Creating interwiki table: ";
156         dbsource( archive("patch-interwiki.sql") );
157         echo "ok\n";
158         echo "Adding default interwiki definitions: ";
159         dbsource( "$IP/maintenance/interwiki.sql" );
160         echo "ok\n";
163 function do_index_update() {
164         # Check that proper indexes are in place
165         global $wgDatabase;
166         $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
167         if( $meta->multiple_key == 0 ) {
168                 echo "Updating indexes to 20031107: ";
169                 dbsource( archive("patch-indexes.sql") );
170                 echo "ok\n";
171                 return true;
172         }
173         echo "...indexes seem up to 20031107 standards\n";
174         return false;
177 function do_image_index_update() {
178         global $wgDatabase;
180         $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
181         if( $meta->multiple_key == 0 ) {
182                 echo "Updating indexes to 20050912: ";
183                 dbsource( archive("patch-mimesearch-indexes.sql") );
184                 echo "ok\n";
185                 return true;
186         }
187         echo "...indexes seem up to 20050912 standards\n";
188         return false;
191 function do_image_name_unique_update() {
192         global $wgDatabase;
193         if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
194                 echo "...image primary key already set.\n";
195         } else {
196                 echo "Making img_name the primary key... ";
197                 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
198                 echo "ok\n";
199         }
202 function do_logging_timestamp_index() {
203         global $wgDatabase;
204         if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
205                 echo "...timestamp key on logging already exists.\n";
206         } else {
207                 echo "Adding timestamp key on logging table... ";
208                 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
209                 echo "ok\n";
210         }
214 function do_watchlist_update() {
215         global $wgDatabase;
216         $fname = 'do_watchlist_update';
217         if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
218                 echo "The watchlist table is already set up for email notification.\n";
219         } else {
220                 echo "Adding wl_notificationtimestamp field for email notification management.";
221                 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
222                 dbsource( archive( 'patch-email-notification.sql' ), $wgDatabase );
223                 echo "ok\n";
224         }
225         # Check if we need to add talk page rows to the watchlist
226         $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
227         $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
228         if ( $talk != $nontalk ) {
229                 echo "Adding missing watchlist talk page rows... ";
230                 flush();
232                 $wgDatabase->insertSelect( 'watchlist', 'watchlist', 
233                         array(
234                                 'wl_user' => 'wl_user',
235                                 'wl_namespace' => 'wl_namespace | 1',
236                                 'wl_title' => 'wl_title',
237                                 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
238                         ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
239                 echo "ok\n";
240         } else {
241                 echo "...watchlist talk page rows already present\n";
242         }
245 function do_copy_newtalk_to_watchlist() {
246         global $wgDatabase;
247         global $wgCommandLineMode;      # this needs to be saved while getID() and getName() are called
249         $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
250                 $wgDatabase->tableName( 'user_newtalk' ) );
251         $num_newtalks=$wgDatabase->numRows($res);
252         echo "Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
254         $user = new User();
255         for ( $i = 1; $i <= $num_newtalks; $i++ ) {
256                 $wluser = $wgDatabase->fetchObject( $res );
257                 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
258                         if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
259                                 $wgDatabase->replace( 'watchlist',
260                                         array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
261                                           array('wl_user'                       => 0,
262                                                 'wl_namespace'                  => NS_USER_TALK,
263                                                 'wl_title'                      => $wluser->user_ip,
264                                                 'wl_notificationtimestamp'      => '19700101000000'
265                                                 ), 'updaters.inc::do_watchlist_update2'
266                                         );
267                         }
268                 } else { # normal users ... have user_ids
269                         $user->setID($wluser->user_id);
270                         $wgDatabase->replace( 'watchlist',
271                                 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
272                                   array('wl_user'                       => $user->getID(),
273                                         'wl_namespace'                  => NS_USER_TALK,
274                                         'wl_title'                      => $user->getName(),
275                                         'wl_notificationtimestamp'      => '19700101000000'
276                                         ), 'updaters.inc::do_watchlist_update3'
277                                 );
278                 }
279         }
280         echo "Done.\n";
284 function do_user_update() {
285         global $wgDatabase;
286         if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
287                 echo "User table contains old email authentication field. Dropping... ";
288                 dbsource( archive( 'patch-email-authentication.sql' ), $wgDatabase );
289                 echo "ok\n";
290         } else {
291                 echo "...user table does not contain old email authentication field.\n";
292         }
296  * 1.4 betas were missing the 'binary' marker from logging.log_title,
297  * which causes a collation mismatch error on joins in MySQL 4.1.
298  */
299 function do_logging_encoding() {
300         global $wgDatabase, $wgDBtype;
301         if ($wgDBtype != 'mysql')
302                 return;
303         $logging = $wgDatabase->tableName( 'logging' );
304         $res = $wgDatabase->query( "SELECT log_title FROM $logging LIMIT 0" );
305         $flags = explode( ' ', mysql_field_flags( $res, 0 ) );
306         $wgDatabase->freeResult( $res );
308         if( in_array( 'binary', $flags ) ) {
309                 echo "Logging table has correct title encoding.\n";
310         } else {
311                 echo "Fixing title encoding on logging table... ";
312                 dbsource( archive( 'patch-logging-title.sql' ), $wgDatabase );
313                 echo "ok\n";
314         }
317 function do_schema_restructuring() {
318         global $wgDatabase;
319         $fname="do_schema_restructuring";
320         if ( $wgDatabase->tableExists( 'page' ) ) {
321                 echo "...page table already exists.\n";
322         } else {
323                 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
324                 echo wfTimestamp( TS_DB );
325                 echo "......checking for duplicate entries.\n"; flush();
327                 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
329                 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
330                                 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
332                 if ( $wgDatabase->numRows( $rows ) > 0 ) {
333                         echo wfTimestamp( TS_DB );
334                         echo "......<b>Found duplicate entries</b>\n";
335                         echo ( sprintf( "<b>      %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
336                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
337                                 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
338                                         $duplicate[$row->cur_namespace] = array();
339                                 }
340                                 $duplicate[$row->cur_namespace][] = $row->cur_title;
341                                 echo ( sprintf( "      %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
342                         }
343                         $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
344                         $firstCond = true;
345                         foreach ( $duplicate as $ns => $titles ) {
346                                 if ( $firstCond ) {
347                                         $firstCond = false;
348                                 } else {
349                                         $sql .= ' OR ';
350                                 }
351                                 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
352                                 $first = true;
353                                 foreach ( $titles as $t ) {
354                                         if ( $first ) {
355                                                 $sql .= $wgDatabase->addQuotes( $t );
356                                                 $first = false;
357                                         } else {
358                                                 $sql .= ', ' . $wgDatabase->addQuotes( $t );
359                                         }
360                                 }
361                                 $sql .= ") ) \n";
362                         }
363                         # By sorting descending, the most recent entry will be the first in the list.
364                         # All following entries will be deleted by the next while-loop.
365                         $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
367                         $rows = $wgDatabase->query( $sql, $fname );
369                         $prev_title = $prev_namespace = false;
370                         $deleteId = array();
372                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
373                                 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
374                                         $deleteId[] = $row->cur_id;
375                                 }
376                                 $prev_title     = $row->cur_title;
377                                 $prev_namespace = $row->cur_namespace;
378                         }
379                         $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
380                         $rows = $wgDatabase->query( $sql, $fname );
381                         echo wfTimestamp( TS_DB );
382                         echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
383                 }
386                 echo wfTimestamp( TS_DB );
387                 echo "......Creating tables.\n";
388                 $wgDatabase->query("CREATE TABLE $page (
389                         page_id int(8) unsigned NOT NULL auto_increment,
390                         page_namespace int NOT NULL,
391                         page_title varchar(255) binary NOT NULL,
392                         page_restrictions tinyblob NOT NULL,
393                         page_counter bigint(20) unsigned NOT NULL default '0',
394                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
395                         page_is_new tinyint(1) unsigned NOT NULL default '0',
396                         page_random real unsigned NOT NULL,
397                         page_touched char(14) binary NOT NULL default '',
398                         page_latest int(8) unsigned NOT NULL,
399                         page_len int(8) unsigned NOT NULL,
401                         PRIMARY KEY page_id (page_id),
402                         UNIQUE INDEX name_title (page_namespace,page_title),
403                         INDEX (page_random),
404                         INDEX (page_len)
405                         ) TYPE=InnoDB", $fname );
406                 $wgDatabase->query("CREATE TABLE $revision (
407                         rev_id int(8) unsigned NOT NULL auto_increment,
408                         rev_page int(8) unsigned NOT NULL,
409                         rev_comment tinyblob NOT NULL,
410                         rev_user int(5) unsigned NOT NULL default '0',
411                         rev_user_text varchar(255) binary NOT NULL default '',
412                         rev_timestamp char(14) binary NOT NULL default '',
413                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
414                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
416                         PRIMARY KEY rev_page_id (rev_page, rev_id),
417                         UNIQUE INDEX rev_id (rev_id),
418                         INDEX rev_timestamp (rev_timestamp),
419                         INDEX page_timestamp (rev_page,rev_timestamp),
420                         INDEX user_timestamp (rev_user,rev_timestamp),
421                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
422                         ) TYPE=InnoDB", $fname );
424                 echo wfTimestamp( TS_DB );
425                 echo "......Locking tables.\n";
426                 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
428                 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
429                 echo wfTimestamp( TS_DB );
430                 echo "......maxold is {$maxold}\n";
432                 echo wfTimestamp( TS_DB );
433                 global $wgLegacySchemaConversion;
434                 if( $wgLegacySchemaConversion ) {
435                         // Create HistoryBlobCurStub entries.
436                         // Text will be pulled from the leftover 'cur' table at runtime.
437                         echo "......Moving metadata from cur; using blob references to text in cur table.\n";
438                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
439                         $cur_flags = "'object'";
440                 } else {
441                         // Copy all cur text in immediately: this may take longer but avoids
442                         // having to keep an extra table around.
443                         echo "......Moving text from cur.\n";
444                         $cur_text = 'cur_text';
445                         $cur_flags = "''";
446                 }
447                 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
448                                 old_timestamp, old_minor_edit, old_flags)
449                         SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
450                         FROM $cur", $fname );
452                 echo wfTimestamp( TS_DB );
453                 echo "......Setting up revision table.\n";
454                 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
455                                 rev_minor_edit)
456                         SELECT old_id, cur_id, old_comment, old_user, old_user_text,
457                                 old_timestamp, old_minor_edit
458                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
460                 echo wfTimestamp( TS_DB );
461                 echo "......Setting up page table.\n";
462                 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
463                                 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
464                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
465                                 cur_random, cur_touched, rev_id, LENGTH(cur_text)
466                         FROM $cur,$revision
467                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
469                 echo wfTimestamp( TS_DB );
470                 echo "......Unlocking tables.\n";
471                 $wgDatabase->query( "UNLOCK TABLES", $fname );
473                 echo wfTimestamp( TS_DB );
474                 echo "......Renaming old.\n";
475                 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
477                 echo wfTimestamp( TS_DB );
478                 echo "...done.\n";
479         }
482 function do_inverse_timestamp() {
483         global $wgDatabase;
484         if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
485                 echo "Removing revision.inverse_timestamp and fixing indexes... ";
486                 dbsource( archive( 'patch-inverse_timestamp.sql' ), $wgDatabase );
487                 echo "ok\n";
488         } else {
489                 echo "revision timestamp indexes already up to 2005-03-13\n";
490         }
493 function do_text_id() {
494         global $wgDatabase;
495         if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
496                 echo "...rev_text_id already in place.\n";
497         } else {
498                 echo "Adding rev_text_id field... ";
499                 dbsource( archive( 'patch-rev_text_id.sql' ), $wgDatabase );
500                 echo "ok\n";
501         }
504 function do_namespace_size() {
505         $tables = array(
506                 'page'          => 'page',
507                 'archive'       => 'ar',
508                 'recentchanges' => 'rc',
509                 'watchlist'     => 'wl',
510                 'querycache'    => 'qc',
511                 'logging'       => 'log',
512         );
513         foreach( $tables as $table => $prefix ) {
514                 do_namespace_size_on( $table, $prefix );
515                 flush();
516         }
519 function do_namespace_size_on( $table, $prefix ) {
520         global $wgDatabase, $wgDBtype;
521         if ($wgDBtype != 'mysql')
522                 return;
523         $field = $prefix . '_namespace';
525         $tablename = $wgDatabase->tableName( $table );
526         $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
527         $info = $wgDatabase->fetchObject( $result );
528         $wgDatabase->freeResult( $result );
530         if( substr( $info->Type, 0, 3 ) == 'int' ) {
531                 echo "...$field is already a full int ($info->Type).\n";
532         } else {
533                 echo "Promoting $field from $info->Type to int... ";
535                 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
536                 $wgDatabase->query( $sql );
538                 echo "ok\n";
539         }
542 function do_pagelinks_update() {
543         global $wgDatabase;
544         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
545                 echo "...already have pagelinks table.\n";
546         } else {
547                 echo "Converting links and brokenlinks tables to pagelinks... ";
548                 dbsource( archive( 'patch-pagelinks.sql' ), $wgDatabase );
549                 echo "ok\n";
550                 flush();
552                 global $wgCanonicalNamespaceNames;
553                 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
554                         if( $ns != 0 ) {
555                                 do_pagelinks_namespace( $ns );
556                         }
557                 }
558         }
561 function do_pagelinks_namespace( $namespace ) {
562         global $wgDatabase, $wgContLang;
564         $ns = intval( $namespace );
565         echo "Cleaning up broken links for namespace $ns... ";
567         $pagelinks = $wgDatabase->tableName( 'pagelinks' );
568         $name = $wgContLang->getNsText( $ns );
569         $prefix = $wgDatabase->strencode( $name );
570         $likeprefix = str_replace( '_', '\\_', $prefix);
572         $sql = "UPDATE $pagelinks
573                    SET pl_namespace=$ns,
574                        pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
575                  WHERE pl_namespace=0
576                    AND pl_title LIKE '$likeprefix:%'";
578         $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
579         echo "ok\n";
582 function do_drop_img_type() {
583         global $wgDatabase;
585         if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
586                 echo "Dropping unused img_type field in image table... ";
587                 dbsource( archive( 'patch-drop_img_type.sql' ), $wgDatabase );
588                 echo "ok\n";
589         } else {
590                 echo "No img_type field in image table; Good.\n";
591         }
594 function do_old_links_update() {
595         global $wgDatabase;
596         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
597                 echo "Already have pagelinks; skipping old links table updates.\n";
598         } else {
599                 convertLinks(); flush();
600         }
603 function do_user_unique_update() {
604         global $wgDatabase;
605         $duper = new UserDupes( $wgDatabase );
606         if( $duper->hasUniqueIndex() ) {
607                 echo "Already have unique user_name index.\n";
608         } else {
609                 if( !$duper->clearDupes() ) {
610                         echo "WARNING: This next step will probably fail due to unfixed duplicates...\n";
611                 }
612                 echo "Adding unique index on user_name... ";
613                 dbsource( archive( 'patch-user_nameindex.sql' ), $wgDatabase );
614                 echo "ok\n";
615         }
618 function do_user_groups_update() {
619         $fname = 'do_user_groups_update';
620         global $wgDatabase;
622         if( $wgDatabase->tableExists( 'user_groups' ) ) {
623                 echo "...user_groups table already exists.\n";
624                 return do_user_groups_reformat();
625         }
627         echo "Adding user_groups table... ";
628         dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
629         echo "ok\n";
631         if( !$wgDatabase->tableExists( 'user_rights' ) ) {
632                 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
633                         echo "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion...";
634                         dbsource( archive( 'patch-user_rights.sql' ), $wgDatabase );
635                         echo "ok\n";
636                 } else {
637                         echo "*** WARNING: couldn't locate user_rights table or field for upgrade.\n";
638                         echo "*** You may need to manually configure some sysops by manipulating\n";
639                         echo "*** the user_groups table.\n";
640                         return;
641                 }
642         }
644         echo "Converting user_rights table to user_groups... ";
645         $result = $wgDatabase->select( 'user_rights',
646                 array( 'ur_user', 'ur_rights' ),
647                 array( "ur_rights != ''" ),
648                 $fname );
650         while( $row = $wgDatabase->fetchObject( $result ) ) {
651                 $groups = array_unique(
652                         array_map( 'trim',
653                                 explode( ',', $row->ur_rights ) ) );
655                 foreach( $groups as $group ) {
656                         $wgDatabase->insert( 'user_groups',
657                                 array(
658                                         'ug_user'  => $row->ur_user,
659                                         'ug_group' => $group ),
660                                 $fname );
661                 }
662         }
663         $wgDatabase->freeResult( $result );
664         echo "ok\n";
667 function do_user_groups_reformat() {
668         # Check for bogus formats from previous 1.5 alpha code.
669         global $wgDatabase;
670         $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
672         if( $info->type == 'int' ) {
673                 $oldug = $wgDatabase->tableName( 'user_groups' );
674                 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
675                 echo "user_groups is in bogus intermediate format. Renaming to $newug... ";
676                 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
677                 echo "ok\n";
679                 echo "Re-adding fresh user_groups table... ";
680                 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
681                 echo "ok\n";
683                 echo "***\n";
684                 echo "*** WARNING: You will need to manually fix up user permissions in the user_groups\n";
685                 echo "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n";
686                 echo "***\n";
687         } else {
688                 echo "...user_groups is in current format.\n";
689         }
693 function do_watchlist_null() {
694         # Make sure wl_notificationtimestamp can be NULL,
695         # and update old broken items.
696         global $wgDatabase;
697         $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
699         if( $info->not_null ) {
700                 echo "Making wl_notificationtimestamp nullable... ";
701                 dbsource( archive( 'patch-watchlist-null.sql' ), $wgDatabase );
702                 echo "ok\n";
703         } else {
704                 echo "...wl_notificationtimestamp is already nullable.\n";
705         }
710  * @bug 3946
711  */
712 function do_page_random_update() {
713         global $wgDatabase;
715         echo "Setting page_random to a random value on rows where it equals 0...";
717         $page = $wgDatabase->tableName( 'page' );
718         $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
719         $rows = $wgDatabase->affectedRows();
721         echo "changed $rows rows\n";
724 function do_templatelinks_update() {
725         global $wgDatabase, $wgLoadBalancer;
726         $fname = 'do_templatelinks_update';
728         if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
729                 echo "...templatelinks table already exists\n";
730                 return;
731         }
732         echo "Creating templatelinks table...\n";
733         dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
734         echo "Populating...\n";
735         if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
736                 // Slow, replication-friendly update
737                 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
738                         array( 'pl_namespace' => NS_TEMPLATE ), $fname );
739                 $count = 0;
740                 while ( $row = $wgDatabase->fetchObject( $res ) ) {
741                         $count = ($count + 1) % 100;
742                         if ( $count == 0 ) {
743                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
744                                         wfWaitForSlaves( 10 );
745                                 } else {
746                                         sleep( 1 );
747                                 }
748                         }
749                         $wgDatabase->insert( 'templatelinks',
750                                 array(
751                                         'tl_from' => $row->pl_from,
752                                         'tl_namespace' => $row->pl_namespace,
753                                         'tl_title' => $row->pl_title,
754                                 ), $fname
755                         );
757                 }
758                 $wgDatabase->freeResult( $res );
759         } else {
760                 // Fast update
761                 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
762                         array(
763                                 'tl_from' => 'pl_from',
764                                 'tl_namespace' => 'pl_namespace',
765                                 'tl_title' => 'pl_title'
766                         ), array(
767                                 'pl_namespace' => 10
768                         ), $fname
769                 );
770         }
771         echo "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n";
774 # July 2006
775 # Add ( rc_namespace, rc_user_text ) index [R. Church]
776 function do_rc_indices_update() {
777         global $wgDatabase;
778         echo( "Checking for additional recent changes indices...\n" );
779         # See if we can find the index we want
780         $info = $wgDatabase->indexInfo( 'recentchanges', 'rc_ns_usertext', __METHOD__ );
781         if( !$info ) {
782                 # None, so create
783                 echo( "...index on ( rc_namespace, rc_user_text ) not found; creating\n" );
784                 dbsource( archive( 'patch-recentchanges-utindex.sql' ) );
785         } else {
786                 # Index seems to exist
787                 echo( "...index on ( rc_namespace, rc_user_text ) seems to be ok\n" );
788         }
790         #Add (rc_user_text, rc_timestamp) index [A. Garrett], November 2006
791         # See if we can find the index we want
792         $info = $wgDatabase->indexInfo( 'recentchanges', 'rc_user_text', __METHOD__ );
793         if( !$info ) {
794                 # None, so create
795                 echo( "...index on ( rc_user_text, rc_timestamp ) not found; creating\n" );
796                 dbsource( archive( 'patch-rc_user_text-index.sql' ) );
797         } else {
798                 # Index seems to exist
799                 echo( "...index on ( rc_user_text, rc_timestamp ) seems to be ok\n" );
800         }
803 function index_has_field($table, $index, $field) {
804         global $wgDatabase;
805         echo( "Checking if $table index $index includes field $field...\n" );
806         $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
807         if( $info ) {
808                 foreach($info as $row) {
809                         if($row->Column_name == $field) {
810                                 echo( "...index $index on table $table seems to be ok\n" );
811                                 return true;
812                         }
813                 }
814         }
815         echo( "...index $index on table $table has no field $field; adding\n" );
816         return false;
819 function do_backlinking_indices_update() {
820         echo( "Checking for backlinking indices...\n" );
821         if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
822                 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
823                 !index_has_field('imagelinks', 'il_to', 'il_from'))
824         {       
825                 dbsource( archive( 'patch-backlinkindexes.sql' ) );
826         }
829 function do_stats_init() {
830         // Sometimes site_stats table is not properly populated.
831         global $wgDatabase;
832         echo "Checking site_stats row...";
833         $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
834         if( $row === false ) {
835                 echo "data is missing! rebuilding...\n";
836                 
837                 global $IP;
838                 require_once "$IP/maintenance/initStats.inc";
839                 wfInitStats();
840         } else {
841                 echo "ok.\n";
842         }
845 function purge_cache() {
846         global $wgDatabase;
847         # We can't guarantee that the user will be able to use TRUNCATE,
848         # but we know that DELETE is available to us
849         echo( "Purging caches..." );
850         $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
851         echo( "done.\n" );
854 function do_all_updates( $shared = false, $purge = true ) {
855         global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgDatabase, $wgDBtype, $IP;
857         $doUser = !$wgSharedDB || $shared;
859         if ($wgDBtype === 'postgres') {
860                 do_postgres_updates();
861                 return;
862         }
864         # Rename tables
865         foreach ( $wgRenamedTables as $tableRecord ) {
866                 rename_table( $tableRecord[0], $tableRecord[1], $tableRecord[2] );
867         }
869         # Add missing tables
870         foreach ( $wgNewTables as $tableRecord ) {
871                 add_table( $tableRecord[0], $tableRecord[1] );
872                 flush();
873         }
875         # Add missing fields
876         foreach ( $wgNewFields as $fieldRecord ) {
877                 if ( $fieldRecord[0] != 'user' || $doUser ) {
878                         add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2] );
879                 }
880                 flush();
881         }
883         # Do schema updates which require special handling
884         do_interwiki_update(); flush();
885         do_index_update(); flush();
886         do_old_links_update(); flush();
887         do_image_name_unique_update(); flush();
888         do_watchlist_update(); flush();
889         if ( $doUser ) {
890                 do_user_update(); flush();
891         }
892 ######  do_copy_newtalk_to_watchlist(); flush();
893         do_logging_encoding(); flush();
895         do_schema_restructuring(); flush();
896         do_inverse_timestamp(); flush();
897         do_text_id(); flush();
898         do_namespace_size(); flush();
900         do_pagelinks_update(); flush();
901         do_templatelinks_update(); flush(); // after pagelinks
903         do_drop_img_type(); flush();
905         if ( $doUser ) {
906                 do_user_unique_update(); flush();
907         }
908         do_user_groups_update(); flush();
910         do_watchlist_null(); flush();
912         //do_image_index_update(); flush();
914         do_logging_timestamp_index(); flush();
916         do_page_random_update(); flush();
917         
918         do_rc_indices_update(); flush();
920         add_table( 'redirect', 'patch-redirect.sql' );
922         do_backlinking_indices_update(); flush();
924         do_restrictions_update(); flush ();
926         echo "Deleting old default messages..."; flush();
927         deleteDefaultMessages();
928         echo "Done\n"; flush();
929         
930         do_stats_init(); flush();
931         
932         if( $purge ) {
933                 purge_cache();
934                 flush();
935         }
938 function archive($name) {
939         global $wgDBtype, $IP;
940         switch ($wgDBtype) {
941         // @fixme: add mysql5 and postgres items or....?
942         default:
943                 return "$IP/maintenance/archives/$name";
944         }
947 function do_restrictions_update() {
948         # Adding page_restrictions table, obsoleting page.page_restrictions.
949         #  Migrating old restrictions to new table
950         # -- Andrew Garrett, January 2007.
952         global $wgDatabase;
954         $name = 'page_restrictions';
955         $patch = 'patch-page_restrictions.sql';
957         if ( $wgDatabase->tableExists( $name ) ) {
958                 echo "...$name table already exists.\n";
959         } else {
960                 echo "Creating $name table...";
961                 dbsource( archive($patch), $wgDatabase );
962                 echo "ok\n";
964                 echo "Migrating old restrictions to new table...";
966                 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
968                 $count = 0;
970                 while ($row = $wgDatabase->fetchObject($res) ) {
971                         $count = ($count + 1) % 100;
973                         if ($count == 0) {
974                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
975                                         wfWaitForSlaves( 10 );
976                                 } else {
977                                         sleep( 1 );
978                                 }
979                         }
981                         # Figure out what the restrictions are..
982                         $id = $row->page_id;
983                         $flatrestrictions = explode( ':', $row->page_restrictions );
985                         $restrictions = array ();
986                         foreach( $flatrestrictions as $restriction ) {
987                                 $thisrestriction = explode( '=', $restriction, 2 );
988                                 if( count( $thisrestriction ) == 1 ) {
989                                         // Compatibility with old protections from before
990                                         // separate move protection was added.
991                                         list( $level ) = $thisrestriction;
992                                         if( $level ) {
993                                                 $restrictions['edit'] = $level;
994                                                 $restrictions['move'] = $level;
995                                         }
996                                 } else {
997                                         list( $type, $level ) = $thisrestriction;
998                                         if( $level ) {
999                                                 $restrictions[$type] = $level;
1000                                         }
1001                                 }
1003                         $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1005                         }
1006                         
1007                         foreach( $restrictions as $type => $level ) {
1008                                 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1009                                                                                         'pr_type' => $type,
1010                                                                                         'pr_level' => $level,
1011                                                                                         'pr_cascade' => 0 ),
1012                                                                                         __METHOD__ );
1013                         }
1014                 }
1015                 print "ok\n";
1016         }
1017         
1020 function do_postgres_updates() {
1021         global $wgDatabase, $wgVersion, $wgDBmwschema;
1023         # Just in case their LocalSetings.php does not have this:
1024         if ( !isset( $wgDBmwschema ))
1025                 $wgDBmwschema = 'mediawiki';
1027         ## Default to the oldest supported version
1028         $version = 1.7;
1030         $thisver = array();
1031         if ($wgDatabase->tableExists("mediawiki_version")) {
1032                 $version = "1.8";
1033                 $sql = "SELECT mw_version FROM mediawiki_version ORDER BY cdate DESC LIMIT 1";
1034                 $tempversion = pg_fetch_result($wgDatabase->doQuery($sql),0,0);
1035                 if (preg_match('/(\d+\.\d+)/', $tempversion, $thisver)) {
1036                         $version = $thisver[1];
1037                 }
1038         }
1040         print " Detected version: $version\n";
1042         ## Transform to a standard format
1043         if (! preg_match('/(\d+)\.(\d+)/', $version, $thisver)) {
1044                 die ("Sorry, could not figure out what version \"$version\" means");
1045         }
1046         $oldversion = $version;
1047         $version = sprintf("%d%03d",$thisver[1],$thisver[2]);
1048         print " Standardized version: $version\n";
1050         $upgrade = '';
1052         ## 1.8 Updater
1053         if ($version < 1008) {
1054                 $upgrade .= <<<PGEND
1056 -- Type tweaking:
1057 ALTER TABLE oldimage ALTER oi_size TYPE INTEGER;
1058 ALTER TABLE oldimage ALTER oi_width TYPE INTEGER;
1059 ALTER TABLE oldimage ALTER oi_height TYPE INTEGER;
1061 ALTER TABLE image ALTER img_size TYPE INTEGER;
1062 ALTER TABLE image ALTER img_width TYPE INTEGER;
1063 ALTER TABLE image ALTER img_height TYPE INTEGER;
1065 -- Constraint tweaking:
1066 ALTER TABLE recentchanges ALTER rc_cur_id DROP NOT NULL;
1068 -- New columns:
1069 ALTER TABLE ipblocks ADD ipb_anon_only CHAR NOT NULL DEFAULT '0';
1070 ALTER TABLE ipblocks ADD ipb_create_account CHAR NOT NULL DEFAULT '1';
1072 -- Index order rearrangements:
1073 DROP INDEX pagelink_unique;
1074 CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title);
1076 -- Rename tables
1077 ALTER TABLE "user" RENAME TO mwuser;
1078 ALTER TABLE "text" RENAME to pagecontent;
1080 -- New tables:
1081 CREATE TABLE profiling (
1082   pf_count   INTEGER         NOT NULL DEFAULT 0,
1083   pf_time    NUMERIC(18,10)  NOT NULL DEFAULT 0,
1084   pf_name    TEXT            NOT NULL,
1085   pf_server  TEXT            NULL
1087 CREATE UNIQUE INDEX pf_name_server ON profiling (pf_name, pf_server);
1089 CREATE TABLE mediawiki_version (
1090   type         TEXT         NOT NULL,
1091   mw_version   TEXT         NOT NULL,
1092   notes        TEXT             NULL,
1094   pg_version   TEXT             NULL,
1095   pg_dbname    TEXT             NULL,
1096   pg_user      TEXT             NULL,
1097   pg_port      TEXT             NULL,
1098   mw_schema    TEXT             NULL,
1099   ts2_schema   TEXT             NULL,
1100   ctype        TEXT             NULL,
1102   sql_version  TEXT             NULL,
1103   sql_date     TEXT             NULL,
1104   cdate        TIMESTAMPTZ  NOT NULL DEFAULT now()
1107 -- Special modifications
1108 ALTER TABLE archive RENAME to archive2;
1109 CREATE VIEW archive AS 
1110 SELECT 
1111   ar_namespace, ar_title, ar_text, ar_comment, ar_user, ar_user_text, 
1112   ar_minor_edit, ar_flags, ar_rev_id, ar_text_id,
1113        TO_CHAR(ar_timestamp, 'YYYYMMDDHH24MISS') AS ar_timestamp
1114 FROM archive2;
1116 CREATE RULE archive_insert AS ON INSERT TO archive
1117 DO INSTEAD INSERT INTO archive2 VALUES (
1118   NEW.ar_namespace, NEW.ar_title, NEW.ar_text, NEW.ar_comment, NEW.ar_user, NEW.ar_user_text, 
1119   TO_DATE(NEW.ar_timestamp, 'YYYYMMDDHH24MISS'),
1120   NEW.ar_minor_edit, NEW.ar_flags, NEW.ar_rev_id, NEW.ar_text_id
1123 CREATE FUNCTION page_deleted() RETURNS TRIGGER LANGUAGE plpgsql AS
1124 \$mw\$
1125 BEGIN
1126 DELETE FROM recentchanges WHERE rc_namespace = OLD.page_namespace AND rc_title = OLD.page_title;
1127 RETURN NULL;
1128 END;
1129 \$mw\$;
1131 CREATE TRIGGER page_deleted AFTER DELETE ON page
1132   FOR EACH ROW EXECUTE PROCEDURE page_deleted();
1134 -- Note this upgrade
1135 INSERT INTO mediawiki_version (type,mw_version,notes)
1136 VALUES ('Upgrade','MWVERSION','Upgrade from older pre 1.8 version THISVERSION aka SVERSION');
1138 PGEND;
1140         } ## end version 1.8
1142         ## 1.9 Updater
1143         if ($version < 1009) {
1144                 $upgrade = <<<PGEND
1146 -- Tighten up restrictions on the revision table so we don't lose data:
1147 ALTER TABLE revision DROP CONSTRAINT revision_rev_user_fkey;
1148 ALTER TABLE revision ADD CONSTRAINT revision_rev_user_fkey
1149   FOREIGN KEY (rev_user) REFERENCES mwuser(user_id) ON DELETE RESTRICT;
1151 -- New columns for better password tracking:
1152 ALTER TABLE mwuser ADD user_newpass_time TIMESTAMPTZ;
1153 ALTER TABLE mwuser ADD user_editcount INTEGER;
1155 -- New column for autoblocking problem users
1156 ALTER TABLE ipblocks ADD ipb_enable_autoblock CHAR NOT NULL DEFAULT '1';
1158 -- Despite it's name, ipb_address does not necessarily contain IP addresses :)
1159 ALTER TABLE ipblocks ALTER ipb_address TYPE TEXT USING ipb_address::TEXT;
1161 -- New tables:
1162 CREATE TABLE redirect (
1163   rd_from       INTEGER  NOT NULL  REFERENCES page(page_id) ON DELETE CASCADE,
1164   rd_namespace  SMALLINT NOT NULL,
1165   rd_title      TEXT     NOT NULL
1167 CREATE INDEX redirect_ns_title ON redirect (rd_namespace,rd_title,rd_from);
1169 CREATE TABLE querycachetwo (
1170   qcc_type          TEXT     NOT NULL,
1171   qcc_value         SMALLINT NOT NULL  DEFAULT 0,
1172   qcc_namespace     INTEGER  NOT NULL  DEFAULT 0,
1173   qcc_title         TEXT     NOT NULL  DEFAULT '',
1174   qcc_namespacetwo  INTEGER  NOT NULL  DEFAULT 0,
1175   qcc_titletwo      TEXT     NOT NULL  DEFAULT ''
1177 CREATE INDEX querycachetwo_type_value ON querycachetwo (qcc_type, qcc_value);
1178 CREATE INDEX querycachetwo_title      ON querycachetwo (qcc_type,qcc_namespace,qcc_title);
1179 CREATE INDEX querycachetwo_titletwo   ON querycachetwo (qcc_type,qcc_namespacetwo,qcc_titletwo);
1181 -- New columns for fancy recentchanges display
1182 ALTER TABLE recentchanges ADD rc_old_len INT;
1183 ALTER TABLE recentchanges ADD rc_new_len INT;
1185 -- Note this upgrade
1186 INSERT INTO mediawiki_version (type,mw_version,notes)
1187 VALUES ('Upgrade','MWVERSION','Upgrade from older pre 1.9 version THISVERSION aka SVERSION');
1189 PGEND;
1191         } ## end version 1.9
1193         ## 1.10 updater
1194         if ($version <= 1010) {
1195                 $upgrade = <<<PGEND
1197 CREATE TABLE page_restrictions (
1198   pr_page      INTEGER       NULL  REFERENCES page (page_id) ON DELETE CASCADE,
1199   pr_type   TEXT         NOT NULL,
1200   pr_level  TEXT         NOT NULL,
1201   pr_cascade SMALLINT    NOT NULL,
1202   pr_user   INTEGER          NULL,
1203   pr_expiry TIMESTAMPTZ      NULL
1205 ALTER TABLE page_restrictions ADD CONSTRAINT page_restrictions_pk PRIMARY KEY (pr_page,pr_type);
1207 -- Add a new index to help with full-text searches
1208 CREATE INDEX rev_text_id_idx ON revision (rev_text_id);
1210 -- Fix the archive rule ar_timestamp field
1211 CREATE OR REPLACE RULE archive_insert AS ON INSERT TO archive
1212 DO INSTEAD INSERT INTO archive2 VALUES (
1213   NEW.ar_namespace, NEW.ar_title, NEW.ar_text, NEW.ar_comment, NEW.ar_user, NEW.ar_user_text, 
1214   TO_TIMESTAMP(NEW.ar_timestamp, 'YYYYMMDDHH24MISS'),
1215   NEW.ar_minor_edit, NEW.ar_flags, NEW.ar_rev_id, NEW.ar_text_id
1218 -- Allow deletion of archive rows
1219 CREATE RULE archive_delete AS ON DELETE TO archive
1220 DO INSTEAD DELETE FROM archive2 a2 WHERE
1221   a2.ar_title = OLD.ar_title AND
1222   a2.ar_namespace = OLD.ar_namespace AND
1223   a2.ar_rev_id = OLD.ar_rev_id;
1225 -- Another misleadingly named column! :)
1226 ALTER TABLE user_newtalk ALTER user_ip TYPE TEXT USING host(user_ip);
1228 -- Note this upgrade
1229 INSERT INTO mediawiki_version (type,mw_version,notes)
1230 VALUES ('Upgrade','MWVERSION','Upgrade from older pre 1.10 version THISVERSION aka SVERSION');
1233 PGEND;
1234         } ## end version 1.10
1236         if ( !strlen($upgrade)) {
1237                 print "No updates needed for this version ($oldversion)\n";
1238                 return;
1239         }
1241         $upgrade = str_replace( 'MWVERSION', $wgVersion, $upgrade );
1242         $upgrade = str_replace( 'THISVERSION', $oldversion, $upgrade );
1243         $upgrade = str_replace( 'SVERSION', $version, $upgrade );
1244         $wgDatabase->query("BEGIN;\n\n $upgrade\n\nCOMMIT;\n");
1246         return;