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