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