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