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