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