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