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