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