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