* Add a h2 header to the begin of the results
[mediawiki.git] / maintenance / updaters.inc
blob6b1cb10eeb1f8870acabe1b22e83fa2d5b34414c
1 <?php
2 /**
3  * @file
4  * @ingroup Maintenance
5  */
7 if ( !defined( 'MEDIAWIKI' ) ) {
8         echo "This file is not a valid entry point\n";
9         exit( 1 );
12 require_once 'convertLinks.inc';
13 require_once 'userDupes.inc';
14 require_once 'deleteDefaultMessages.php';
15 # Extension updates
16 require_once( "$IP/includes/Hooks.php" );
18 /**
19  * List of update functions to call on a MySQL-based MediaWiki installation,
20  * in sequence. First item is function name, rest are parameters to pass.
21  */
22 $wgMysqlUpdates = array(
23         // 1.2
24         // update_passwords obsolete
25         array( 'add_field', 'ipblocks',      'ipb_id',           'patch-ipblocks.sql' ),
26         array( 'add_field', 'ipblocks',      'ipb_expiry',       'patch-ipb_expiry.sql' ),
27         array( 'do_interwiki_update' ),
28         array( 'do_index_update' ),
29         // do_linkscc_update obsolete
30         array( 'add_table', 'hitcounter',                        'patch-hitcounter.sql' ),
31         array( 'add_field', 'recentchanges', 'rc_type',          'patch-rc_type.sql' ),
32         
33         // 1.3
34         array( 'add_field', 'user',          'user_real_name',   'patch-user-realname.sql' ),
35         array( 'add_table', 'querycache',                        'patch-querycache.sql' ),
36         array( 'add_table', 'objectcache',                       'patch-objectcache.sql' ),
37         array( 'add_table', 'categorylinks',                     'patch-categorylinks.sql' ),
38         // do_linkscc_1_3_update obsolete
39         array( 'do_old_links_update' ),
40         array( 'add_field', 'recentchanges', 'rc_ip',            'patch-rc_ip.sql' ),
41         
42         // 1.4
43         array( 'do_image_name_unique_update' ),
44         array( 'add_field', 'recentchanges', 'rc_id',            'patch-rc_id.sql' ),
45         array( 'add_field', 'recentchanges', 'rc_patrolled',     'patch-rc-patrol.sql' ),
46         array( 'add_table', 'logging',                           'patch-logging.sql' ),
47         // do_user_rights_update obsolete
48         array( 'add_field', 'user',          'user_token',       'patch-user_token.sql' ),
49         // old, old_articleid, patch-remove-old-title-namespace.sql obsolete
50         // user_groups, patch-userlevels.sql obsolete
51         // do_group_update() obsolete
52         array( 'do_watchlist_update' ),
53         array( 'do_user_update' ),
54         // do_copy_newtalk_to_watchlist obsolete
55         
56         // 1.5
57         array( 'do_schema_restructuring' ),
58         array( 'add_field', 'logging',       'log_params',       'patch-log_params.sql' ),
59         array( 'check_bin', 'logging',       'log_title',        'patch-logging-title.sql', ),
60         array( 'add_field', 'archive',       'ar_rev_id',        'patch-archive-rev_id.sql' ),
61         array( 'add_field', 'page',          'page_len',         'patch-page_len.sql' ),
62         array( 'do_inverse_timestamp' ),
63         array( 'do_text_id' ),
64         array( 'add_field', 'revision',      'rev_deleted',      'patch-rev_deleted.sql' ),
65         array( 'add_field', 'image',         'img_width',        'patch-img_width.sql' ),
66         array( 'add_field', 'image',         'img_metadata',     'patch-img_metadata.sql' ),
67         array( 'add_field', 'user',          'user_email_token', 'patch-user_email_token.sql' ),
68         array( 'add_field', 'archive',       'ar_text_id',       'patch-archive-text_id.sql' ),
69         array( 'do_namespace_size' ),
70         array( 'add_field', 'image',         'img_media_type',   'patch-img_media_type.sql' ),
71         array( 'do_pagelinks_update' ),
72         array( 'do_drop_img_type' ),
73         array( 'do_user_unique_update' ),
74         array( 'do_user_groups_update' ),
75         array( 'add_field', 'site_stats',    'ss_total_pages',   'patch-ss_total_articles.sql' ),
76         array( 'add_table', 'user_newtalk',                      'patch-usernewtalk2.sql' ),
77         array( 'add_table', 'transcache',                        'patch-transcache.sql' ),
78         array( 'add_field', 'interwiki',     'iw_trans',         'patch-interwiki-trans.sql' ),
79         array( 'add_table', 'trackbacks',                        'patch-trackbacks.sql' ),
80         
81         // 1.6
82         array( 'do_watchlist_null' ),
83         // do_image_index_update obsolete
84         array( 'do_logging_timestamp_index' ),
85         array( 'add_field', 'ipblocks',        'ipb_range_start',  'patch-ipb_range_start.sql' ),
86         array( 'do_page_random_update' ),
87         array( 'add_field', 'user',            'user_registration','patch-user_registration.sql' ),
88         array( 'do_templatelinks_update' ),
89         array( 'add_table', 'externallinks',                       'patch-externallinks.sql' ),
90         array( 'add_table', 'job',                                 'patch-job.sql' ),
91         array( 'add_field', 'site_stats',      'ss_images',        'patch-ss_images.sql' ),
92         array( 'add_table', 'langlinks',                           'patch-langlinks.sql' ),
93         array( 'add_table', 'querycache_info',                     'patch-querycacheinfo.sql' ),
94         array( 'add_table', 'filearchive',                         'patch-filearchive.sql' ),
95         array( 'add_field', 'ipblocks',        'ipb_anon_only',    'patch-ipb_anon_only.sql' ),
96         array( 'do_rc_indices_update' ),
97         
98         // 1.9
99         array( 'add_field', 'user',          'user_newpass_time', 'patch-user_newpass_time.sql' ),
100         array( 'add_table', 'redirect',                           'patch-redirect.sql' ),
101         array( 'add_table', 'querycachetwo', 'patch-querycachetwo.sql' ),
102         array( 'add_field', 'ipblocks',      'ipb_enable_autoblock', 'patch-ipb_optional_autoblock.sql' ),
103         array( 'do_backlinking_indices_update' ),
104         array( 'add_field', 'recentchanges', 'rc_old_len',        'patch-rc_len.sql' ),
105         array( 'add_field', 'user',          'user_editcount',    'patch-user_editcount.sql' ),
106         
107         // 1.10
108         array( 'do_restrictions_update' ),
109         array( 'add_field', 'logging',       'log_id',           'patch-log_id.sql' ),
110         array( 'add_field', 'revision',      'rev_parent_id',    'patch-rev_parent_id.sql' ),
111         array( 'add_field', 'page_restrictions', 'pr_id',        'patch-page_restrictions_sortkey.sql' ),
112         array( 'add_field', 'revision',      'rev_len',          'patch-rev_len.sql' ),
113         array( 'add_field', 'recentchanges', 'rc_deleted',       'patch-rc_deleted.sql' ),
114         array( 'add_field', 'logging',       'log_deleted',      'patch-log_deleted.sql' ),
115         array( 'add_field', 'archive',       'ar_deleted',       'patch-ar_deleted.sql' ),
116         array( 'add_field', 'ipblocks',      'ipb_deleted',      'patch-ipb_deleted.sql' ),
117         array( 'add_field', 'filearchive',   'fa_deleted',       'patch-fa_deleted.sql' ),
118         array( 'add_field', 'archive',       'ar_len',           'patch-ar_len.sql' ),
119         
120         // 1.11
121         array( 'add_field', 'ipblocks',      'ipb_block_email',  'patch-ipb_emailban.sql' ),
122         array( 'do_categorylinks_indices_update' ),
123         array( 'add_field', 'oldimage',      'oi_metadata',      'patch-oi_metadata.sql'),
124         array( 'do_archive_user_index' ),
125         array( 'do_image_user_index' ),
126         array( 'do_oldimage_user_index' ),
127         array( 'add_field', 'archive',       'ar_page_id',       'patch-archive-page_id.sql'),
128         array( 'add_field', 'image',         'img_sha1',         'patch-img_sha1.sql' ),
130         // 1.12
131         array( 'add_table', 'protected_titles',                  'patch-protected_titles.sql' ),
132         
133         // 1.13
134         array( 'add_field', 'ipblocks',      'ipb_by_text',      'patch-ipb_by_text.sql' ),
135         array( 'add_table', 'page_props',                        'patch-page_props.sql' ),
136         array( 'add_table', 'updatelog',                         'patch-updatelog.sql' ),
137         array( 'add_table', 'category',                          'patch-category.sql' ),
138         array( 'do_category_population' ),
139         array( 'add_field', 'archive',       'ar_parent_id',     'patch-ar_parent_id.sql'),
140         array( 'add_field', 'user_newtalk',  'user_last_timestamp', 'patch-user_last_timestamp.sql'),
141         array( 'do_populate_parent_id' ),
142         array( 'check_bin', 'protected_titles', 'pt_title',      'patch-pt_title-encoding.sql', ),
143         array( 'maybe_do_profiling_memory_update' ),
144         array( 'do_filearchive_indices_update' ),
148 # For extensions only, should be populated via hooks
149 # $wgDBtype should be checked to specifiy the proper file
150 $wgExtNewTables = array(); // table, dir
151 $wgExtNewFields = array(); // table, column, dir
152 $wgExtPGNewFields = array(); // table, column attributes; for PostgreSQL
153 $wgExtNewIndexes = array(); // table, index, dir
155 # Helper function: check if the given key is present in the updatelog table.
156 # Obviously, only use this for updates that occur after the updatelog table was
157 # created!
158 function update_row_exists( $key ) {
159         $dbr = wfGetDB( DB_SLAVE );
160         $row = $dbr->selectRow(
161                 'updatelog',
162                 '1',
163                 array( 'ul_key' => $key ),
164                 __FUNCTION__
165         );
166         return (bool)$row;
169 function rename_table( $from, $to, $patch ) {
170         global $wgDatabase;
171         if ( $wgDatabase->tableExists( $from ) ) {
172                 if ( $wgDatabase->tableExists( $to ) ) {
173                         echo "...can't move table $from to $to, $to already exists.\n";
174                 } else {
175                         echo "Moving table $from to $to...";
176                         dbsource( archive($patch), $wgDatabase );
177                         echo "ok\n";
178                 }
179         } else {
180                 // Source table does not exist
181                 // Renames are done before creations, so this is typical for a new installation
182                 // Ignore silently
183         }
186 function add_table( $name, $patch, $fullpath=false ) {
187         global $wgDatabase;
188         if ( $wgDatabase->tableExists( $name ) ) {
189                 echo "...$name table already exists.\n";
190         } else {
191                 echo "Creating $name table...";
192                 if( $fullpath ) {
193                         dbsource( $patch, $wgDatabase );
194                 } else {
195                         dbsource( archive($patch), $wgDatabase );
196                 }
197                 echo "ok\n";
198         }
201 function add_field( $table, $field, $patch, $fullpath=false ) {
202         global $wgDatabase;
203         if ( !$wgDatabase->tableExists( $table ) ) {
204                 echo "...$table table does not exist, skipping new field patch\n";
205         } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
206                 echo "...have $field field in $table table.\n";
207         } else {
208                 echo "Adding $field field to table $table...";
209                 if( $fullpath ) {
210                         dbsource( $patch, $wgDatabase );
211                 } else {
212                         dbsource( archive($patch), $wgDatabase );
213                 }
214                 echo "ok\n";
215         }
218 function add_index( $table, $index, $patch, $fullpath=false ) {
219         global $wgDatabase;
220         if( $wgDatabase->indexExists( $table, $index ) ) {
221                 echo "...$index key already set on $table table.\n";
222         } else {
223                 echo "Adding $index key to table $table... ";
224                 if( $fullpath ) {
225                         dbsource( $patch, $wgDatabase );
226                 } else {
227                         dbsource( archive($patch), $wgDatabase );
228                 }
229                 echo "ok\n";
230         }
233 function do_revision_updates() {
234         global $wgSoftwareRevision;
235         if ( $wgSoftwareRevision < 1001 ) {
236                 update_passwords();
237         }
240 function update_passwords() {
241         wfDebugDieBacktrace( "This function needs to be updated or removed.\n" );
243         global $wgDatabase;
244         $fname = "Update script: update_passwords()";
245         print "\nIt appears that you need to update the user passwords in your\n" .
246           "database. If you have already done this (if you've run this update\n" .
247           "script once before, for example), doing so again will make all your\n" .
248           "user accounts inaccessible, so be sure you only do this once.\n" .
249           "Update user passwords? (yes/no)";
251         $resp = readconsole();
252     if ( ! ( "Y" == $resp{0} || "y" == $resp{0} ) ) { return; }
254         $sql = "SELECT user_id,user_password FROM user";
255         $source = $wgDatabase->query( $sql, $fname );
257         while ( $row = $wgDatabase->fetchObject( $source ) ) {
258                 $id = $row->user_id;
259                 $oldpass = $row->user_password;
260                 $newpass = md5( "{$id}-{$oldpass}" );
262                 $sql = "UPDATE user SET user_password='{$newpass}' " .
263                   "WHERE user_id={$id}";
264                 $wgDatabase->query( $sql, $fname );
265         }
268 function do_interwiki_update() {
269         # Check that interwiki table exists; if it doesn't source it
270         global $wgDatabase, $IP;
271         if( $wgDatabase->tableExists( "interwiki" ) ) {
272                 echo "...already have interwiki table\n";
273                 return true;
274         }
275         echo "Creating interwiki table: ";
276         dbsource( archive("patch-interwiki.sql") );
277         echo "ok\n";
278         echo "Adding default interwiki definitions: ";
279         dbsource( "$IP/maintenance/interwiki.sql" );
280         echo "ok\n";
283 function do_index_update() {
284         # Check that proper indexes are in place
285         global $wgDatabase;
286         $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
287         if( !$meta->isMultipleKey() ) {
288                 echo "Updating indexes to 20031107: ";
289                 dbsource( archive("patch-indexes.sql") );
290                 echo "ok\n";
291                 return true;
292         }
293         echo "...indexes seem up to 20031107 standards\n";
294         return false;
297 function do_image_index_update() {
298         global $wgDatabase;
300         $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
301         if( !$meta->isMultipleKey() ) {
302                 echo "Updating indexes to 20050912: ";
303                 dbsource( archive("patch-mimesearch-indexes.sql") );
304                 echo "ok\n";
305                 return true;
306         }
307         echo "...indexes seem up to 20050912 standards\n";
308         return false;
311 function do_image_name_unique_update() {
312         global $wgDatabase;
313         if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
314                 echo "...image primary key already set.\n";
315         } else {
316                 echo "Making img_name the primary key... ";
317                 dbsource( archive("patch-image_name_primary.sql"), $wgDatabase );
318                 echo "ok\n";
319         }
322 function do_logging_timestamp_index() {
323         global $wgDatabase;
324         if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
325                 echo "...timestamp key on logging already exists.\n";
326         } else {
327                 echo "Adding timestamp key on logging table... ";
328                 dbsource( archive("patch-logging-times-index.sql"), $wgDatabase );
329                 echo "ok\n";
330         }
333 function do_archive_user_index() {
334         global $wgDatabase;
335         if( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
336                 echo "...usertext,timestamp key on archive already exists.\n";
337         } else {
338                 echo "Adding usertext,timestamp key on archive table... ";
339                 dbsource( archive("patch-archive-user-index.sql"), $wgDatabase );
340                 echo "ok\n";
341         }
344 function do_image_user_index() {
345         global $wgDatabase;
346         if( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
347                 echo "...usertext,timestamp key on image already exists.\n";
348         } else {
349                 echo "Adding usertext,timestamp key on image table... ";
350                 dbsource( archive("patch-image-user-index.sql"), $wgDatabase );
351                 echo "ok\n";
352         }
355 function do_oldimage_user_index() {
356         global $wgDatabase;
357         if( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
358                 echo "...usertext,timestamp key on oldimage already exists.\n";
359         } else {
360                 echo "Adding usertext,timestamp key on oldimage table... ";
361                 dbsource( archive("patch-oldimage-user-index.sql"), $wgDatabase );
362                 echo "ok\n";
363         }
366 function do_watchlist_update() {
367         global $wgDatabase;
368         $fname = 'do_watchlist_update';
369         if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
370                 echo "The watchlist table is already set up for email notification.\n";
371         } else {
372                 echo "Adding wl_notificationtimestamp field for email notification management.";
373                 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
374                 dbsource( archive( 'patch-email-notification.sql' ), $wgDatabase );
375                 echo "ok\n";
376         }
377         # Check if we need to add talk page rows to the watchlist
378         $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
379         $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
380         if ( $talk != $nontalk ) {
381                 echo "Adding missing watchlist talk page rows... ";
382                 flush();
384                 $wgDatabase->insertSelect( 'watchlist', 'watchlist', 
385                         array(
386                                 'wl_user' => 'wl_user',
387                                 'wl_namespace' => 'wl_namespace | 1',
388                                 'wl_title' => 'wl_title',
389                                 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
390                         ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
391                 echo "ok\n";
392         } else {
393                 echo "...watchlist talk page rows already present\n";
394         }
397 function do_copy_newtalk_to_watchlist() {
398         global $wgDatabase;
399         global $wgCommandLineMode;      # this needs to be saved while getID() and getName() are called
401         $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
402                 $wgDatabase->tableName( 'user_newtalk' ) );
403         $num_newtalks=$wgDatabase->numRows($res);
404         echo "Now converting ".$num_newtalks." user_newtalk entries to watchlist table entries ... \n";
406         $user = new User();
407         for ( $i = 1; $i <= $num_newtalks; $i++ ) {
408                 $wluser = $wgDatabase->fetchObject( $res );
409                 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
410                         if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
411                                 $wgDatabase->replace( 'watchlist',
412                                         array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
413                                           array('wl_user'                       => 0,
414                                                 'wl_namespace'                  => NS_USER_TALK,
415                                                 'wl_title'                      => $wluser->user_ip,
416                                                 'wl_notificationtimestamp'      => '19700101000000'
417                                                 ), 'updaters.inc::do_watchlist_update2'
418                                         );
419                         }
420                 } else { # normal users ... have user_ids
421                         $user->setID($wluser->user_id);
422                         $wgDatabase->replace( 'watchlist',
423                                 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
424                                   array('wl_user'                       => $user->getID(),
425                                         'wl_namespace'                  => NS_USER_TALK,
426                                         'wl_title'                      => $user->getName(),
427                                         'wl_notificationtimestamp'      => '19700101000000'
428                                         ), 'updaters.inc::do_watchlist_update3'
429                                 );
430                 }
431         }
432         echo "Done.\n";
436 function do_user_update() {
437         global $wgDatabase;
438         if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
439                 echo "User table contains old email authentication field. Dropping... ";
440                 dbsource( archive( 'patch-email-authentication.sql' ), $wgDatabase );
441                 echo "ok\n";
442         } else {
443                 echo "...user table does not contain old email authentication field.\n";
444         }
448  * 1.4 betas were missing the 'binary' marker from logging.log_title,
449  * which causes a collation mismatch error on joins in MySQL 4.1.
450  */
451 function check_bin( $table, $field, $patchFile ) {
452         global $wgDatabase, $wgDBtype;
453         if ($wgDBtype != 'mysql')
454                 return;
455         $tableName = $wgDatabase->tableName( $table );
456         $res = $wgDatabase->query( "SELECT $field FROM $tableName LIMIT 0" );
457         $flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
458         $wgDatabase->freeResult( $res );
460         if( in_array( 'binary', $flags ) ) {
461                 echo "$table table has correct $field encoding.\n";
462         } else {
463                 echo "Fixing $field encoding on $table table... ";
464                 dbsource( archive( $patchFile ), $wgDatabase );
465                 echo "ok\n";
466         }
469 function do_schema_restructuring() {
470         global $wgDatabase;
471         $fname="do_schema_restructuring";
472         if ( $wgDatabase->tableExists( 'page' ) ) {
473                 echo "...page table already exists.\n";
474         } else {
475                 echo "...converting from cur/old to page/revision/text DB structure.\n"; flush();
476                 echo wfTimestamp( TS_DB );
477                 echo "......checking for duplicate entries.\n"; flush();
479                 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
481                 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
482                                 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
484                 if ( $wgDatabase->numRows( $rows ) > 0 ) {
485                         echo wfTimestamp( TS_DB );
486                         echo "......<b>Found duplicate entries</b>\n";
487                         echo ( sprintf( "<b>      %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
488                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
489                                 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
490                                         $duplicate[$row->cur_namespace] = array();
491                                 }
492                                 $duplicate[$row->cur_namespace][] = $row->cur_title;
493                                 echo ( sprintf( "      %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
494                         }
495                         $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
496                         $firstCond = true;
497                         foreach ( $duplicate as $ns => $titles ) {
498                                 if ( $firstCond ) {
499                                         $firstCond = false;
500                                 } else {
501                                         $sql .= ' OR ';
502                                 }
503                                 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
504                                 $first = true;
505                                 foreach ( $titles as $t ) {
506                                         if ( $first ) {
507                                                 $sql .= $wgDatabase->addQuotes( $t );
508                                                 $first = false;
509                                         } else {
510                                                 $sql .= ', ' . $wgDatabase->addQuotes( $t );
511                                         }
512                                 }
513                                 $sql .= ") ) \n";
514                         }
515                         # By sorting descending, the most recent entry will be the first in the list.
516                         # All following entries will be deleted by the next while-loop.
517                         $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
519                         $rows = $wgDatabase->query( $sql, $fname );
521                         $prev_title = $prev_namespace = false;
522                         $deleteId = array();
524                         while ( $row = $wgDatabase->fetchObject( $rows ) ) {
525                                 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
526                                         $deleteId[] = $row->cur_id;
527                                 }
528                                 $prev_title     = $row->cur_title;
529                                 $prev_namespace = $row->cur_namespace;
530                         }
531                         $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
532                         $rows = $wgDatabase->query( $sql, $fname );
533                         echo wfTimestamp( TS_DB );
534                         echo "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n";
535                 }
538                 echo wfTimestamp( TS_DB );
539                 echo "......Creating tables.\n";
540                 $wgDatabase->query("CREATE TABLE $page (
541                         page_id int(8) unsigned NOT NULL auto_increment,
542                         page_namespace int NOT NULL,
543                         page_title varchar(255) binary NOT NULL,
544                         page_restrictions tinyblob NOT NULL,
545                         page_counter bigint(20) unsigned NOT NULL default '0',
546                         page_is_redirect tinyint(1) unsigned NOT NULL default '0',
547                         page_is_new tinyint(1) unsigned NOT NULL default '0',
548                         page_random real unsigned NOT NULL,
549                         page_touched char(14) binary NOT NULL default '',
550                         page_latest int(8) unsigned NOT NULL,
551                         page_len int(8) unsigned NOT NULL,
553                         PRIMARY KEY page_id (page_id),
554                         UNIQUE INDEX name_title (page_namespace,page_title),
555                         INDEX (page_random),
556                         INDEX (page_len)
557                         ) TYPE=InnoDB", $fname );
558                 $wgDatabase->query("CREATE TABLE $revision (
559                         rev_id int(8) unsigned NOT NULL auto_increment,
560                         rev_page int(8) unsigned NOT NULL,
561                         rev_comment tinyblob NOT NULL,
562                         rev_user int(5) unsigned NOT NULL default '0',
563                         rev_user_text varchar(255) binary NOT NULL default '',
564                         rev_timestamp char(14) binary NOT NULL default '',
565                         rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
566                         rev_deleted tinyint(1) unsigned NOT NULL default '0',
567                         rev_len int(8) unsigned,
568                         rev_parent_id int(8) unsigned default NULL,
569                         PRIMARY KEY rev_page_id (rev_page, rev_id),
570                         UNIQUE INDEX rev_id (rev_id),
571                         INDEX rev_timestamp (rev_timestamp),
572                         INDEX page_timestamp (rev_page,rev_timestamp),
573                         INDEX user_timestamp (rev_user,rev_timestamp),
574                         INDEX usertext_timestamp (rev_user_text,rev_timestamp)
575                         ) TYPE=InnoDB", $fname );
577                 echo wfTimestamp( TS_DB );
578                 echo "......Locking tables.\n";
579                 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
581                 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
582                 echo wfTimestamp( TS_DB );
583                 echo "......maxold is {$maxold}\n";
585                 echo wfTimestamp( TS_DB );
586                 global $wgLegacySchemaConversion;
587                 if( $wgLegacySchemaConversion ) {
588                         // Create HistoryBlobCurStub entries.
589                         // Text will be pulled from the leftover 'cur' table at runtime.
590                         echo "......Moving metadata from cur; using blob references to text in cur table.\n";
591                         $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
592                         $cur_flags = "'object'";
593                 } else {
594                         // Copy all cur text in immediately: this may take longer but avoids
595                         // having to keep an extra table around.
596                         echo "......Moving text from cur.\n";
597                         $cur_text = 'cur_text';
598                         $cur_flags = "''";
599                 }
600                 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
601                                 old_timestamp, old_minor_edit, old_flags)
602                         SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
603                         FROM $cur", $fname );
605                 echo wfTimestamp( TS_DB );
606                 echo "......Setting up revision table.\n";
607                 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
608                                 rev_minor_edit)
609                         SELECT old_id, cur_id, old_comment, old_user, old_user_text,
610                                 old_timestamp, old_minor_edit
611                         FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
613                 echo wfTimestamp( TS_DB );
614                 echo "......Setting up page table.\n";
615                 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
616                                 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
617                         SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
618                                 cur_random, cur_touched, rev_id, LENGTH(cur_text)
619                         FROM $cur,$revision
620                         WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
622                 echo wfTimestamp( TS_DB );
623                 echo "......Unlocking tables.\n";
624                 $wgDatabase->query( "UNLOCK TABLES", $fname );
626                 echo wfTimestamp( TS_DB );
627                 echo "......Renaming old.\n";
628                 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
630                 echo wfTimestamp( TS_DB );
631                 echo "...done.\n";
632         }
635 function do_inverse_timestamp() {
636         global $wgDatabase;
637         if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
638                 echo "Removing revision.inverse_timestamp and fixing indexes... ";
639                 dbsource( archive( 'patch-inverse_timestamp.sql' ), $wgDatabase );
640                 echo "ok\n";
641         } else {
642                 echo "revision timestamp indexes already up to 2005-03-13\n";
643         }
646 function do_text_id() {
647         global $wgDatabase;
648         if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
649                 echo "...rev_text_id already in place.\n";
650         } else {
651                 echo "Adding rev_text_id field... ";
652                 dbsource( archive( 'patch-rev_text_id.sql' ), $wgDatabase );
653                 echo "ok\n";
654         }
657 function do_namespace_size() {
658         $tables = array(
659                 'page'          => 'page',
660                 'archive'       => 'ar',
661                 'recentchanges' => 'rc',
662                 'watchlist'     => 'wl',
663                 'querycache'    => 'qc',
664                 'logging'       => 'log',
665         );
666         foreach( $tables as $table => $prefix ) {
667                 do_namespace_size_on( $table, $prefix );
668                 flush();
669         }
672 function do_namespace_size_on( $table, $prefix ) {
673         global $wgDatabase, $wgDBtype;
674         if ($wgDBtype != 'mysql')
675                 return;
676         $field = $prefix . '_namespace';
678         $tablename = $wgDatabase->tableName( $table );
679         $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
680         $info = $wgDatabase->fetchObject( $result );
681         $wgDatabase->freeResult( $result );
683         if( substr( $info->Type, 0, 3 ) == 'int' ) {
684                 echo "...$field is already a full int ($info->Type).\n";
685         } else {
686                 echo "Promoting $field from $info->Type to int... ";
688                 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
689                 $wgDatabase->query( $sql );
691                 echo "ok\n";
692         }
695 function do_pagelinks_update() {
696         global $wgDatabase;
697         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
698                 echo "...already have pagelinks table.\n";
699         } else {
700                 echo "Converting links and brokenlinks tables to pagelinks... ";
701                 dbsource( archive( 'patch-pagelinks.sql' ), $wgDatabase );
702                 echo "ok\n";
703                 flush();
705                 global $wgCanonicalNamespaceNames;
706                 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
707                         if( $ns != 0 ) {
708                                 do_pagelinks_namespace( $ns );
709                         }
710                 }
711         }
714 function do_pagelinks_namespace( $namespace ) {
715         global $wgDatabase, $wgContLang;
717         $ns = intval( $namespace );
718         echo "Cleaning up broken links for namespace $ns... ";
720         $pagelinks = $wgDatabase->tableName( 'pagelinks' );
721         $name = $wgContLang->getNsText( $ns );
722         $prefix = $wgDatabase->strencode( $name );
723         $likeprefix = str_replace( '_', '\\_', $prefix);
725         $sql = "UPDATE $pagelinks
726                    SET pl_namespace=$ns,
727                        pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
728                  WHERE pl_namespace=0
729                    AND pl_title LIKE '$likeprefix:%'";
731         $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
732         echo "ok\n";
735 function do_drop_img_type() {
736         global $wgDatabase;
738         if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
739                 echo "Dropping unused img_type field in image table... ";
740                 dbsource( archive( 'patch-drop_img_type.sql' ), $wgDatabase );
741                 echo "ok\n";
742         } else {
743                 echo "No img_type field in image table; Good.\n";
744         }
747 function do_old_links_update() {
748         global $wgDatabase;
749         if( $wgDatabase->tableExists( 'pagelinks' ) ) {
750                 echo "Already have pagelinks; skipping old links table updates.\n";
751         } else {
752                 convertLinks(); flush();
753         }
756 function do_user_unique_update() {
757         global $wgDatabase;
758         $duper = new UserDupes( $wgDatabase );
759         if( $duper->hasUniqueIndex() ) {
760                 echo "Already have unique user_name index.\n";
761         } else {
762                 if( !$duper->clearDupes() ) {
763                         echo "WARNING: This next step will probably fail due to unfixed duplicates...\n";
764                 }
765                 echo "Adding unique index on user_name... ";
766                 dbsource( archive( 'patch-user_nameindex.sql' ), $wgDatabase );
767                 echo "ok\n";
768         }
771 function do_user_groups_update() {
772         $fname = 'do_user_groups_update';
773         global $wgDatabase;
775         if( $wgDatabase->tableExists( 'user_groups' ) ) {
776                 echo "...user_groups table already exists.\n";
777                 return do_user_groups_reformat();
778         }
780         echo "Adding user_groups table... ";
781         dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
782         echo "ok\n";
784         if( !$wgDatabase->tableExists( 'user_rights' ) ) {
785                 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
786                         echo "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion...";
787                         dbsource( archive( 'patch-user_rights.sql' ), $wgDatabase );
788                         echo "ok\n";
789                 } else {
790                         echo "*** WARNING: couldn't locate user_rights table or field for upgrade.\n";
791                         echo "*** You may need to manually configure some sysops by manipulating\n";
792                         echo "*** the user_groups table.\n";
793                         return;
794                 }
795         }
797         echo "Converting user_rights table to user_groups... ";
798         $result = $wgDatabase->select( 'user_rights',
799                 array( 'ur_user', 'ur_rights' ),
800                 array( "ur_rights != ''" ),
801                 $fname );
803         while( $row = $wgDatabase->fetchObject( $result ) ) {
804                 $groups = array_unique(
805                         array_map( 'trim',
806                                 explode( ',', $row->ur_rights ) ) );
808                 foreach( $groups as $group ) {
809                         $wgDatabase->insert( 'user_groups',
810                                 array(
811                                         'ug_user'  => $row->ur_user,
812                                         'ug_group' => $group ),
813                                 $fname );
814                 }
815         }
816         $wgDatabase->freeResult( $result );
817         echo "ok\n";
820 function do_user_groups_reformat() {
821         # Check for bogus formats from previous 1.5 alpha code.
822         global $wgDatabase;
823         $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
825         if( $info->type() == 'int' ) {
826                 $oldug = $wgDatabase->tableName( 'user_groups' );
827                 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
828                 echo "user_groups is in bogus intermediate format. Renaming to $newug... ";
829                 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
830                 echo "ok\n";
832                 echo "Re-adding fresh user_groups table... ";
833                 dbsource( archive( 'patch-user_groups.sql' ), $wgDatabase );
834                 echo "ok\n";
836                 echo "***\n";
837                 echo "*** WARNING: You will need to manually fix up user permissions in the user_groups\n";
838                 echo "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n";
839                 echo "***\n";
840         } else {
841                 echo "...user_groups is in current format.\n";
842         }
846 function do_watchlist_null() {
847         # Make sure wl_notificationtimestamp can be NULL,
848         # and update old broken items.
849         global $wgDatabase;
850         $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
852         if( !$info->nullable() ) {
853                 echo "Making wl_notificationtimestamp nullable... ";
854                 dbsource( archive( 'patch-watchlist-null.sql' ), $wgDatabase );
855                 echo "ok\n";
856         } else {
857                 echo "...wl_notificationtimestamp is already nullable.\n";
858         }
863  * @bug 3946
864  */
865 function do_page_random_update() {
866         global $wgDatabase;
868         echo "Setting page_random to a random value on rows where it equals 0...";
870         $page = $wgDatabase->tableName( 'page' );
871         $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
872         $rows = $wgDatabase->affectedRows();
874         echo "changed $rows rows\n";
877 function do_templatelinks_update() {
878         global $wgDatabase, $wgLoadBalancer;
879         $fname = 'do_templatelinks_update';
881         if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
882                 echo "...templatelinks table already exists\n";
883                 return;
884         }
885         echo "Creating templatelinks table...\n";
886         dbsource( archive('patch-templatelinks.sql'), $wgDatabase );
887         echo "Populating...\n";
888         if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
889                 // Slow, replication-friendly update
890                 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
891                         array( 'pl_namespace' => NS_TEMPLATE ), $fname );
892                 $count = 0;
893                 while ( $row = $wgDatabase->fetchObject( $res ) ) {
894                         $count = ($count + 1) % 100;
895                         if ( $count == 0 ) {
896                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
897                                         wfWaitForSlaves( 10 );
898                                 } else {
899                                         sleep( 1 );
900                                 }
901                         }
902                         $wgDatabase->insert( 'templatelinks',
903                                 array(
904                                         'tl_from' => $row->pl_from,
905                                         'tl_namespace' => $row->pl_namespace,
906                                         'tl_title' => $row->pl_title,
907                                 ), $fname
908                         );
910                 }
911                 $wgDatabase->freeResult( $res );
912         } else {
913                 // Fast update
914                 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
915                         array(
916                                 'tl_from' => 'pl_from',
917                                 'tl_namespace' => 'pl_namespace',
918                                 'tl_title' => 'pl_title'
919                         ), array(
920                                 'pl_namespace' => 10
921                         ), $fname
922                 );
923         }
924         echo "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n";
927 // Add index on ( rc_namespace, rc_user_text ) [Jul. 2006]
928 // Add index on ( rc_user_text, rc_timestamp ) [Nov. 2006]
929 function do_rc_indices_update() {
930         global $wgDatabase;
931         echo( "Checking for additional recent changes indices...\n" );
933         $indexes = array(
934                 'rc_ns_usertext' => 'patch-recentchanges-utindex.sql',
935                 'rc_user_text' => 'patch-rc_user_text-index.sql',
936         );
937         
938         foreach( $indexes as $index => $patch ) {
939                 $info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
940                 if( !$info ) {
941                         echo( "...index `{$index}` not found; adding..." );
942                         dbsource( archive( $patch ) );
943                         echo( "done.\n" );
944                 } else {
945                         echo( "...index `{$index}` seems ok.\n" );
946                 }
947         }
950 function index_has_field($table, $index, $field) {
951         global $wgDatabase;
952         echo( "Checking if $table index $index includes field $field...\n" );
953         $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
954         if( $info ) {
955                 foreach($info as $row) {
956                         if($row->Column_name == $field) {
957                                 echo( "...index $index on table $table seems to be ok\n" );
958                                 return true;
959                         }
960                 }
961         }
962         echo( "...index $index on table $table has no field $field; adding\n" );
963         return false;
966 function do_backlinking_indices_update() {
967         echo( "Checking for backlinking indices...\n" );
968         if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
969                 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
970                 !index_has_field('imagelinks', 'il_to', 'il_from'))
971         {       
972                 dbsource( archive( 'patch-backlinkindexes.sql' ) );
973                 echo( "...backlinking indices updated\n" );
974         }
977 function do_categorylinks_indices_update() {
978         echo( "Checking for categorylinks indices...\n" );
979         if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
980         {       
981                 dbsource( archive( 'patch-categorylinksindex.sql' ) );
982                 echo( "...categorylinks indices updated\n" );
983         }
986 function do_filearchive_indices_update() {
987         global $wgDatabase;
988         echo( "Checking filearchive indices...\n" );
989         $info = $wgDatabase->indexInfo( 'filearchive', 'fa_user_timestamp', __METHOD__ );
990         if ( !$info )
991         {       
992                 dbsource( archive( 'patch-filearhive-user-index.sql' ) );
993                 echo( "...filearchive indices updated\n" );
994         }
997 function maybe_do_profiling_memory_update() {
998         global $wgDatabase;
999         if ( !$wgDatabase->tableExists( 'profiling' ) ) {
1000                 // Simply ignore
1001         } elseif ( $wgDatabase->fieldExists( 'profiling', 'pf_memory' ) ) {
1002                 echo "profiling table has pf_memory field.\n";
1003         } else {
1004                 echo "Adding pf_memory field to table profiling...";
1005                 dbsource( archive( 'patch-profiling-memory.sql' ), $wgDatabase );
1006                 echo "ok\n";
1007         }
1010 function do_stats_init() {
1011         // Sometimes site_stats table is not properly populated.
1012         global $wgDatabase;
1013         echo "Checking site_stats row...";
1014         $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
1015         if( $row === false ) {
1016                 echo "data is missing! rebuilding...\n";
1017                 
1018                 global $IP;
1019                 require_once "$IP/maintenance/initStats.inc";
1020                 wfInitStats();
1021         } else {
1022                 echo "ok.\n";
1023         }
1026 function purge_cache() {
1027         global $wgDatabase;
1028         # We can't guarantee that the user will be able to use TRUNCATE,
1029         # but we know that DELETE is available to us
1030         echo( "Purging caches..." );
1031         $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
1032         echo( "done.\n" );
1035 function do_all_updates( $shared = false, $purge = true ) {
1036         global $wgNewTables, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgDatabase, $wgDBtype, $IP;
1038         wfRunHooks('LoadExtensionSchemaUpdates');
1040         $doUser = !$wgSharedDB || $shared;
1042         if ($wgDBtype === 'postgres') {
1043                 do_postgres_updates();
1044                 return;
1045         }
1046         
1047         # Run core updates in sequence...
1048         global $wgMysqlUpdates;
1049         foreach( $wgMysqlUpdates as $params ) {
1050                 $func = array_shift( $params );
1051                 call_user_func_array( $func, $params );
1052                 flush();
1053         }
1054         
1055         /// @fixme clean up this mess too!
1056         global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
1057         # Add missing extension tables
1058         foreach ( $wgExtNewTables as $tableRecord ) {
1059                 add_table( $tableRecord[0], $tableRecord[1], true );
1060                 flush();
1061         }
1062         # Add missing extension fields
1063         foreach ( $wgExtNewFields as $fieldRecord ) {
1064                 if ( $fieldRecord[0] != 'user' || $doUser ) {
1065                         add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1066                 }
1067                 flush();
1068         }
1069         # Add missing extension indexes
1070         foreach ( $wgExtNewIndexes as $fieldRecord ) {
1071                 add_index( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1072                 flush();
1073         }
1076         echo "Deleting old default messages (this may take a long time!)..."; flush();
1077         deleteDefaultMessages();
1078         echo "Done\n"; flush();
1079         
1080         do_stats_init(); flush();
1081         
1082         if( $purge ) {
1083                 purge_cache();
1084                 flush();
1085         }
1088 function archive($name) {
1089         global $wgDBtype, $IP;
1090         switch ($wgDBtype) {
1091         case "postgres":
1092                 return "$IP/maintenance/postgres/archives/$name";
1093         default:
1094                 return "$IP/maintenance/archives/$name";
1095         }
1098 function do_restrictions_update() {
1099         # Adding page_restrictions table, obsoleting page.page_restrictions.
1100         #  Migrating old restrictions to new table
1101         # -- Andrew Garrett, January 2007.
1103         global $wgDatabase;
1105         $name = 'page_restrictions';
1106         $patch = 'patch-page_restrictions.sql';
1107         $patch2 = 'patch-page_restrictions_sortkey.sql';
1109         if ( $wgDatabase->tableExists( $name ) ) {
1110                 echo "...$name table already exists.\n";
1111         } else {
1112                 echo "Creating $name table...";
1113                 dbsource( archive($patch), $wgDatabase );
1114                 dbsource( archive($patch2), $wgDatabase );
1115                 echo "ok\n";
1117                 echo "Migrating old restrictions to new table...";
1119                 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
1121                 $count = 0;
1123                 while ($row = $wgDatabase->fetchObject($res) ) {
1124                         $count = ($count + 1) % 100;
1126                         if ($count == 0) {
1127                                 if ( function_exists( 'wfWaitForSlaves' ) ) {
1128                                         wfWaitForSlaves( 10 );
1129                                 } else {
1130                                         sleep( 1 );
1131                                 }
1132                         }
1134                         # Figure out what the restrictions are..
1135                         $id = $row->page_id;
1136                         $flatrestrictions = explode( ':', $row->page_restrictions );
1138                         $restrictions = array ();
1139                         foreach( $flatrestrictions as $restriction ) {
1140                                 $thisrestriction = explode( '=', $restriction, 2 );
1141                                 if( count( $thisrestriction ) == 1 ) {
1142                                         // Compatibility with old protections from before
1143                                         // separate move protection was added.
1144                                         list( $level ) = $thisrestriction;
1145                                         if( $level ) {
1146                                                 $restrictions['edit'] = $level;
1147                                                 $restrictions['move'] = $level;
1148                                         }
1149                                 } else {
1150                                         list( $type, $level ) = $thisrestriction;
1151                                         if( $level ) {
1152                                                 $restrictions[$type] = $level;
1153                                         }
1154                                 }
1156                         $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1158                         }
1159                         
1160                         foreach( $restrictions as $type => $level ) {
1161                                 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1162                                                                                         'pr_type' => $type,
1163                                                                                         'pr_level' => $level,
1164                                                                                         'pr_cascade' => 0,
1165                                                                                         'pr_expiry' => 'infinity' ),
1166                                                                                         __METHOD__ );
1167                         }
1168                 }
1169                 print "ok\n";
1170         }
1173 function do_category_population() {
1174         if( update_row_exists( 'populate category' ) ) {
1175                 echo "...category table already populated.\n";
1176                 return;
1177         }
1178         require_once( 'populateCategory.inc' );
1179         echo "Populating category table, printing progress markers.  ".
1180 "For large databases, you\n".
1181 "may want to hit Ctrl-C and do this manually with maintenance/\n".
1182 "populateCategory.php.\n";
1183         populateCategory( '', 10, 0, true );
1184         echo "Done populating category table.\n";
1187 function do_populate_parent_id() {
1188         if( update_row_exists( 'populate rev_parent_id' ) ) {
1189                 echo "...rev_parent_id column already populated.\n";
1190                 return;
1191         }
1192         require_once( 'populateParentId.inc' );
1193         
1194         global $wgDatabase;
1195         populate_rev_parent_id( $wgDatabase );
1198 function
1199 pg_describe_table($table)
1201 global  $wgDatabase, $wgDBmwschema;
1202         $q = <<<END
1203 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1204         WHERE pg_class.relnamespace = pg_namespace.oid 
1205           AND attrelid=pg_class.oid AND attnum > 0
1206           AND relname=%s AND nspname=%s
1207 END;
1208         $res = $wgDatabase->query(sprintf($q,
1209                         $wgDatabase->addQuotes($table),
1210                         $wgDatabase->addQuotes($wgDBmwschema)));
1211         if (!$res)
1212                 return null;
1214         $cols = array();
1215         while ($r = $wgDatabase->fetchRow($res)) {
1216                 $cols[] = array(        
1217                                 "name" => $r[0],
1218                                 "ord" => $r[1],
1219                         );
1220         }
1221         return $cols;
1224 function
1225 pg_describe_index($idx)
1227 global  $wgDatabase, $wgDBmwschema;
1229         // first fetch the key (which is a list of columns ords) and
1230         // the table the index applies to (an oid)
1231         $q = <<<END
1232 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1233         WHERE nspname=%s
1234           AND pg_class.relnamespace = pg_namespace.oid
1235           AND relname=%s
1236           AND indexrelid=pg_class.oid
1237 END;
1238         $res = $wgDatabase->query(sprintf($q,
1239                         $wgDatabase->addQuotes($wgDBmwschema),
1240                         $wgDatabase->addQuotes($idx)));
1241         if (!$res)
1242                 return null;
1243         if (!($r = $wgDatabase->fetchRow($res))) {
1244                 $wgDatabase->freeResult($res);
1245                 return null;
1246         }
1248         $indkey = $r[0];
1249         $relid = intval($r[1]);
1250         $indkeys = explode(" ", $indkey);
1251         $wgDatabase->freeResult($res);
1253         $colnames = array();
1254         foreach ($indkeys as $rid) {
1255                 $query = <<<END
1256 SELECT attname FROM pg_class, pg_attribute
1257         WHERE attrelid=$relid
1258           AND attnum=%d
1259           AND attrelid=pg_class.oid
1260 END;
1261                 $r2 = $wgDatabase->query(sprintf($query, $rid));
1262                 if (!$r2)
1263                         return null;
1264                 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1265                         $wgDatabase->freeResult($r2);
1266                         return null;
1267                 }
1268                 $colnames[] = $row2[0];
1269                 $wgDatabase->freeResult($r2);
1270         }
1272         return $colnames;
1275 function
1276 pg_index_exists($table, $index)
1278 global  $wgDatabase, $wgDBmwschema;
1279         $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1280                         array(  "indexname" => $index,
1281                                 "tablename" => $table,
1282                                 "schemaname" => $wgDBmwschema));
1283         return $exists === $index;
1286 function
1287 pg_fkey_deltype($fkey)
1289 global  $wgDatabase, $wgDBmwschema;
1290         $q = <<<END
1291 SELECT confdeltype FROM pg_constraint, pg_namespace
1292         WHERE connamespace=pg_namespace.oid
1293           AND nspname=%s
1294           AND conname=%s;
1295 END;
1296         $r = $wgDatabase->query(sprintf($q,
1297                 $wgDatabase->addQuotes($wgDBmwschema),
1298                 $wgDatabase->addQuotes($fkey)));
1299         if (!($row = $wgDatabase->fetchRow($r)))
1300                 return null;
1301         return $row[0];
1304 function
1305 pg_rule_def($table, $rule)
1307 global  $wgDatabase, $wgDBmwschema;
1308         $q = <<<END
1309 SELECT definition FROM pg_rules
1310         WHERE schemaname = %s
1311           AND tablename = %s
1312           AND rulename = %s
1313 END;
1314         $r = $wgDatabase->query(sprintf($q,
1315                         $wgDatabase->addQuotes($wgDBmwschema),
1316                         $wgDatabase->addQuotes($table),
1317                         $wgDatabase->addQuotes($rule)));
1318         $row = $wgDatabase->fetchRow($r);
1319         if (!$row)
1320                 return null;
1321         $d = $row[0];
1322         $wgDatabase->freeResult($r);
1323         return $d;
1326 function do_postgres_updates() {
1327         global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1329         ## Gather version numbers in case we need them
1330         $version = $wgDatabase->getServerVersion(); ## long string
1331         $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
1333         $wgShowExceptionDetails = 1;
1335         # Just in case their LocalSettings.php does not have this:
1336         if ( !isset( $wgDBmwschema ))
1337                 $wgDBmwschema = 'mediawiki';
1339         # Verify that this user is configured correctly
1340         $safeuser = $wgDatabase->addQuotes($wgDBuser);
1341         $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1342         $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1343         $conf = array();
1344         foreach( explode( '*', $config ) as $c ) {
1345                 list( $x,$y ) = explode( '=', $c );
1346                 $conf[$x] = $y;
1347         }
1348         if( !array_key_exists( 'search_path', $conf ) ) {
1349                 $search_path = '';
1350         }
1351         else {
1352                 $search_path = $conf['search_path'];
1353         }
1354         if( strpos( $search_path, $wgDBmwschema ) === false ) {
1355                 echo "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n";
1356                 $search_path = "$wgDBmwschema, $search_path";
1357         }
1358         if( strpos( $search_path, $wgDBts2schema ) === false ) {
1359                 echo "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n";
1360                 $search_path = "$search_path, $wgDBts2schema";
1361         }
1362         if( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
1363                 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
1364                 $wgDatabase->doQuery( "SET search_path = $search_path" );
1365         }
1366         else {
1367                 $path = $conf['search_path'];
1368                 echo "... search_path for user \"$wgDBuser\" looks correct ($path)\n";
1369         }
1370         $goodconf = array(
1371                 'client_min_messages' => 'error',
1372                 'DateStyle'           => 'ISO, YMD',
1373                 'TimeZone'            => 'GMT'
1374         );
1375         foreach( array_keys( $goodconf ) AS $key ) {
1376                 $value = $goodconf[$key];
1377                 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1378                         echo "Setting $key to '$value' for user \"$wgDBuser\"\n";
1379                         $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1380                         $wgDatabase->doQuery( "SET $key = '$value'" );
1381                 }
1382                 else {
1383                         echo "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n";
1384                 }
1385         }
1387         $newsequences = array(
1388                 "log_log_id_seq",
1389                 "pr_id_val",
1390         );
1392         $newtables = array(
1393                 array("category",          "patch-category.sql"),
1394                 array("mediawiki_version", "patch-mediawiki_version.sql"),
1395                 array("mwuser",            "patch-mwuser.sql"),
1396                 array("pagecontent",       "patch-pagecontent.sql"),
1397                 array("querycachetwo",     "patch-querycachetwo.sql"),
1398                 array("page_props",        "patch-page_props.sql"),
1399                 array("page_restrictions", "patch-page_restrictions.sql"),
1400                 array("profiling",         "patch-profiling.sql"),
1401                 array("protected_titles",  "patch-protected_titles.sql"),
1402                 array("redirect",          "patch-redirect.sql"),
1403                 array("updatelog",         "patch-updatelog.sql"),
1404         );
1406         $newcols = array(
1407                 array("archive",       "ar_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1408                 array("archive",       "ar_len",               "INTEGER"),
1409                 array("archive",       "ar_page_id",           "INTEGER"),
1410                 array("archive",       "ar_parent_id",         "INTEGER"),
1411                 array("image",         "img_sha1",             "TEXT NOT NULL DEFAULT ''"),
1412                 array("ipblocks",      "ipb_anon_only",        "CHAR NOT NULL DEFAULT '0'"),
1413                 array("ipblocks",      "ipb_by_text",          "TEXT NOT NULL DEFAULT ''"),
1414                 array("ipblocks",      "ipb_block_email",      "CHAR NOT NULL DEFAULT '0'"),
1415                 array("ipblocks",      "ipb_create_account",   "CHAR NOT NULL DEFAULT '1'"),
1416                 array("ipblocks",      "ipb_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1417                 array("ipblocks",      "ipb_enable_autoblock", "CHAR NOT NULL DEFAULT '1'"),
1418                 array("filearchive",   "fa_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1419                 array("logging",       "log_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1420                 array("logging",       "log_id",               "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1421                 array("logging",       "log_params",           "TEXT"),
1422                 array("mwuser",        "user_editcount",       "INTEGER"),
1423                 array("mwuser",        "user_newpass_time",    "TIMESTAMPTZ"),
1424                 array("oldimage",      "oi_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1425                 array("oldimage",      "oi_metadata",          "BYTEA NOT NULL DEFAULT ''"),
1426                 array("oldimage",      "oi_media_type",        "TEXT"),
1427                 array("oldimage",      "oi_major_mime",        "TEXT NOT NULL DEFAULT 'unknown'"),
1428                 array("oldimage",      "oi_minor_mime",        "TEXT NOT NULL DEFAULT 'unknown'"),
1429                 array("oldimage",      "oi_sha1",              "TEXT NOT NULL DEFAULT ''"),
1430                 array("page_restrictions", "pr_id",            "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1431                 array("profiling",     "pf_memory",            "NUMERIC(18,10) NOT NULL DEFAULT 0"),
1432                 array("recentchanges", "rc_deleted",           "SMALLINT NOT NULL DEFAULT 0"),
1433                 array("recentchanges", "rc_log_action",        "TEXT"),
1434         array("recentchanges", "rc_log_type",          "TEXT"),
1435         array("recentchanges", "rc_logid",             "INTEGER NOT NULL DEFAULT 0"),
1436                 array("recentchanges", "rc_new_len",           "INTEGER"),
1437                 array("recentchanges", "rc_old_len",           "INTEGER"),
1438                 array("recentchanges", "rc_params",            "TEXT"),
1439                 array("revision",      "rev_len",              "INTEGER"),
1440                 array("revision",      "rev_deleted",          "SMALLINT NOT NULL DEFAULT 0"),
1441                 array("user_newtalk",  "user_last_timestamp",  "TIMESTAMPTZ"),
1442         );
1445         # table, column, desired type, USING clause if needed (with new default if needed)
1446         $typechanges = array(
1447                 array("archive",      "ar_deleted",      "smallint", ""),
1448                 array("archive",      "ar_minor_edit",   "smallint", "ar_minor_edit::smallint DEFAULT 0"),
1449                 array("filearchive",  "fa_deleted",      "smallint", ""),
1450                 array("filearchive",  "fa_height",       "integer",  ""),
1451                 array("filearchive",  "fa_metadata",     "bytea",    "decode(fa_metadata,'escape')"),
1452                 array("filearchive",  "fa_size",         "integer",  ""),
1453                 array("filearchive",  "fa_width",        "integer",  ""),
1454                 array("filearchive",  "fa_storage_group","text",     ""),
1455                 array("filearchive",  "fa_storage_key",  "text",     ""),
1456                 array("image",        "img_metadata",    "bytea",    "decode(img_metadata,'escape')"),
1457                 array("image",        "img_size",        "integer",  ""),
1458                 array("image",        "img_width",       "integer",  ""),
1459                 array("image",        "img_height",      "integer",  ""),
1460                 array("interwiki",    "iw_local",        "smallint", "iw_local::smallint DEFAULT 0"),
1461                 array("interwiki",    "iw_trans",        "smallint", "iw_trans::smallint DEFAULT 0"),
1462                 array("ipblocks",     "ipb_auto",        "smallint", "ipb_auto::smallint DEFAULT 0"),
1463                 array("ipblocks",     "ipb_anon_only",   "smallint", "ipb_anon_only::smallint DEFAULT 0"),
1464                 array("ipblocks",     "ipb_create_account", "smallint", "ipb_create_account::smallint DEFAULT 1"),
1465                 array("ipblocks",     "ipb_enable_autoblock", "smallint", "ipb_enable_autoblock::smallint DEFAULT 1"),
1466                 array("ipblocks",     "ipb_block_email", "smallint", "ipb_block_email::smallint DEFAULT 0"),
1467                 array("ipblocks",     "ipb_address",     "text",     "ipb_address::text"),
1468                 array("ipblocks",     "ipb_deleted",     "smallint", "ipb_deleted::smallint"),
1469                 array("math",         "math_inputhash",  "bytea",    "decode(math_inputhash,'escape')"),
1470                 array("math",         "math_outputhash", "bytea",    "decode(math_outputhash,'escape')"),
1471                 array("mwuser",       "user_token",      "text",     ""),
1472                 array("mwuser",       "user_email_token","text",     ""),
1473                 array("objectcache",  "keyname",         "text",     ""),
1474                 array("oldimage",     "oi_height",       "integer",  ""),
1475                 array("oldimage",     "oi_size",         "integer",  ""),
1476                 array("oldimage",     "oi_width",        "integer",  ""),
1477                 array("page",         "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
1478                 array("page",         "page_is_new",     "smallint", "page_is_new::smallint DEFAULT 0"),
1479                 array("querycache",   "qc_value",        "integer",  ""),
1480                 array("querycachetwo","qcc_value",       "integer",  ""),
1481                 array("recentchanges","rc_bot",          "smallint", "rc_bot::smallint DEFAULT 0"),
1482                 array("recentchanges","rc_deleted",      "smallint", ""),
1483                 array("recentchanges","rc_minor",        "smallint", "rc_minor::smallint DEFAULT 0"),
1484                 array("recentchanges","rc_new",          "smallint", "rc_new::smallint DEFAULT 0"),
1485                 array("recentchanges","rc_type",         "smallint", "rc_type::smallint DEFAULT 0"),
1486                 array("recentchanges","rc_patrolled",    "smallint", "rc_patrolled::smallint DEFAULT 0"),
1487                 array("revision",     "rev_deleted",     "smallint", "rev_deleted::smallint DEFAULT 0"),
1488                 array("revision",     "rev_minor_edit",  "smallint", "rev_minor_edit::smallint DEFAULT 0"),
1489                 array("templatelinks","tl_namespace",    "smallint", "tl_namespace::smallint"),
1490                 array("user_newtalk", "user_ip",         "text",     "host(user_ip)"),
1491         );
1493         $newindexes = array(
1494                 array("archive",       "archive_user_text", "(ar_user_text)"),
1495                 array("image",         "img_sha1",          "(img_sha1)"),
1496                 array("oldimage",      "oi_sha1",           "(oi_sha1)"),
1497                 array("revision",      "rev_text_id_idx",   "(rev_text_id)"),
1498         );
1500         $newrules = array(
1501         );
1503         foreach ($newsequences as $ns) {
1504                 if ($wgDatabase->sequenceExists($ns)) {
1505                         echo "... sequence \"$ns\" already exists\n";
1506                         continue;
1507                 }
1509                 echo "Creating sequence \"$ns\"\n";
1510                 $wgDatabase->query("CREATE SEQUENCE $ns");
1511         }
1513         foreach ($newtables as $nt) {
1514                 if ($wgDatabase->tableExists($nt[0])) {
1515                         echo "... table \"$nt[0]\" already exists\n";
1516                         continue;
1517                 }
1519                 echo "Creating table \"$nt[0]\"\n";
1520                 dbsource(archive($nt[1]));
1521         }
1523         ## Needed before newcols
1524         if ($wgDatabase->tableExists("archive2")) {
1525                 echo "Converting \"archive2\" back to normal archive table\n";
1526                 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1527                         echo "Dropping rule \"archive_insert\"\n";
1528                         $wgDatabase->query("DROP RULE archive_insert ON archive");
1529                 }
1530                 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1531                         echo "Dropping rule \"archive_delete\"\n";
1532                         $wgDatabase->query("DROP RULE archive_delete ON archive");
1533                 }
1534                 dbsource(archive("patch-remove-archive2.sql"));
1535         }
1536         else
1537                 echo "... obsolete table \"archive2\" does not exist\n";
1539         foreach ($newcols as $nc) {
1540                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1541                 if (!is_null($fi)) {
1542                         echo "... column \"$nc[0].$nc[1]\" already exists\n";
1543                         continue;
1544                 }
1546                 echo "Adding column \"$nc[0].$nc[1]\"\n";
1547                 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1548         }
1550         foreach ($typechanges as $tc) {
1551                 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1552                 if (is_null($fi)) {
1553                         echo "... error: expected column $tc[0].$tc[1] to exist\n";
1554                         exit(1);
1555                 }
1557                 if ($fi->type() === $tc[2])
1558                         echo "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n";
1559                 else {
1560                         echo "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n";
1561                         $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1562                         if (strlen($tc[3])) {
1563                                 $default = array();
1564                                 if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
1565                                         $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1566                                         $wgDatabase->query($sqldef);
1567                                         $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
1568                                 }
1569                                 $sql .= " USING $tc[3]";
1570                         }
1571                         $sql .= ";\nCOMMIT;\n";
1572                         $wgDatabase->query($sql);
1573                 }
1574         }
1576         if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
1577                 echo "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n";
1578                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1579                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1580                 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1581         }
1582         else
1583                 echo "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n";
1586         foreach ($newindexes as $ni) {
1587                 if (pg_index_exists($ni[0], $ni[1])) {
1588                         echo "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n";
1589                         continue;
1590                 }
1591                 echo "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n";
1592                 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1593         }
1595         foreach ($newrules as $nr) {
1596                 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1597                         echo "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n";
1598                         continue;
1599                 }
1600                 echo "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n";
1601                 dbsource(archive($nr[2]));
1602         }
1604         if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
1605                 echo "Making foriegn key on table \"oldimage\" (to image) a cascade delete\n";
1606                 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1607                 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascade ".
1608                         "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE" );
1609         }
1610         else
1611                 echo "... table \"oldimage\" has correct cascade delete foreign key to image\n";
1613         if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1614                 echo "Adding function and trigger \"page_deleted\" to table \"page\"\n";
1615                 dbsource(archive('patch-page_deleted.sql'));
1616         }
1617         else
1618                 echo "... table \"page\" has \"page_deleted\" trigger\n";
1620         $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1621         if (!$fi->nullable()) {
1622                 echo "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n";
1623                 dbsource(archive('patch-rc_cur_id-not-null.sql'));
1624         }
1625         else
1626                 echo "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n";
1628         $pu = pg_describe_index("pagelink_unique");
1629         if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1630                 echo "Dropping obsolete version of index \"pagelink_unique index\"\n";
1631                 $wgDatabase->query("DROP INDEX pagelink_unique");
1632                 $pu = null;
1633         }
1634         else
1635                 echo "... obsolete version of index \"pagelink_unique index\" does not exist\n";
1637         if (is_null($pu)) {
1638                 echo "Creating index \"pagelink_unique index\"\n";
1639                 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1640         }
1641         else
1642                 echo "... index \"pagelink_unique_index\" aready exists\n";
1644         if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1645                 echo "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n";
1646         }
1647         else {
1648                 echo "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n";
1649                 dbsource(archive('patch-revision_rev_user_fkey.sql'));
1650         }
1652         global $wgExtNewTables, $wgExtPGNewFields, $wgExtNewIndexes;
1653         # Add missing extension tables
1654         foreach ( $wgExtNewTables as $nt ) {
1655                 if ($wgDatabase->tableExists($nt[0])) {
1656                         echo "... table \"$nt[0]\" already exists\n";
1657                         continue;
1658                 }
1659                 echo "Creating table \"$nt[0]\"\n";
1660                 dbsource($nt[1]);
1661         }
1662         # Add missing extension fields
1663         foreach ( $wgExtPGNewFields as $nc ) {
1664                 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1665                 if (!is_null($fi)) {
1666                         echo "... column \"$nc[0].$nc[1]\" already exists\n";
1667                         continue;
1668                 }
1669                 echo "Adding column \"$nc[0].$nc[1]\"\n";
1670                 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1671         }
1672         # Add missing extension indexes
1673         foreach ( $wgExtNewIndexes as $ni ) {
1674                 if (pg_index_exists($ni[0], $ni[1])) {
1675                         echo "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n";
1676                         continue;
1677                 }
1678                 echo "Creating index \"$ni[1]\" on table \"$ni[0]\"\n";
1679                 dbsource($ni[2]);
1680         }
1682         # Tweak the page_title tsearch2 trigger to filter out slashes
1683         # This is create or replace, so harmless to call if not needed
1684         dbsource(archive('patch-ts2pagetitle.sql'));
1686         ## If the server is 8.3 or higher, rewrite teh tsearch2 triggers
1687         ## in case they have the old 'default' versions
1688         if ( $numver >= 8.3 )
1689                 dbsource(archive('patch-tsearch2funcs.sql'));
1691         return;