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