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