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