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