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