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