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