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