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