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