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