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