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