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