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