Fixups for page id field in the archive table:
[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 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_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( !array_key_exists( 'search_path', $conf ) or strpos( $conf['search_path'],$wgDBmwschema ) === false ) {
1281 print "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n";
1282 $newpath[$wgDBmwschema] = 1;
1283 }
1284 if( !array_key_exists( 'search_path', $conf ) or strpos( $conf['search_path'],$wgDBts2schema ) === false ) {
1285 print "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n";
1286 $newpath[$wgDBts2schema] = 1;
1287 }
1288 $searchpath = implode( ',', array_keys( $newpath ) );
1289 if( strlen( $searchpath ) ) {
1290 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $searchpath" );
1291 }
1292 $goodconf = array(
1293 'client_min_messages' => 'error',
1294 'DateStyle' => 'ISO, YMD',
1295 'TimeZone' => 'GMT'
1296 );
1297 foreach( array_keys( $goodconf ) AS $key ) {
1298 $value = $goodconf[$key];
1299 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1300 print "Setting $key to '$value' for user \"$wgDBuser\"\n";
1301 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1302 }
1303 }
1304
1305 $newsequences = array(
1306 "log_log_id_seq",
1307 "pr_id_val",
1308 );
1309
1310 $newtables = array(
1311 array("mediawiki_version", "patch-mediawiki_version.sql"),
1312 array("mwuser", "patch-mwuser.sql"),
1313 array("pagecontent", "patch-pagecontent.sql"),
1314 array("querycachetwo", "patch-querycachetwo.sql"),
1315 array("page_restrictions", "patch-page_restrictions.sql"),
1316 array("profiling", "patch-profiling.sql"),
1317 array("redirect", "patch-redirect.sql"),
1318 );
1319
1320 $newcols = array(
1321 array("archive", "ar_len", "INTEGER"),
1322 array("archive", "ar_page_id", "INTEGER"),
1323 array("image", "img_sha1", "TEXT NOT NULL DEFAULT ''"),
1324 array("ipblocks", "ipb_anon_only", "CHAR NOT NULL DEFAULT '0'"),
1325 array("ipblocks", "ipb_block_email", "CHAR NOT NULL DEFAULT '0'"),
1326 array("ipblocks", "ipb_create_account", "CHAR NOT NULL DEFAULT '1'"),
1327 array("ipblocks", "ipb_deleted", "INTEGER NOT NULL DEFAULT 0"),
1328 array("ipblocks", "ipb_enable_autoblock", "CHAR NOT NULL DEFAULT '1'"),
1329 array("filearchive", "fa_deleted", "INTEGER NOT NULL DEFAULT 0"),
1330 array("logging", "log_deleted", "INTEGER NOT NULL DEFAULT 0"),
1331 array("logging", "log_id", "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('log_log_id_seq')"),
1332 array("logging", "log_params", "TEXT"),
1333 array("mwuser", "user_editcount", "INTEGER"),
1334 array("mwuser", "user_newpass_time", "TIMESTAMPTZ"),
1335 array("oldimage", "oi_deleted", "CHAR NOT NULL DEFAULT '0'"),
1336 array("oldimage", "oi_metadata", "BYTEA NOT NULL DEFAULT ''"),
1337 array("oldimage", "oi_media_type", "TEXT"),
1338 array("oldimage", "oi_major_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1339 array("oldimage", "oi_minor_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1340 array("oldimage", "oi_sha1", "TEXT NOT NULL DEFAULT ''"),
1341 array("page_restrictions", "pr_id", "INTEGER NOT NULL UNIQUE DEFAULT nextval('pr_id_val')"),
1342 array("recentchanges", "rc_deleted", "INTEGER NOT NULL DEFAULT 0"),
1343 array("recentchanges", "rc_log_action", "TEXT"),
1344 array("recentchanges", "rc_log_type", "TEXT"),
1345 array("recentchanges", "rc_logid", "INTEGER NOT NULL DEFAULT 0"),
1346 array("recentchanges", "rc_new_len", "INTEGER"),
1347 array("recentchanges", "rc_old_len", "INTEGER"),
1348 array("recentchanges", "rc_params", "TEXT"),
1349 array("revision", "rev_len", "INTEGER"),
1350 );
1351
1352
1353 # table, column, desired type, USING clause if needed
1354 $typechanges = array(
1355 array("image", "img_size", "int4", ""),
1356 array("image", "img_width", "int4", ""),
1357 array("image", "img_height", "int4", ""),
1358 array("ipblocks", "ipb_address", "text", "ipb_address::text"),
1359 array("math", "math_inputhash", "bytea", "decode(math_inputhash,'escape')"),
1360 array("math", "math_outputhash", "bytea", "decode(math_outputhash,'escape')"),
1361 array("oldimage", "oi_size", "int4", ""),
1362 array("oldimage", "oi_width", "int4", ""),
1363 array("oldimage", "oi_height", "int4", ""),
1364 array("user_newtalk", "user_ip", "text", "host(user_ip)"),
1365 );
1366
1367 $newindexes = array(
1368 array("archive", "archive_user_text", "(ar_user_text)"),
1369 array("image", "img_sha1", "(img_sha1)"),
1370 array("oldimage", "oi_sha1", "(oi_sha1)"),
1371 array("recentchanges", "rc_patrolling", "(rc_this_oldid, rc_last_oldid, rc_patrolled)"),
1372 array("revision", "rev_text_id_idx", "(rev_text_id)"),
1373 );
1374
1375 $newrules = array(
1376 );
1377
1378 foreach ($newsequences as $ns) {
1379 if ($wgDatabase->sequenceExists($ns)) {
1380 echo "... sequence $ns already exists\n";
1381 continue;
1382 }
1383
1384 echo "... create sequence $ns\n";
1385 $wgDatabase->query("CREATE SEQUENCE $ns");
1386 }
1387
1388 foreach ($newtables as $nt) {
1389 if ($wgDatabase->tableExists($nt[0])) {
1390 echo "... table $nt[0] already exists\n";
1391 continue;
1392 }
1393
1394 echo "... create table $nt[0]\n";
1395 dbsource(archive($nt[1]));
1396 }
1397
1398 ## Needed before newcols
1399 if ($wgDatabase->tableExists("archive2")) {
1400 echo "... convert archive2 back to normal archive table\n";
1401 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1402 echo "... drop rule archive_insert\n";
1403 $wgDatabase->query("DROP RULE archive_insert ON archive");
1404 }
1405 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1406 echo "... drop rule archive_delete\n";
1407 $wgDatabase->query("DROP RULE archive_delete ON archive");
1408 }
1409
1410 dbsource(archive("patch-remove-archive2.sql"));
1411 } else
1412 echo "... obsolete archive2 not present\n";
1413
1414 foreach ($newcols as $nc) {
1415 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1416 if (!is_null($fi)) {
1417 echo "... column $nc[0].$nc[1] already exists\n";
1418 continue;
1419 }
1420
1421 echo "... add column $nc[0].$nc[1]\n";
1422 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1423 }
1424
1425 foreach ($typechanges as $tc) {
1426 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1427 if (is_null($fi)) {
1428 echo "... error: expected column $tc[0].$tc[1] to exist\n";
1429 exit(1);
1430 }
1431
1432 if ($fi->type() === $tc[2])
1433 echo "... $tc[0].$tc[1] is already $tc[2]\n";
1434 else {
1435 echo "... change $tc[0].$tc[1] from {$fi->type()} to $tc[2]\n";
1436 $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1437 if (strlen($tc[3])) {
1438 $sql .= " USING $tc[3]";
1439 }
1440 $sql .= ";\nCOMMIT;\n";
1441 $wgDatabase->query($sql);
1442 }
1443 }
1444
1445 foreach ($newindexes as $ni) {
1446 if (pg_index_exists($ni[0], $ni[1])) {
1447 echo "... index $ni[1] on $ni[0] already exists\n";
1448 continue;
1449 }
1450 $wgDatabase->query("CREATE INDEX $ni[1] ON $ni[0] $ni[2]");
1451 echo "create index $ni[1]\n";
1452 }
1453
1454 foreach ($newrules as $nr) {
1455 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1456 echo "... rule $nr[1] on $nr[0] already exists\n";
1457 continue;
1458 }
1459 dbsource(archive($nr[2]));
1460 }
1461
1462 if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1463 echo "... create page_deleted trigger\n";
1464 dbsource(archive('patch-page_deleted.sql'));
1465 }
1466
1467 $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1468 if (!$fi->nullable()) {
1469 echo "... remove NOT NULL constraint on recentchanges.rc_cur_id\n";
1470 dbsource(archive('patch-rc_cur_id-not-null.sql'));
1471 }
1472
1473 $pu = pg_describe_index("pagelink_unique");
1474 if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1475 echo "... dropping obsolete pagelink_unique index\n";
1476 $wgDatabase->query("DROP INDEX pagelink_unique");
1477 $pu = null;
1478 } else
1479 echo "... obsolete pagelink_unique index not present\n";
1480
1481 if (is_null($pu)) {
1482 echo "... adding new pagelink_unique index\n";
1483 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1484 } else
1485 echo "... already have current pagelink_unique index\n";
1486
1487 if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1488 echo "... revision_rev_user_fkey is already ON DELETE RESTRICT\n";
1489 } else {
1490 echo "... change revision_rev_user_fkey to ON DELETE RESTRICT\n";
1491 dbsource(archive('patch-revision_rev_user_fkey.sql'));
1492 }
1493
1494 if (is_null($wgDatabase->fieldInfo("archive", "ar_deleted"))) {
1495 echo "... add archive.ar_deleted\n";
1496 dbsource(archive("patch-archive-ar_deleted.sql"));
1497 } else
1498 echo "... archive.ar_deleted already exists\n";
1499
1500 global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
1501 # Add missing extension tables
1502 foreach ( $wgExtNewTables as $nt ) {
1503 if ($wgDatabase->tableExists($nt[0])) {
1504 echo "... table $nt[0] already exists\n";
1505 continue;
1506 }
1507
1508 echo "... create table $nt[0]\n";
1509 dbsource($nt[1]);
1510 }
1511 # Add missing extension fields
1512 foreach ( $wgExtNewFields as $nc ) {
1513 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1514 if (!is_null($fi)) {
1515 echo "... column $nc[0].$nc[1] already exists\n";
1516 continue;
1517 }
1518
1519 echo "... add column $nc[0].$nc[1]\n";
1520 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1521 }
1522 # Add missing extension indexes
1523 foreach ( $wgExtNewIndexes as $ni ) {
1524 if (pg_index_exists($ni[0], $ni[1])) {
1525 echo "... index $ni[1] on $ni[0] already exists\n";
1526 continue;
1527 }
1528 dbsource($ni[2]);
1529 }
1530
1531 return;
1532 }