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