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