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