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