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