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