}
function stream_open( $path, $mode, $options, &$opened_path ) {
- if( $mode[0] == 'r' ) {
+ if ( $mode[0] == 'r' ) {
$options = 'e -bd -so';
- } elseif( $mode[0] == 'w' ) {
+ } elseif ( $mode[0] == 'w' ) {
$options = 'a -bd -si';
} else {
return false;
}
$arg = wfEscapeShellArg( $this->stripPath( $path ) );
$command = "7za $options $arg";
- if( !wfIsWindows() ) {
+ if ( !wfIsWindows() ) {
// Suppress the stupid messages on stderr
$command .= ' 2>/dev/null';
}
$this->stream = popen( $command, $mode );
- return ($this->stream !== false);
+ return ( $this->stream !== false );
}
function url_stat( $path, $flags ) {
}
// This is all so lame; there should be a default class we can extend
-
+
function stream_close() {
return fclose( $this->stream );
}
'ipblocks',
'recentchanges',
'querycache' );
- foreach( $tables as $table ) {
- if( $this->doing( $table ) ) {
+ foreach ( $tables as $table ) {
+ if ( $this->doing( $table ) ) {
$method = 'upgrade' . ucfirst( $table );
$this->$method();
}
}
- if( $this->doing( 'cleanup' ) ) {
+ if ( $this->doing( 'cleanup' ) ) {
$this->upgradeCleanup();
}
}
* Commit transactions and close the connections when we're done...
*/
function close() {
- foreach( $this->loadBalancers as $lb ) {
+ foreach ( $this->loadBalancers as $lb ) {
$lb->commitMasterChanges();
$lb->closeAll();
}
$timeout = 3600 * 24;
$db = $this->newConnection();
$db->bufferResults( false );
- if ($wgDBtype == 'mysql') {
+ if ( $wgDBtype == 'mysql' ) {
$db->query( "SET net_read_timeout=$timeout" );
$db->query( "SET net_write_timeout=$timeout" );
}
# Mappings from:
# http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP1252.TXT
static $cp1252 = array(
- 0x80 => 0x20AC, #EURO SIGN
- 0x81 => 0xFFFD, #REPLACEMENT CHARACTER (no mapping)
- 0x82 => 0x201A, #SINGLE LOW-9 QUOTATION MARK
- 0x83 => 0x0192, #LATIN SMALL LETTER F WITH HOOK
- 0x84 => 0x201E, #DOUBLE LOW-9 QUOTATION MARK
- 0x85 => 0x2026, #HORIZONTAL ELLIPSIS
- 0x86 => 0x2020, #DAGGER
- 0x87 => 0x2021, #DOUBLE DAGGER
- 0x88 => 0x02C6, #MODIFIER LETTER CIRCUMFLEX ACCENT
- 0x89 => 0x2030, #PER MILLE SIGN
- 0x8A => 0x0160, #LATIN CAPITAL LETTER S WITH CARON
- 0x8B => 0x2039, #SINGLE LEFT-POINTING ANGLE QUOTATION MARK
- 0x8C => 0x0152, #LATIN CAPITAL LIGATURE OE
- 0x8D => 0xFFFD, #REPLACEMENT CHARACTER (no mapping)
- 0x8E => 0x017D, #LATIN CAPITAL LETTER Z WITH CARON
- 0x8F => 0xFFFD, #REPLACEMENT CHARACTER (no mapping)
- 0x90 => 0xFFFD, #REPLACEMENT CHARACTER (no mapping)
- 0x91 => 0x2018, #LEFT SINGLE QUOTATION MARK
- 0x92 => 0x2019, #RIGHT SINGLE QUOTATION MARK
- 0x93 => 0x201C, #LEFT DOUBLE QUOTATION MARK
- 0x94 => 0x201D, #RIGHT DOUBLE QUOTATION MARK
- 0x95 => 0x2022, #BULLET
- 0x96 => 0x2013, #EN DASH
- 0x97 => 0x2014, #EM DASH
- 0x98 => 0x02DC, #SMALL TILDE
- 0x99 => 0x2122, #TRADE MARK SIGN
- 0x9A => 0x0161, #LATIN SMALL LETTER S WITH CARON
- 0x9B => 0x203A, #SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
- 0x9C => 0x0153, #LATIN SMALL LIGATURE OE
- 0x9D => 0xFFFD, #REPLACEMENT CHARACTER (no mapping)
- 0x9E => 0x017E, #LATIN SMALL LETTER Z WITH CARON
- 0x9F => 0x0178, #LATIN CAPITAL LETTER Y WITH DIAERESIS
+ 0x80 => 0x20AC, # EURO SIGN
+ 0x81 => 0xFFFD, # REPLACEMENT CHARACTER (no mapping)
+ 0x82 => 0x201A, # SINGLE LOW-9 QUOTATION MARK
+ 0x83 => 0x0192, # LATIN SMALL LETTER F WITH HOOK
+ 0x84 => 0x201E, # DOUBLE LOW-9 QUOTATION MARK
+ 0x85 => 0x2026, # HORIZONTAL ELLIPSIS
+ 0x86 => 0x2020, # DAGGER
+ 0x87 => 0x2021, # DOUBLE DAGGER
+ 0x88 => 0x02C6, # MODIFIER LETTER CIRCUMFLEX ACCENT
+ 0x89 => 0x2030, # PER MILLE SIGN
+ 0x8A => 0x0160, # LATIN CAPITAL LETTER S WITH CARON
+ 0x8B => 0x2039, # SINGLE LEFT-POINTING ANGLE QUOTATION MARK
+ 0x8C => 0x0152, # LATIN CAPITAL LIGATURE OE
+ 0x8D => 0xFFFD, # REPLACEMENT CHARACTER (no mapping)
+ 0x8E => 0x017D, # LATIN CAPITAL LETTER Z WITH CARON
+ 0x8F => 0xFFFD, # REPLACEMENT CHARACTER (no mapping)
+ 0x90 => 0xFFFD, # REPLACEMENT CHARACTER (no mapping)
+ 0x91 => 0x2018, # LEFT SINGLE QUOTATION MARK
+ 0x92 => 0x2019, # RIGHT SINGLE QUOTATION MARK
+ 0x93 => 0x201C, # LEFT DOUBLE QUOTATION MARK
+ 0x94 => 0x201D, # RIGHT DOUBLE QUOTATION MARK
+ 0x95 => 0x2022, # BULLET
+ 0x96 => 0x2013, # EN DASH
+ 0x97 => 0x2014, # EM DASH
+ 0x98 => 0x02DC, # SMALL TILDE
+ 0x99 => 0x2122, # TRADE MARK SIGN
+ 0x9A => 0x0161, # LATIN SMALL LETTER S WITH CARON
+ 0x9B => 0x203A, # SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
+ 0x9C => 0x0153, # LATIN SMALL LIGATURE OE
+ 0x9D => 0xFFFD, # REPLACEMENT CHARACTER (no mapping)
+ 0x9E => 0x017E, # LATIN SMALL LETTER Z WITH CARON
+ 0x9F => 0x0178, # LATIN CAPITAL LETTER Y WITH DIAERESIS
);
$pairs = array();
- for( $i = 0; $i < 0x100; $i++ ) {
+ for ( $i = 0; $i < 0x100; $i++ ) {
$unicode = isset( $cp1252[$i] ) ? $cp1252[$i] : $i;
$pairs[chr( $i )] = codepointToUtf8( $unicode );
}
* @access private
*/
function addChunk( &$chunk, $key = null ) {
- if( count( $chunk ) >= $this->chunkSize ) {
+ if ( count( $chunk ) >= $this->chunkSize ) {
$this->insertChunk( $chunk );
$this->chunkCount += count( $chunk );
$delta = $now - $this->chunkStartTime;
$rate = $this->chunkCount / $delta;
- if( is_null( $key ) ) {
+ if ( is_null( $key ) ) {
$completed = $this->chunkCount;
} else {
$completed = $key;
*/
function lastChunk( &$chunk ) {
$n = count( $chunk );
- if( $n > 0 ) {
+ if ( $n > 0 ) {
$this->insertChunk( $chunk );
}
$this->log( "100.00% done on $this->chunkTable (last chunk $n rows)." );
$fname );
$add = array();
- while( $row = $this->dbr->fetchObject( $result ) ) {
+ while ( $row = $this->dbr->fetchObject( $result ) ) {
$copy = array();
- foreach( $fields as $field => $source ) {
- if( $source === MW_UPGRADE_COPY ) {
+ foreach ( $fields as $field => $source ) {
+ if ( $source === MW_UPGRADE_COPY ) {
$copy[$field] = $row->$field;
- } elseif( $source === MW_UPGRADE_ENCODE ) {
+ } elseif ( $source === MW_UPGRADE_ENCODE ) {
$copy[$field] = $this->conv( $row->$field );
- } elseif( $source === MW_UPGRADE_NULL ) {
+ } elseif ( $source === MW_UPGRADE_NULL ) {
$copy[$field] = null;
} else {
$this->log( "Unknown field copy type: $field => $source" );
}
}
- if( is_callable( $callback ) ) {
+ if ( is_callable( $callback ) ) {
$copy = call_user_func( $callback, $row, $copy );
}
$add[] = $copy;
$fname = "FiveUpgrade::upgradePage";
$chunksize = 100;
- if( $this->dbw->tableExists( 'page' ) ) {
+ if ( $this->dbw->tableExists( 'page' ) ) {
$this->log( 'Page table already exists; aborting.' );
die( -1 );
}
$this->log( "...converting from cur/old to page/revision/text DB structure." );
- list ($cur, $old, $page, $revision, $text) = $this->dbw->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
+ list ( $cur, $old, $page, $revision, $text ) = $this->dbw->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
$this->log( "Creating page and revision tables..." );
- $this->dbw->query("CREATE TABLE $page (
+ $this->dbw->query( "CREATE TABLE $page (
page_id int(8) unsigned NOT NULL auto_increment,
page_namespace int NOT NULL,
page_title varchar(255) binary NOT NULL,
INDEX (page_random),
INDEX (page_len)
) TYPE=InnoDB", $fname );
- $this->dbw->query("CREATE TABLE $revision (
+ $this->dbw->query( "CREATE TABLE $revision (
rev_id int(8) unsigned NOT NULL auto_increment,
rev_page int(8) unsigned NOT NULL,
rev_text_id int(8) unsigned NOT NULL,
$this->log( "Last old record is {$maxold}" );
global $wgLegacySchemaConversion;
- if( $wgLegacySchemaConversion ) {
+ if ( $wgLegacySchemaConversion ) {
// Create HistoryBlobCurStub entries.
// Text will be pulled from the leftover 'cur' table at runtime.
echo "......Moving metadata from cur; using blob references to text in cur table.\n";
FROM $cur
ORDER BY cur_id", $fname );
$add = array();
- while( $row = $this->dbr->fetchObject( $result ) ) {
+ while ( $row = $this->dbr->fetchObject( $result ) ) {
$add[] = array(
'old_namespace' => $row->cur_namespace,
'old_title' => $row->cur_title,
* Copy revision metadata from old into revision.
* We'll also do UTF-8 conversion of usernames and comments.
*/
- #$newmaxold = $this->dbw->selectField( 'old', 'max(old_id)', '', $fname );
- #$this->setChunkScale( $chunksize, $newmaxold, 'revision', $fname );
- #$countold = $this->dbw->selectField( 'old', 'count(old_id)', '', $fname );
+ # $newmaxold = $this->dbw->selectField( 'old', 'max(old_id)', '', $fname );
+ # $this->setChunkScale( $chunksize, $newmaxold, 'revision', $fname );
+ # $countold = $this->dbw->selectField( 'old', 'count(old_id)', '', $fname );
$countold = $this->dbw->selectField( 'old', 'max(old_id)', '', $fname );
$this->setChunkScale( $chunksize, $countold, 'revision', $fname );
$fname );
$add = array();
- while( $row = $this->dbr->fetchObject( $result ) ) {
+ while ( $row = $this->dbr->fetchObject( $result ) ) {
$add[] = array(
'rev_id' => $row->old_id,
'rev_page' => $row->cur_id,
WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}
ORDER BY cur_id", $fname );
$add = array();
- while( $row = $this->dbr->fetchObject( $result ) ) {
+ while ( $row = $this->dbr->fetchObject( $result ) ) {
$add[] = array(
'page_id' => $row->cur_id,
'page_namespace' => $row->cur_namespace,
'page_touched' => $this->dbw->timestamp(),
'page_latest' => $row->rev_id,
'page_len' => $row->len );
- #$this->addChunk( $add, $row->cur_id );
+ # $this->addChunk( $add, $row->cur_id );
$this->addChunk( $add );
}
$this->lastChunk( $add );
function upgradeLinks() {
$fname = 'FiveUpgrade::upgradeLinks';
$chunksize = 200;
- list ($links, $brokenlinks, $pagelinks, $cur) = $this->dbw->tableNamesN( 'links', 'brokenlinks', 'pagelinks', 'cur' );
+ list ( $links, $brokenlinks, $pagelinks, $cur ) = $this->dbw->tableNamesN( 'links', 'brokenlinks', 'pagelinks', 'cur' );
$this->log( 'Checking for interwiki table change in case of bogus items...' );
- if( $this->dbw->fieldExists( 'interwiki', 'iw_trans' ) ) {
+ if ( $this->dbw->fieldExists( 'interwiki', 'iw_trans' ) ) {
$this->log( 'interwiki has iw_trans.' );
} else {
global $IP;
$this->log( 'Importing live links -> pagelinks' );
$nlinks = $this->dbw->selectField( 'links', 'count(*)', '', $fname );
- if( $nlinks ) {
+ if ( $nlinks ) {
$this->setChunkScale( $chunksize, $nlinks, 'pagelinks', $fname );
$result = $this->dbr->query( "
SELECT l_from,cur_namespace,cur_title
FROM $links, $cur
WHERE l_to=cur_id", $fname );
$add = array();
- while( $row = $this->dbr->fetchObject( $result ) ) {
+ while ( $row = $this->dbr->fetchObject( $result ) ) {
$add[] = array(
'pl_from' => $row->l_from,
'pl_namespace' => $row->cur_namespace,
$this->log( 'Importing brokenlinks -> pagelinks' );
$nbrokenlinks = $this->dbw->selectField( 'brokenlinks', 'count(*)', '', $fname );
- if( $nbrokenlinks ) {
+ if ( $nbrokenlinks ) {
$this->setChunkScale( $chunksize, $nbrokenlinks, 'pagelinks', $fname );
$result = $this->dbr->query(
"SELECT bl_from, bl_to FROM $brokenlinks",
$fname );
$add = array();
- while( $row = $this->dbr->fetchObject( $result ) ) {
+ while ( $row = $this->dbr->fetchObject( $result ) ) {
$pagename = $this->conv( $row->bl_to );
$title = Title::newFromText( $pagename );
- if( is_null( $title ) ) {
+ if ( is_null( $title ) ) {
$this->log( "** invalid brokenlink: $row->bl_from -> '$pagename' (converted from '$row->bl_to')" );
} else {
$add[] = array(
function upgradeUser() {
// Apply unique index, if necessary:
$duper = new UserDupes( $this->dbw );
- if( $duper->hasUniqueIndex() ) {
+ if ( $duper->hasUniqueIndex() ) {
$this->log( "Already have unique user_name index." );
} else {
$this->log( "Clearing user duplicates..." );
- if( !$duper->clearDupes() ) {
+ if ( !$duper->clearDupes() ) {
$this->log( "WARNING: Duplicate user accounts, may explode!" );
}
}
function imageCallback( $row, $copy ) {
global $options;
- if( !isset( $options['noimage'] ) ) {
+ if ( !isset( $options['noimage'] ) ) {
// Fill in the new image info fields
$info = $this->imageInfo( $row->img_name );
* @param string $basename pre-conversion base filename for dir hashing, if an archive
* @access private
*/
- function renameFile( $oldname, $subdirCallback='wfImageDir', $basename=null ) {
+ function renameFile( $oldname, $subdirCallback = 'wfImageDir', $basename = null ) {
$newname = $this->conv( $oldname );
- if( $newname == $oldname ) {
+ if ( $newname == $oldname ) {
// No need to rename; another field triggered this row.
return false;
}
- if( is_null( $basename ) ) $basename = $oldname;
+ if ( is_null( $basename ) ) $basename = $oldname;
$ubasename = $this->conv( $basename );
$oldpath = call_user_func( $subdirCallback, $basename ) . '/' . $oldname;
$newpath = call_user_func( $subdirCallback, $ubasename ) . '/' . $newname;
$this->log( "$oldpath -> $newpath" );
- if( rename( $oldpath, $newpath ) ) {
+ if ( rename( $oldpath, $newpath ) ) {
$relpath = wfRelativePath( $newpath, dirname( $oldpath ) );
- if( !symlink( $relpath, $oldpath ) ) {
+ if ( !symlink( $relpath, $oldpath ) ) {
$this->log( "... symlink failed!" );
}
return $newname;
function oldimageCallback( $row, $copy ) {
global $options;
- if( !isset( $options['noimage'] ) ) {
+ if ( !isset( $options['noimage'] ) ) {
// Fill in the new image info fields
$info = $this->imageInfo( $row->oi_archive_name, 'wfImageArchiveDir', $row->oi_name );
$copy['oi_width' ] = $info['width' ];
$fname = 'FiveUpgrade::upgradeWatchlist';
$chunksize = 100;
- list ($watchlist, $watchlist_temp) = $this->dbw->tableNamesN( 'watchlist', 'watchlist_temp' );
+ list ( $watchlist, $watchlist_temp ) = $this->dbw->tableNamesN( 'watchlist', 'watchlist_temp' );
$this->log( 'Migrating watchlist table to watchlist_temp...' );
$this->dbw->query(
$fname );
$add = array();
- while( $row = $this->dbr->fetchObject( $result ) ) {
+ while ( $row = $this->dbr->fetchObject( $result ) ) {
$add[] = array(
'wl_user' => $row->wl_user,
'wl_namespace' => MWNamespace::getSubject( $row->wl_namespace ),
function upgradeImagelinks() {
global $wgUseLatin1;
- if( $wgUseLatin1 ) {
+ if ( $wgUseLatin1 ) {
$tabledef = <<<ENDS
CREATE TABLE $1 (
-- Key to page_id of the page containing the image / media link.
function upgradeCategorylinks() {
global $wgUseLatin1;
- if( $wgUseLatin1 ) {
+ if ( $wgUseLatin1 ) {
$tabledef = <<<ENDS
CREATE TABLE $1 (
cl_from int(8) unsigned NOT NULL default '0',
function upgradeIpblocks() {
global $wgUseLatin1;
- if( $wgUseLatin1 ) {
+ if ( $wgUseLatin1 ) {
$tabledef = <<<ENDS
CREATE TABLE $1 (
ipb_id int(8) NOT NULL auto_increment,
function upgradeCleanup() {
$this->renameTable( 'old', 'text' );
- foreach( $this->cleanupSwaps as $table ) {
+ foreach ( $this->cleanupSwaps as $table ) {
$this->swap( $table );
}
}
$maintClass = false;
// Make sure we're on PHP5 or better
-if( version_compare( PHP_VERSION, '5.0.0' ) < 0 ) {
+if ( version_compare( PHP_VERSION, '5.0.0' ) < 0 ) {
echo( "Sorry! This version of MediaWiki requires PHP 5; you are running " .
PHP_VERSION . ".\n\n" .
"If you are sure you already have PHP 5 installed, it may be installed\n" .
* @return mixed
*/
protected function getOption( $name, $default = null ) {
- if( $this->hasOption( $name ) ) {
+ if ( $this->hasOption( $name ) ) {
return $this->mOptions[$name];
} else {
// Set it so we don't have to provide the default again
* @param $required Boolean Is this required?
*/
protected function addArg( $arg, $description, $required = true ) {
- $this->mArgList[] = array(
+ $this->mArgList[] = array(
'name' => $arg,
- 'desc' => $description,
- 'require' => $required
+ 'desc' => $description,
+ 'require' => $required
);
}
if ( $len == Maintenance::STDIN_ALL )
return file_get_contents( 'php://stdin' );
$f = fopen( 'php://stdin', 'rt' );
- if( !$len )
+ if ( !$len )
return $f;
$input = fgets( $f, $len );
fclose( $f );
* @param $channel Mixed Unique identifier for the channel. See function outputChanneled.
*/
protected function output( $out, $channel = null ) {
- if( $this->mQuiet ) {
+ if ( $this->mQuiet ) {
return;
}
$out = preg_replace( '/\n\z/', '', $out );
if ( php_sapi_name() == 'cli' ) {
fwrite( STDERR, $err . "\n" );
} else {
- $f = fopen( 'php://stderr', 'w' );
+ $f = fopen( 'php://stderr', 'w' );
fwrite( $f, $err . "\n" );
fclose( $f );
}
- if( $die ) die();
+ if ( $die ) die();
}
private $atLineStart = true;
* @param $channel Channel identifier or null for no channel. Channel comparison uses ===.
*/
public function outputChanneled( $msg, $channel = null ) {
- $handle = fopen( 'php://stdout', 'w' );
+ $handle = fopen( 'php://stdout', 'w' );
if ( $msg === false ) {
// For cleanup
$this->addOption( 'wiki', "For specifying the wiki ID", false, true );
$this->addOption( 'globals', "Output globals at the end of processing for debugging" );
// If we support a DB, show the options
- if( $this->getDbType() > 0 ) {
+ if ( $this->getDbType() > 0 ) {
$this->addOption( 'dbuser', "The DB user to use for this script", false, true );
$this->addOption( 'dbpass', "The password to use for this script", false, true );
}
// If we support $mBatchSize, show the option
- if( $this->mBatchSize ) {
+ if ( $this->mBatchSize ) {
$this->addOption( 'batch-size', 'Run this many operations ' .
'per batch, default: ' . $this->mBatchSize , false, true );
}
self::disableSetup();
// Make sure the class is loaded first
- if( !class_exists( $maintClass ) ) {
- if( $classFile ) {
+ if ( !class_exists( $maintClass ) ) {
+ if ( $classFile ) {
require_once( $classFile );
}
- if( !class_exists( $maintClass ) ) {
+ if ( !class_exists( $maintClass ) ) {
$this->error( "Cannot spawn child: $maintClass" );
}
}
* Disable Setup.php mostly
*/
protected static function disableSetup() {
- if( !defined( 'MW_NO_SETUP' ) )
+ if ( !defined( 'MW_NO_SETUP' ) )
define( 'MW_NO_SETUP', true );
}
}
# Make sure we can handle script parameters
- if( !ini_get( 'register_argc_argv' ) ) {
+ if ( !ini_get( 'register_argc_argv' ) ) {
$this->error( "Cannot get command line arguments, register_argc_argv is set to false", true );
}
- if( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
+ if ( version_compare( phpversion(), '5.2.4' ) >= 0 ) {
// Send PHP warnings and errors to stderr instead of stdout.
// This aids in diagnosing problems, while keeping messages
// out of redirected output.
- if( ini_get( 'display_errors' ) ) {
+ if ( ini_get( 'display_errors' ) ) {
ini_set( 'display_errors', 'stderr' );
}
*/
public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
# If we were given opts or args, set those and return early
- if( $self ) {
+ if ( $self ) {
$this->mSelf = $self;
$this->mInputLoaded = true;
}
- if( $opts ) {
+ if ( $opts ) {
$this->mOptions = $opts;
$this->mInputLoaded = true;
}
- if( $args ) {
+ if ( $args ) {
$this->mArgs = $args;
$this->mInputLoaded = true;
}
# If we've already loaded input (either by user values or from $argv)
# skip on loading it again. The array_shift() will corrupt values if
# it's run again and again
- if( $this->mInputLoaded ) {
+ if ( $this->mInputLoaded ) {
$this->loadSpecialVars();
return;
}
$args = array();
# Parse arguments
- for( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
+ for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
if ( $arg == '--' ) {
# End of options, remainder should be considered arguments
$arg = next( $argv );
- while( $arg !== false ) {
+ while ( $arg !== false ) {
$args[] = $arg;
$arg = next( $argv );
}
$options[$option] = $param;
} else {
$bits = explode( '=', $option, 2 );
- if( count( $bits ) > 1 ) {
+ if ( count( $bits ) > 1 ) {
$option = $bits[0];
$param = $bits[1];
} else {
}
} elseif ( substr( $arg, 0, 1 ) == '-' ) {
# Short options
- for ( $p=1; $p<strlen( $arg ); $p++ ) {
- $option = $arg{$p};
+ for ( $p = 1; $p < strlen( $arg ); $p++ ) {
+ $option = $arg { $p } ;
if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
$param = next( $argv );
if ( $param === false ) {
protected function validateParamsAndArgs() {
$die = false;
# Check to make sure we've got all the required options
- foreach( $this->mParams as $opt => $info ) {
- if( $info['require'] && !$this->hasOption( $opt ) ) {
+ foreach ( $this->mParams as $opt => $info ) {
+ if ( $info['require'] && !$this->hasOption( $opt ) ) {
$this->error( "Param $opt required!" );
$die = true;
}
}
# Check arg list too
- foreach( $this->mArgList as $k => $info ) {
- if( $info['require'] && !$this->hasArg($k) ) {
+ foreach ( $this->mArgList as $k => $info ) {
+ if ( $info['require'] && !$this->hasArg( $k ) ) {
$this->error( "Argument <" . $info['name'] . "> required!" );
$die = true;
}
}
- if( $die ) $this->maybeHelp( true );
+ if ( $die ) $this->maybeHelp( true );
}
/**
* Handle the special variables that are global to all scripts
*/
protected function loadSpecialVars() {
- if( $this->hasOption( 'dbuser' ) )
+ if ( $this->hasOption( 'dbuser' ) )
$this->mDbUser = $this->getOption( 'dbuser' );
- if( $this->hasOption( 'dbpass' ) )
+ if ( $this->hasOption( 'dbpass' ) )
$this->mDbPass = $this->getOption( 'dbpass' );
- if( $this->hasOption( 'quiet' ) )
+ if ( $this->hasOption( 'quiet' ) )
$this->mQuiet = true;
- if( $this->hasOption( 'batch-size' ) )
+ if ( $this->hasOption( 'batch-size' ) )
$this->mBatchSize = $this->getOption( 'batch-size' );
}
$descWidth = $screenWidth - ( 2 * strlen( $tab ) );
ksort( $this->mParams );
- if( $this->hasOption( 'help' ) || $force ) {
+ if ( $this->hasOption( 'help' ) || $force ) {
$this->mQuiet = false;
- if( $this->mDescription ) {
+ if ( $this->mDescription ) {
$this->output( "\n" . $this->mDescription . "\n" );
}
$output = "\nUsage: php " . basename( $this->mSelf );
- if( $this->mParams ) {
+ if ( $this->mParams ) {
$output .= " [--" . implode( array_keys( $this->mParams ), "|--" ) . "]";
}
- if( $this->mArgList ) {
+ if ( $this->mArgList ) {
$output .= " <";
- foreach( $this->mArgList as $k => $arg ) {
+ foreach ( $this->mArgList as $k => $arg ) {
$output .= $arg['name'] . ">";
- if( $k < count( $this->mArgList ) - 1 )
+ if ( $k < count( $this->mArgList ) - 1 )
$output .= " <";
}
}
$this->output( "$output\n" );
- foreach( $this->mParams as $par => $info ) {
- $this->output( wordwrap( "$tab$par : " . $info['desc'], $descWidth,
+ foreach ( $this->mParams as $par => $info ) {
+ $this->output( wordwrap( "$tab$par : " . $info['desc'], $descWidth,
"\n$tab$tab" ) . "\n" );
}
- foreach( $this->mArgList as $info ) {
+ foreach ( $this->mArgList as $info ) {
$this->output( wordwrap( "$tab<" . $info['name'] . "> : " .
$info['desc'], $descWidth, "\n$tab$tab" ) . "\n" );
}
global $wgDBuser, $wgDBpassword, $wgDBservers, $wgLBFactoryConf;
# Turn off output buffering again, it might have been turned on in the settings files
- if( ob_get_level() ) {
+ if ( ob_get_level() ) {
ob_end_flush();
}
# Same with these
$wgCommandLineMode = true;
# If these were passed, use them
- if( $this->mDbUser )
+ if ( $this->mDbUser )
$wgDBadminuser = $this->mDbUser;
- if( $this->mDbPass )
+ if ( $this->mDbPass )
$wgDBadminpassword = $this->mDbPass;
if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
$wgDBuser = $wgDBadminuser;
$wgDBpassword = $wgDBadminpassword;
- if( $wgDBservers ) {
+ if ( $wgDBservers ) {
foreach ( $wgDBservers as $i => $server ) {
$wgDBservers[$i]['user'] = $wgDBuser;
$wgDBservers[$i]['password'] = $wgDBpassword;
}
}
- if( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
+ if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
$wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
$wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
}
* for refreshLinks
*/
public function globals() {
- if( $this->hasOption( 'globals' ) ) {
+ if ( $this->hasOption( 'globals' ) ) {
print_r( $GLOBALS );
}
}
# This is for the IRC scripts, which now run as the apache user
# The apache user doesn't have access to the wikiadmin_pass command
if ( $_ENV['USER'] == 'apache' ) {
- #if ( posix_geteuid() == 48 ) {
+ # if ( posix_geteuid() == 48 ) {
$wgUseNormalUser = true;
}
# Get "active" text records from the revisions table
$this->output( "Searching for active text records in revisions table..." );
$res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$cur[] = $row->rev_text_id;
}
$this->output( "done.\n" );
# Get "active" text records from the archive table
$this->output( "Searching for active text records in archive table..." );
$res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$cur[] = $row->ar_text_id;
}
$this->output( "done.\n" );
$set = implode( ', ', $cur );
$res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
$old = array();
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$old[] = $row->old_id;
}
$this->output( "done.\n" );
$this->output( "$count inactive items found.\n" );
# Delete as appropriate
- if( $delete && $count ) {
+ if ( $delete && $count ) {
$this->output( "Deleting..." );
$set = implode( ', ', $old );
$dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
* @return array
*/
protected static function getCoreScripts() {
- if( !self::$mCoreScripts ) {
+ if ( !self::$mCoreScripts ) {
self::disableSetup();
$paths = array(
dirname( __FILE__ ),
dirname( __FILE__ ) . '/storage',
);
self::$mCoreScripts = array();
- foreach( $paths as $p ) {
+ foreach ( $paths as $p ) {
$handle = opendir( $p );
- while( ( $file = readdir( $handle ) ) !== false ) {
- if( $file == 'Maintenance.php' )
+ while ( ( $file = readdir( $handle ) ) !== false ) {
+ if ( $file == 'Maintenance.php' )
continue;
$file = $p . '/' . $file;
- if( is_dir( $file ) || !strpos( $file, '.php' ) ||
+ if ( is_dir( $file ) || !strpos( $file, '.php' ) ||
( strpos( file_get_contents( $file ), '$maintClass' ) === false ) ) {
continue;
}
require( $file );
$vars = get_defined_vars();
- if( array_key_exists( 'maintClass', $vars ) ) {
+ if ( array_key_exists( 'maintClass', $vars ) ) {
self::$mCoreScripts[$vars['maintClass']] = $file;
}
}
// Get current revision
$rev = Revision::loadFromPageId( $dbw, $pageId );
$title = null;
- if( $rev ) {
+ if ( $rev ) {
$titleObj = $rev->getTitle();
$title = $titleObj->getPrefixedDBkey();
$this->output( "$title..." );
* @ingroup Wikimedia
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class AddWiki extends Maintenance {
public function __construct() {
global $IP, $wgDefaultExternalStore, $wgNoDBParam;
$wgNoDBParam = true;
- $lang = $this->getArg(0);
- $site = $this->getArg(1);
- $dbName = $this->getArg(2);
+ $lang = $this->getArg( 0 );
+ $site = $this->getArg( 1 );
+ $dbName = $this->getArg( 2 );
$languageNames = Language::getLanguageNames();
if ( !isset( $languageNames[$lang] ) ) {
fclose( $file );
# Update the sublists
- shell_exec("cd $common && ./refresh-dblist");
+ shell_exec( "cd $common && ./refresh-dblist" );
- #print "Constructing interwiki SQL\n";
+ # print "Constructing interwiki SQL\n";
# Rebuild interwiki tables
- #passthru( '/home/wikipedia/conf/interwiki/update' );
+ # passthru( '/home/wikipedia/conf/interwiki/update' );
$this->output( "Script ended. You still have to:
* Add any required settings in InitialiseSettings.php
* @ingroup MaintenanceArchive
*/
-require( dirname(__FILE__).'/../commandLine.inc' );
+require( dirname( __FILE__ ) . '/../commandLine.inc' );
class UpdateLogging {
var $dbw;
} else {
$conds = array( 'log_timestamp > ' . $this->dbw->addQuotes( $copyPos ) );
}
- $srcRes = $this->dbw->select( $srcTable, '*', $conds, __METHOD__,
+ $srcRes = $this->dbw->select( $srcTable, '*', $conds, __METHOD__,
array( 'LIMIT' => $batchSize, 'ORDER BY' => 'log_timestamp' ) );
if ( ! $srcRes->numRows() ) {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class AttachLatest extends Maintenance {
__METHOD__ );
$n = 0;
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
$pageId = intval( $row->page_id );
$title = Title::makeTitle( $row->page_namespace, $row->page_title );
$name = $title->getPrefixedText();
'MAX(rev_timestamp)',
array( 'rev_page' => $pageId ),
__METHOD__ );
- if( !$latestTime ) {
- $this->output( wfWikiID()." $pageId [[$name]] can't find latest rev time?!\n" );
+ if ( !$latestTime ) {
+ $this->output( wfWikiID() . " $pageId [[$name]] can't find latest rev time?!\n" );
continue;
}
$revision = Revision::loadFromTimestamp( $dbw, $title, $latestTime );
- if( is_null( $revision ) ) {
- $this->output( wfWikiID()." $pageId [[$name]] latest time $latestTime, can't find revision id\n" );
+ if ( is_null( $revision ) ) {
+ $this->output( wfWikiID() . " $pageId [[$name]] latest time $latestTime, can't find revision id\n" );
continue;
}
$id = $revision->getId();
- $this->output( wfWikiID()." $pageId [[$name]] latest time $latestTime, rev id $id\n" );
- if( $this->hasOption('fix') ) {
+ $this->output( wfWikiID() . " $pageId [[$name]] latest time $latestTime, rev id $id\n" );
+ if ( $this->hasOption( 'fix' ) ) {
$article = new Article( $title );
$article->updateRevisionOn( $dbw, $revision );
}
}
$dbw->freeResult( $result );
$this->output( "Done! Processed $n pages.\n" );
- if( !$this->hasOption('fix') ) {
+ if ( !$this->hasOption( 'fix' ) ) {
$this->output( "This was a dry run; rerun with --fix to update page_latest.\n" );
}
}
* @param $file String: full or relative path to the PHP file to load, or empty
*/
function loadPlugin( $class, $file ) {
- if( $file != '' ) {
+ if ( $file != '' ) {
require_once( $file );
}
$register = array( $class, 'register' );
function processArgs( $args ) {
$sink = null;
$sinks = array();
- foreach( $args as $arg ) {
+ foreach ( $args as $arg ) {
$matches = array();
- if( preg_match( '/^--(.+?)(?:=(.+?)(?::(.+?))?)?$/', $arg, $matches ) ) {
+ if ( preg_match( '/^--(.+?)(?:=(.+?)(?::(.+?))?)?$/', $arg, $matches ) ) {
@list( /* $full */ , $opt, $val, $param ) = $matches;
switch( $opt ) {
case "plugin":
$this->loadPlugin( $val, $param );
break;
case "output":
- if( !is_null( $sink ) ) {
+ if ( !is_null( $sink ) ) {
$sinks[] = $sink;
}
- if( !isset( $this->outputTypes[$val] ) ) {
+ if ( !isset( $this->outputTypes[$val] ) ) {
wfDie( "Unrecognized output sink type '$val'\n" );
}
$type = $this->outputTypes[$val];
$sink = new $type( $param );
break;
case "filter":
- if( is_null( $sink ) ) {
+ if ( is_null( $sink ) ) {
$this->progress( "Warning: assuming stdout for filter output\n" );
$sink = new DumpOutput();
}
- if( !isset( $this->filterTypes[$val] ) ) {
+ if ( !isset( $this->filterTypes[$val] ) ) {
wfDie( "Unrecognized filter type '$val'\n" );
}
$type = $this->filterTypes[$val];
$this->server = $val;
break;
case "force-normal":
- if( !function_exists( 'utf8_normalize' ) ) {
+ if ( !function_exists( 'utf8_normalize' ) ) {
dl( "php_utfnormal.so" );
- if( !function_exists( 'utf8_normalize' ) ) {
+ if ( !function_exists( 'utf8_normalize' ) ) {
wfDie( "Failed to load UTF-8 normalization extension. " .
"Install or remove --force-normal parameter to use slower code.\n" );
}
}
}
- if( is_null( $sink ) ) {
+ if ( is_null( $sink ) ) {
$sink = new DumpOutput();
}
$sinks[] = $sink;
- if( count( $sinks ) > 1 ) {
+ if ( count( $sinks ) > 1 ) {
return new DumpMultiWriter( $sinks );
} else {
return $sink;
function dump( $history, $text = WikiExporter::TEXT ) {
# Notice messages will foul up your XML output even if they're
# relatively harmless.
- if( ini_get( 'display_errors' ) )
+ if ( ini_get( 'display_errors' ) )
ini_set( 'display_errors', 'stderr' );
$this->initProgress( $history );
$wrapper = new ExportProgressFilter( $this->sink, $this );
$exporter->setOutputSink( $wrapper );
- if( !$this->skipHeader )
+ if ( !$this->skipHeader )
$exporter->openStream();
# Log item dumps: all or by range
- if( $history & WikiExporter::LOGS ) {
- if( $this->startId || $this->endId ) {
+ if ( $history & WikiExporter::LOGS ) {
+ if ( $this->startId || $this->endId ) {
$exporter->logsByRange( $this->startId, $this->endId );
} else {
$exporter->allLogs();
}
# Page dumps: all or by page ID range
- } else if( is_null( $this->pages ) ) {
- if( $this->startId || $this->endId ) {
+ } else if ( is_null( $this->pages ) ) {
+ if ( $this->startId || $this->endId ) {
$exporter->pagesByRange( $this->startId, $this->endId );
} else {
$exporter->allPages();
$exporter->pagesByName( $this->pages );
}
- if( !$this->skipFooter )
+ if ( !$this->skipFooter )
$exporter->closeStream();
$this->report( true );
* @param $history Integer: WikiExporter::CURRENT or WikiExporter::FULL
*/
function initProgress( $history = WikiExporter::FULL ) {
- $table = ($history == WikiExporter::CURRENT) ? 'page' : 'revision';
- $field = ($history == WikiExporter::CURRENT) ? 'page_id' : 'rev_id';
+ $table = ( $history == WikiExporter::CURRENT ) ? 'page' : 'revision';
+ $field = ( $history == WikiExporter::CURRENT ) ? 'page_id' : 'rev_id';
$dbr = wfGetDB( DB_SLAVE );
$this->maxCount = $dbr->selectField( $table, "MAX($field)", '', 'BackupDumper::dump' );
}
function __destruct() {
- if( isset( $this->lb ) ) {
+ if ( isset( $this->lb ) ) {
$this->lb->closeAll();
}
}
}
function report( $final = false ) {
- if( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
+ if ( $final xor ( $this->revCount % $this->reportingInterval == 0 ) ) {
$this->showReport();
}
}
function showReport() {
- if( $this->reporting ) {
+ if ( $this->reporting ) {
$delta = wfTime() - $this->startTime;
$now = wfTimestamp( TS_DB );
- if( $delta ) {
+ if ( $delta ) {
$rate = $this->pageCount / $delta;
$revrate = $this->revCount / $delta;
$portion = $this->revCount / $this->maxCount;
$xmlReaderConstants = array(
"NONE",
"ELEMENT",
- "ATTRIBUTE",
+ "ATTRIBUTE",
"TEXT",
"CDATA",
"ENTITY_REF",
"DEFAULTATTRS",
"VALIDATE",
"SUBST_ENTITIES" );
-foreach( $xmlReaderConstants as $name ) {
+foreach ( $xmlReaderConstants as $name ) {
$fullName = "XMLREADER_$name";
$newName = "XMLReader::$name";
- if( !defined( $fullName ) ) {
- if( defined( $newName ) ) {
+ if ( !defined( $fullName ) ) {
+ if ( defined( $newName ) ) {
define( $fullName, constant( $newName ) );
} else {
// broken or missing the extension...
function prefetch( $page, $rev ) {
$page = intval( $page );
$rev = intval( $rev );
- while( $this->lastPage < $page && !$this->atEnd ) {
+ while ( $this->lastPage < $page && !$this->atEnd ) {
$this->debug( "BaseDump::prefetch at page $this->lastPage, looking for $page" );
$this->nextPage();
}
- if( $this->lastPage > $page || $this->atEnd ) {
+ if ( $this->lastPage > $page || $this->atEnd ) {
$this->debug( "BaseDump::prefetch already past page $page looking for rev $rev [$this->lastPage, $this->lastRev]" );
return null;
}
- while( $this->lastRev < $rev && !$this->atEnd && !$this->atPageEnd ) {
+ while ( $this->lastRev < $rev && !$this->atEnd && !$this->atPageEnd ) {
$this->debug( "BaseDump::prefetch at page $this->lastPage, rev $this->lastRev, looking for $page, $rev" );
$this->nextRev();
}
- if( $this->lastRev == $rev && !$this->atEnd ) {
+ if ( $this->lastRev == $rev && !$this->atEnd ) {
$this->debug( "BaseDump::prefetch hit on $page, $rev [$this->lastPage, $this->lastRev]" );
return $this->nextText();
} else {
function debug( $str ) {
wfDebug( $str . "\n" );
- //global $dumper;
- //$dumper->progress( $str );
+ // global $dumper;
+ // $dumper->progress( $str );
}
/**
* @access private
*/
function nextPage() {
- if( $this->skipTo( 'page', 'mediawiki' ) ) {
- if( $this->skipTo( 'id' ) ) {
+ if ( $this->skipTo( 'page', 'mediawiki' ) ) {
+ if ( $this->skipTo( 'id' ) ) {
$this->lastPage = intval( $this->nodeContents() );
$this->lastRev = 0;
$this->atPageEnd = false;
* @access private
*/
function nextRev() {
- if( $this->skipTo( 'revision' ) ) {
- if( $this->skipTo( 'id' ) ) {
+ if ( $this->skipTo( 'revision' ) ) {
+ if ( $this->skipTo( 'id' ) ) {
$this->lastRev = intval( $this->nodeContents() );
}
} else {
/**
* @access private
*/
- function skipTo( $name, $parent='page' ) {
- if( $this->atEnd ) {
+ function skipTo( $name, $parent = 'page' ) {
+ if ( $this->atEnd ) {
return false;
}
- while( $this->reader->read() ) {
- if( $this->reader->nodeType == XMLREADER_ELEMENT &&
+ while ( $this->reader->read() ) {
+ if ( $this->reader->nodeType == XMLREADER_ELEMENT &&
$this->reader->name == $name ) {
return true;
}
- if( $this->reader->nodeType == XMLREADER_END_ELEMENT &&
+ if ( $this->reader->nodeType == XMLREADER_END_ELEMENT &&
$this->reader->name == $parent ) {
$this->debug( "BaseDump::skipTo found </$parent> searching for <$name>" );
return false;
* @access private
*/
function nodeContents() {
- if( $this->atEnd ) {
+ if ( $this->atEnd ) {
return null;
}
- if( $this->reader->isEmptyElement ) {
+ if ( $this->reader->isEmptyElement ) {
return "";
}
$buffer = "";
- while( $this->reader->read() ) {
+ while ( $this->reader->read() ) {
switch( $this->reader->nodeType ) {
case XMLREADER_TEXT:
// case XMLREADER_WHITESPACE:
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class BenchmarkPurge extends Maintenance {
public function execute() {
global $wgUseSquid;
- if( !$wgUseSquid ) {
- $this->error( "Squid purge benchmark doesn't do much without squid support on.". true );
+ if ( !$wgUseSquid ) {
+ $this->error( "Squid purge benchmark doesn't do much without squid support on." . true );
} else {
$this->output( "There are " . count( $wgSquidServers ) . " defined squid servers:\n" );
- if( $this->hasOption( 'count' ) ) {
- $lengths = array( intval( $this->getOption('count') ) );
+ if ( $this->hasOption( 'count' ) ) {
+ $lengths = array( intval( $this->getOption( 'count' ) ) );
} else {
$lengths = array( 1, 10, 100 );
}
- foreach( $lengths as $length ) {
+ foreach ( $lengths as $length ) {
$urls = $this->randomUrlList( $length );
$trial = $this->benchSquid( $urls );
$this->output( $trial . "\n" );
*/
private function benchSquid( $urls, $trials = 1 ) {
$start = wfTime();
- for( $i = 0; $i < $trials; $i++) {
+ for ( $i = 0; $i < $trials; $i++ ) {
SquidUpdate::purge( $urls );
}
$delta = wfTime() - $start;
*/
private function randomUrlList( $length ) {
$list = array();
- for( $i = 0; $i < $length; $i++ ) {
+ for ( $i = 0; $i < $length; $i++ ) {
$list[] = $this->randomUrl();
}
return $list;
private function randomTitle() {
$str = '';
$length = mt_rand( 1, 20 );
- for( $i = 0; $i < $length; $i++ ) {
- $str .= chr( mt_rand( ord('a'), ord('z') ) );
+ for ( $i = 0; $i < $length; $i++ ) {
+ $str .= chr( mt_rand( ord( 'a' ), ord( 'z' ) ) );
}
return ucfirst( $str );
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class ChangePassword extends Maintenance {
public function __construct() {
}
public function execute() {
- $user = User::newFromName( $this->getOption('user') );
- if( !$user->getId() ) {
- $this->error( "No such user: " . $this->getOption('user'), true );
+ $user = User::newFromName( $this->getOption( 'user' ) );
+ if ( !$user->getId() ) {
+ $this->error( "No such user: " . $this->getOption( 'user' ), true );
}
try {
- $user->setPassword( $this->getOption('password') );
+ $user->setPassword( $this->getOption( 'password' ) );
$user->saveSettings();
$this->output( "Password set for " . $user->getName() . "\n" );
- } catch( PasswordError $pwe ) {
+ } catch ( PasswordError $pwe ) {
$this->error( $pwe->getText(), true );
}
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class CheckAutoLoader extends Maintenance {
public function __construct() {
global $wgAutoloadLocalClasses, $IP;
$files = array_unique( $wgAutoloadLocalClasses );
- foreach( $files as $file ) {
- if( function_exists( 'parsekit_compile_file' ) ){
+ foreach ( $files as $file ) {
+ if ( function_exists( 'parsekit_compile_file' ) ) {
$parseInfo = parsekit_compile_file( "$IP/$file" );
$classes = array_keys( $parseInfo['class_table'] );
} else {
}
foreach ( $classes as $class ) {
if ( !isset( $wgAutoloadLocalClasses[$class] ) ) {
- //printf( "%-50s Unlisted, in %s\n", $class, $file );
+ // printf( "%-50s Unlisted, in %s\n", $class, $file );
$this->output( "\t'$class' => '$file',\n" );
} elseif ( $wgAutoloadLocalClasses[$class] !== $file ) {
$this->output( "$class: Wrong file: found in $file, listed in " . $wgAutoloadLocalClasses[$class] . "\n" );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class CheckBadRedirects extends Maintenance {
public function __construct() {
$dbr = wfGetDB( DB_SLAVE );
$result = $dbr->select(
array( 'page' ),
- array( 'page_namespace','page_title', 'page_latest' ),
+ array( 'page_namespace', 'page_title', 'page_latest' ),
array( 'page_is_redirect' => 1 ) );
$count = $result->numRows();
$this->output( "Found $count total redirects.\n" .
"Looking for bad redirects:\n\n" );
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
$title = Title::makeTitle( $row->page_namespace, $row->page_title );
$rev = Revision::newFromId( $row->page_latest );
- if( $rev ) {
+ if ( $rev ) {
$target = Title::newFromRedirect( $rev->getText() );
- if( !$target ) {
+ if ( !$target ) {
$this->output( $title->getPrefixedText() . "\n" );
}
}
*
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class CheckImages extends Maintenance {
$numGood = 0;
do {
- $res = $dbr->select( 'image', '*', array( 'img_name > ' . $dbr->addQuotes( $start ) ),
+ $res = $dbr->select( 'image', '*', array( 'img_name > ' . $dbr->addQuotes( $start ) ),
__METHOD__, array( 'LIMIT' => $this->mBatchSize ) );
foreach ( $res as $row ) {
$numImages++;
$this->mDescription = "Check syntax for all PHP files in MediaWiki";
$this->addOption( 'with-extensions', 'Also recurse the extensions folder' );
$this->addOption( 'path', 'Specific path (file or directory) to check, either with absolute path or relative to the root of this MediaWiki installation',
- false, true);
- $this->addOption( 'list-file', 'Text file containing list of files or directories to check', false, true);
+ false, true );
+ $this->addOption( 'list-file', 'Text file containing list of files or directories to check', false, true );
$this->addOption( 'modified', 'Check only files that were modified (requires SVN command-line client)' );
$this->addOption( 'syntax-only', 'Check for syntax validity only, skip code style warnings' );
}
// ParseKit is broken on PHP 5.3+, disabled until this is fixed
$useParseKit = function_exists( 'parsekit_compile_file' ) && version_compare( PHP_VERSION, '5.3', '<' );
- $str = 'Checking syntax (using ' . ( $useParseKit ?
+ $str = 'Checking syntax (using ' . ( $useParseKit ?
'parsekit)' : ' php -l, this can take a long time)' );
$this->output( $str );
- foreach( $this->mFiles as $f ) {
- if( $useParseKit ) {
+ foreach ( $this->mFiles as $f ) {
+ if ( $useParseKit ) {
$this->checkFileWithParsekit( $f );
} else {
$this->checkFileWithCli( $f );
}
- if( !$this->hasOption( 'syntax-only' ) ) {
+ if ( !$this->hasOption( 'syntax-only' ) ) {
$this->checkForMistakes( $f );
}
}
if ( !$f ) {
$this->error( "Can't open file $file\n", true );
}
- while( $path = trim( fgets( $f ) ) ) {
+ while ( $path = trim( fgets( $f ) ) ) {
$this->addPath( $path );
}
fclose( $f );
// Only check files in these directories.
// Don't just put $IP, because the recursive dir thingie goes into all subdirs
- $dirs = array(
+ $dirs = array(
$IP . '/includes',
$IP . '/config',
$IP . '/languages',
$IP . '/maintenance',
$IP . '/skins',
);
- if( $this->hasOption( 'with-extensions' ) ) {
+ if ( $this->hasOption( 'with-extensions' ) ) {
$dirs[] = $IP . '/extensions';
}
- foreach( $dirs as $d ) {
+ foreach ( $dirs as $d ) {
$this->addDirectoryContent( $d );
}
$ext = pathinfo( $file, PATHINFO_EXTENSION );
if ( $ext != 'php' && $ext != 'inc' && $ext != 'php5' )
return false;
- foreach( $this->mIgnorePaths as $regex ) {
+ foreach ( $this->mIgnorePaths as $regex ) {
$m = array();
if ( preg_match( "~{$regex}~", $file, $m ) )
return false;
*/
private function addDirectoryContent( $dir ) {
$iterator = new RecursiveIteratorIterator(
- new RecursiveDirectoryIterator( $dir ),
+ new RecursiveDirectoryIterator( $dir ),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ( $iterator as $file ) {
* @return boolean
*/
private function checkFileWithCli( $file ) {
- $res = exec( 'php -l ' . wfEscapeShellArg( $file ) );
- if( strpos( $res, 'No syntax errors detected' ) === false ) {
+ $res = exec( 'php -l ' . wfEscapeShellArg( $file ) );
+ if ( strpos( $res, 'No syntax errors detected' ) === false ) {
$this->mFailures[$file] = $res;
$this->output( $res . "\n" );
return false;
* @return boolean
*/
private function checkForMistakes( $file ) {
- foreach( $this->mNoStyleCheckPaths as $regex ) {
+ foreach ( $this->mNoStyleCheckPaths as $regex ) {
$m = array();
if ( preg_match( "~{$regex}~", $file, $m ) )
return;
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class CheckUsernames extends Maintenance {
* @ingroup maintenance
*/
-require_once( dirname(__FILE__) . '/cleanupTable.inc' );
+require_once( dirname( __FILE__ ) . '/cleanupTable.inc' );
class CapsCleanup extends TableCleanup {
public function __construct() {
$this->namespace = intval( $this->getOption( 'namespace', 0 ) );
$this->dryrun = $this->hasOption( 'dry-run' );
$wgUser->setName( 'Conversion script' );
- if( $wgCapitalLinks )
+ if ( $wgCapitalLinks )
$this->error( "\$wgCapitalLinks is on -- no need for caps links cleanup.", true );
$this->runTable( array(
$display = $current->getPrefixedText();
$upper = $row->page_title;
$lower = $wgContLang->lcfirst( $row->page_title );
- if( $upper == $lower ) {
+ if ( $upper == $lower ) {
$this->output( "\"$display\" already lowercase.\n" );
return $this->progress( 0 );
}
$target = Title::makeTitle( $row->page_namespace, $lower );
$targetDisplay = $target->getPrefixedText();
- if( $target->exists() ) {
+ if ( $target->exists() ) {
$this->output( "\"$display\" skipped; \"$targetDisplay\" already exists\n" );
return $this->progress( 0 );
}
- if( $this->dryrun ) {
+ if ( $this->dryrun ) {
$this->output( "\"$display\" -> \"$targetDisplay\": DRY RUN, NOT MOVED\n" );
$ok = true;
} else {
$ok = $current->moveTo( $target, false, 'Converting page titles to lowercase' );
$this->output( "\"$display\" -> \"$targetDisplay\": $ok\n" );
}
- if( $ok === true ) {
+ if ( $ok === true ) {
$this->progress( 1 );
- if( $row->page_namespace == $this->namespace ) {
+ if ( $row->page_namespace == $this->namespace ) {
$talk = $target->getTalkPage();
$row->page_namespace = $talk->getNamespace();
- if( $talk->exists() ) {
+ if ( $talk->exists() ) {
return $this->processRow( $row );
}
}
* @ingroup Maintenance
*/
-function fixDupes( $fixthem = false) {
+function fixDupes( $fixthem = false ) {
$dbw = wfGetDB( DB_MASTER );
$cur = $dbw->tableName( 'cur' );
$old = $dbw->tableName( 'old' );
);
$n = $dbw->numRows( $res );
echo "Found $n titles with duplicate entries.\n";
- if( $n > 0 ) {
- if( $fixthem ) {
+ if ( $n > 0 ) {
+ if ( $fixthem ) {
echo "Correcting...\n";
} else {
echo "Just a demo...\n";
}
- while( $row = $dbw->fetchObject( $res ) ) {
+ while ( $row = $dbw->fetchObject( $res ) ) {
$ns = intval( $row->cur_namespace );
$title = $dbw->addQuotes( $row->cur_title );
'cur_title' => $row->cur_title ) );
echo "$ns:$row->cur_title (canonical ID $id)\n";
- if( $id != $row->id ) {
+ if ( $id != $row->id ) {
echo " ** minimum ID $row->id; ";
$timeMin = $dbw->selectField( 'cur', 'cur_timestamp', array(
'cur_id' => $row->id ) );
$timeFirst = $dbw->selectField( 'cur', 'cur_timestamp', array(
'cur_id' => $id ) );
- if( $timeMin == $timeFirst ) {
+ if ( $timeMin == $timeFirst ) {
echo "timestamps match at $timeFirst; ok\n";
} else {
echo "timestamps don't match! min: $timeMin, first: $timeFirst; ";
- if( $timeMin > $timeFirst ) {
+ if ( $timeMin > $timeFirst ) {
$id = $row->id;
echo "keeping minimum: $id\n";
} else {
}
}
- if( $fixthem ) {
+ if ( $fixthem ) {
$dbw->query( <<<END
INSERT
INTO $old
}
}
$dbw->query( 'UNLOCK TABLES' );
- if( $fixthem ) {
+ if ( $fixthem ) {
echo "Done.\n";
} else {
echo "Run again with --fix option to delete the duplicates.\n";
function checkDupes( $fixthem = false, $indexonly = false ) {
$dbw = wfGetDB( DB_MASTER );
- if( $dbw->indexExists( 'cur', 'name_title' ) &&
+ if ( $dbw->indexExists( 'cur', 'name_title' ) &&
$dbw->indexUnique( 'cur', 'name_title' ) ) {
- echo wfWikiID().": cur table has the current unique index; no duplicate entries.\n";
- } elseif( $dbw->indexExists( 'cur', 'name_title_dup_prevention' ) ) {
- echo wfWikiID().": cur table has a temporary name_title_dup_prevention unique index; no duplicate entries.\n";
+ echo wfWikiID() . ": cur table has the current unique index; no duplicate entries.\n";
+ } elseif ( $dbw->indexExists( 'cur', 'name_title_dup_prevention' ) ) {
+ echo wfWikiID() . ": cur table has a temporary name_title_dup_prevention unique index; no duplicate entries.\n";
} else {
- echo wfWikiID().": cur table has the old non-unique index and may have duplicate entries.\n";
- if( !$indexonly ) {
+ echo wfWikiID() . ": cur table has the old non-unique index and may have duplicate entries.\n";
+ if ( !$indexonly ) {
fixDupes( $fixthem );
}
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/cleanupTable.inc' );
+require_once( dirname( __FILE__ ) . '/cleanupTable.inc' );
class ImageCleanup extends TableCleanup {
protected $defaultParams = array(
global $wgContLang;
$source = $row->img_name;
- if( $source == '' ) {
+ if ( $source == '' ) {
// Ye olde empty rows. Just kill them.
$this->killRow( $source );
return $this->progress( 1 );
$title = Title::makeTitleSafe( NS_FILE, $cleaned );
- if( is_null( $title ) ) {
+ if ( is_null( $title ) ) {
$this->output( "page $source ($cleaned) is illegal.\n" );
$safe = $this->buildSafeTitle( $cleaned );
- if( $safe === false )
+ if ( $safe === false )
return $this->progress( 0 );
$this->pokeFile( $source, $safe );
return $this->progress( 1 );
}
- if( $title->getDBkey() !== $source ) {
+ if ( $title->getDBkey() !== $source ) {
$munged = $title->getDBkey();
$this->output( "page $source ($munged) doesn't match self.\n" );
$this->pokeFile( $source, $munged );
}
private function killRow( $name ) {
- if( $this->dryrun ) {
+ if ( $this->dryrun ) {
$this->output( "DRY RUN: would delete bogus row '$name'\n" );
} else {
$this->output( "deleting bogus row '$name'\n" );
private function pokeFile( $orig, $new ) {
$path = $this->filePath( $orig );
- if( !file_exists( $path ) ) {
+ if ( !file_exists( $path ) ) {
$this->output( "missing file: $path\n" );
return $this->killRow( $orig );
}
$conflict = ( $this->imageExists( $final, $db ) ||
( $this->pageExists( $orig, $db ) && $this->pageExists( $final, $db ) ) );
- while( $conflict ) {
+ while ( $conflict ) {
$this->output( "Rename conflicts with '$final'...\n" );
$version++;
$final = $this->appendTitle( $new, "_$version" );
$finalPath = $this->filePath( $final );
- if( $this->dryrun ) {
+ if ( $this->dryrun ) {
$this->output( "DRY RUN: would rename $path to $finalPath\n" );
} else {
$this->output( "renaming $path to $finalPath\n" );
array( 'page_title' => $orig, 'page_namespace' => NS_FILE ),
__METHOD__ );
$dir = dirname( $finalPath );
- if( !file_exists( $dir ) ) {
- if( !wfMkdirParents( $dir ) ) {
+ if ( !file_exists( $dir ) ) {
+ if ( !wfMkdirParents( $dir ) ) {
$this->log( "RENAME FAILED, COULD NOT CREATE $dir" );
$db->rollback();
return;
}
}
- if( rename( $path, $finalPath ) ) {
+ if ( rename( $path, $finalPath ) ) {
$db->commit();
} else {
$this->error( "RENAME FAILED" );
$name );
$test = Title::makeTitleSafe( NS_FILE, $x );
- if( is_null( $test ) || $test->getDBkey() !== $x ) {
+ if ( is_null( $test ) || $test->getDBkey() !== $x ) {
$this->error( "Unable to generate safe title from '$name', got '$x'" );
return false;
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class CleanupSpam extends Maintenance {
public function __construct() {
$this->error( "Not a valid hostname specification: $spec", true );
}
- if ( $this->hasOption('all') ) {
+ if ( $this->hasOption( 'all' ) ) {
// Clean up spam on all wikis
$this->output( "Finding spam on " . count( $wgLocalDatabases ) . " wikis\n" );
$found = false;
foreach ( $wgLocalDatabases as $wikiID ) {
$dbr = wfGetDB( DB_SLAVE, array(), $wikiID );
- $count = $dbr->selectField( 'externallinks', 'COUNT(*)',
+ $count = $dbr->selectField( 'externallinks', 'COUNT(*)',
array( 'el_index' . $dbr->buildLike( $like ) ), __METHOD__ );
if ( $count ) {
$found = true;
// Clean up spam on this wiki
$dbr = wfGetDB( DB_SLAVE );
- $res = $dbr->select( 'externallinks', array( 'DISTINCT el_from' ),
+ $res = $dbr->select( 'externallinks', array( 'DISTINCT el_from' ),
array( 'el_index' . $dbr->buildLike( $like ) ), __METHOD__ );
$count = $dbr->numRows( $res );
$this->output( "Found $count articles containing $spec\n" );
while ( $rev && LinkFilter::matchEntry( $rev->getText() , $domain ) ) {
# Revision::getPrevious can't be used in this way before MW 1.6 (Revision.php 1.26)
- #$rev = $rev->getPrevious();
+ # $rev = $rev->getPrevious();
$revId = $title->getPreviousRevisionID( $revId );
if ( $revId ) {
$rev = Revision::newFromTitle( $title, $revId );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class TableCleanup extends Maintenance {
protected $defaultParams = array(
global $wgUser;
$wgUser->setName( 'Conversion script' );
$this->dryrun = $this->hasOption( 'dry-run' );
- if( $this->dryrun ) {
+ if ( $this->dryrun ) {
$this->output( "Checking for bad titles...\n" );
} else {
$this->output( "Checking and fixing bad titles...\n" );
protected function progress( $updated ) {
$this->updated += $updated;
$this->processed++;
- if( $this->processed % $this->reportInterval != 0 ) {
+ if ( $this->processed % $this->reportInterval != 0 ) {
return;
}
$portion = $this->processed / $this->count;
$estimatedTotalTime = $delta / $portion;
$eta = $this->startTime + $estimatedTotalTime;
- $this->output(
+ $this->output(
sprintf( "%s %s: %6.2f%% done on %s; ETA %s [%d/%d] %.2f/sec <%.2f%% updated>\n",
wfWikiID(),
wfTimestamp( TS_DB, intval( $now ) ),
$this->processed,
$this->count,
$this->processed / $delta,
- $updateRate * 100.0
+ $updateRate * 100.0
)
);
flush();
$dbr = wfGetDB( DB_SLAVE );
if ( array_diff( array_keys( $params ),
- array( 'table', 'conds', 'index', 'callback' ) ) )
+ array( 'table', 'conds', 'index', 'callback' ) ) )
{
- throw new MWException( __METHOD__.': Missing parameter ' . implode( ', ', $params ) );
+ throw new MWException( __METHOD__ . ': Missing parameter ' . implode( ', ', $params ) );
}
$table = $params['table'];
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/cleanupTable.inc' );
+require_once( dirname( __FILE__ ) . '/cleanupTable.inc' );
class TitleCleanup extends TableCleanup {
public function __construct() {
$verified = $wgContLang->normalize( $display );
$title = Title::newFromText( $verified );
- if( !is_null( $title )
+ if ( !is_null( $title )
&& $title->canExist()
&& $title->getNamespace() == $row->page_namespace
&& $title->getDBkey() === $row->page_title )
return $this->progress( 0 ); // all is fine
}
- if( $row->page_namespace == NS_FILE && $this->fileExists( $row->page_title ) ) {
+ if ( $row->page_namespace == NS_FILE && $this->fileExists( $row->page_title ) ) {
$this->output( "file $row->page_title needs cleanup, please run cleanupImages.php.\n" );
return $this->progress( 0 );
- } elseif( is_null( $title ) ) {
+ } elseif ( is_null( $title ) ) {
$this->output( "page $row->page_id ($display) is illegal.\n" );
$this->moveIllegalPage( $row );
return $this->progress( 1 );
$legalized = preg_replace_callback( "!([^$legal])!",
array( &$this, 'hexChar' ),
$row->page_title );
- if( $legalized == '.' ) $legalized = '(dot)';
- if( $legalized == '_' ) $legalized = '(space)';
+ if ( $legalized == '.' ) $legalized = '(dot)';
+ if ( $legalized == '_' ) $legalized = '(space)';
$legalized = 'Broken/' . $legalized;
$title = Title::newFromText( $legalized );
- if( is_null( $title ) ) {
+ if ( is_null( $title ) ) {
$clean = 'Broken/id:' . $row->page_id;
$this->output( "Couldn't legalize; form '$legalized' still invalid; using '$clean'\n" );
$title = Title::newFromText( $clean );
- } elseif( $title->exists() ) {
+ } elseif ( $title->exists() ) {
$clean = 'Broken/id:' . $row->page_id;
$this->output( "Legalized for '$legalized' exists; using '$clean'\n" );
$title = Title::newFromText( $clean );
}
$dest = $title->getDBkey();
- if( $this->dryrun ) {
+ if ( $this->dryrun ) {
$this->output( "DRY RUN: would rename $row->page_id ($row->page_namespace,'$row->page_title') to ($row->page_namespace,'$dest')\n" );
} else {
$this->output( "renaming $row->page_id ($row->page_namespace,'$row->page_title') to ($row->page_namespace,'$dest')\n" );
}
protected function moveInconsistentPage( $row, $title ) {
- if( $title->exists() || $title->getInterwiki() || !$title->canExist() ) {
- if( $title->getInterwiki() || !$title->canExist() ) {
+ if ( $title->exists() || $title->getInterwiki() || !$title->canExist() ) {
+ if ( $title->getInterwiki() || !$title->canExist() ) {
$prior = $title->getPrefixedDbKey();
} else {
$prior = $title->getDBkey();
}
# Old cleanupTitles could move articles there. See bug 23147.
- $ns = $row->page_namespace;
- if ( $ns < 0) $ns = 0;
+ $ns = $row->page_namespace;
+ if ( $ns < 0 ) $ns = 0;
$clean = 'Broken/' . $prior;
$verified = Title::makeTitleSafe( $ns, $clean );
- if( $verified->exists() ) {
+ if ( $verified->exists() ) {
$blah = "Broken/id:" . $row->page_id;
$this->output( "Couldn't legalize; form '$clean' exists; using '$blah'\n" );
$verified = Title::makeTitleSafe( $ns, $blah );
}
$title = $verified;
}
- if( is_null( $title ) ) {
+ if ( is_null( $title ) ) {
$this->error( "Something awry; empty title.", true );
}
$ns = $title->getNamespace();
$dest = $title->getDBkey();
- if( $this->dryrun ) {
+ if ( $this->dryrun ) {
$this->output( "DRY RUN: would rename $row->page_id ($row->page_namespace,'$row->page_title') to ($ns,'$dest')\n" );
} else {
$this->output( "renaming $row->page_id ($row->page_namespace,'$row->page_title') to ($ns,'$dest')\n" );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/cleanupTable.inc' );
+require_once( dirname( __FILE__ ) . '/cleanupTable.inc' );
class WatchlistCleanup extends TableCleanup {
protected $defaultParams = array(
$verified = $wgContLang->normalize( $display );
$title = Title::newFromText( $verified );
- if( $row->wl_user == 0 || is_null( $title ) || !$title->equals( $current ) ) {
+ if ( $row->wl_user == 0 || is_null( $title ) || !$title->equals( $current ) ) {
$this->output( "invalid watch by {$row->wl_user} for ({$row->wl_namespace}, \"{$row->wl_title}\")\n" );
$updated = $this->removeWatch( $row );
$this->progress( $updated );
}
private function removeWatch( $row ) {
- if( !$this->dryrun && $this->hasOption( 'fix' ) ) {
+ if ( !$this->dryrun && $this->hasOption( 'fix' ) ) {
$dbw = wfGetDB( DB_MASTER );
$dbw->delete( 'watchlist', array(
'wl_user' => $row->wl_user,
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class ClearInterwikiCache extends Maintenance {
foreach ( $wgLocalDatabases as $db ) {
$this->output( "$db..." );
foreach ( $prefixes as $prefix ) {
- $wgMemc->delete("$db:interwiki:$prefix");
+ $wgMemc->delete( "$db:interwiki:$prefix" );
}
$this->output( "done\n" );
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class clear_stats extends Maintenance {
public function execute() {
global $wgLocalDatabases, $wgMemc;
foreach ( $wgLocalDatabases as $db ) {
- $wgMemc->delete("$db:stats:request_with_session");
- $wgMemc->delete("$db:stats:request_without_session");
- $wgMemc->delete("$db:stats:pcache_hit");
- $wgMemc->delete("$db:stats:pcache_miss_invalid");
- $wgMemc->delete("$db:stats:pcache_miss_expired");
- $wgMemc->delete("$db:stats:pcache_miss_absent");
- $wgMemc->delete("$db:stats:pcache_miss_stub");
- $wgMemc->delete("$db:stats:image_cache_hit");
- $wgMemc->delete("$db:stats:image_cache_miss");
- $wgMemc->delete("$db:stats:image_cache_update");
- $wgMemc->delete("$db:stats:diff_cache_hit");
- $wgMemc->delete("$db:stats:diff_cache_miss");
- $wgMemc->delete("$db:stats:diff_uncacheable");
+ $wgMemc->delete( "$db:stats:request_with_session" );
+ $wgMemc->delete( "$db:stats:request_without_session" );
+ $wgMemc->delete( "$db:stats:pcache_hit" );
+ $wgMemc->delete( "$db:stats:pcache_miss_invalid" );
+ $wgMemc->delete( "$db:stats:pcache_miss_expired" );
+ $wgMemc->delete( "$db:stats:pcache_miss_absent" );
+ $wgMemc->delete( "$db:stats:pcache_miss_stub" );
+ $wgMemc->delete( "$db:stats:image_cache_hit" );
+ $wgMemc->delete( "$db:stats:image_cache_miss" );
+ $wgMemc->delete( "$db:stats:image_cache_update" );
+ $wgMemc->delete( "$db:stats:diff_cache_hit" );
+ $wgMemc->delete( "$db:stats:diff_cache_miss" );
+ $wgMemc->delete( "$db:stats:diff_uncacheable" );
}
}
}
/**
* Backwards-compatibility wrapper for old-style maintenance scripts
*/
-require( dirname(__FILE__) . '/Maintenance.php' );
+require( dirname( __FILE__ ) . '/Maintenance.php' );
if ( !isset( $optionsWithArgs ) ) {
$optionsWithArgs = array();
/** */
function convertLinks() {
global $wgDBtype;
- if( $wgDBtype == 'postgres' ) {
+ if ( $wgDBtype == 'postgres' ) {
wfOut( "Links table already ok on Postgres.\n" );
return;
}
global $wgLang, $wgDBserver, $wgDBadminuser, $wgDBadminpassword, $wgDBname;
global $noKeys, $logPerformance, $fh;
- $tuplesAdded = $numBadLinks = $curRowsRead = 0; #counters etc
+ $tuplesAdded = $numBadLinks = $curRowsRead = 0; # counters etc
$totalTuplesInserted = 0; # total tuples INSERTed into links_temp
- $reportCurReadProgress = true; #whether or not to give progress reports while reading IDs from cur table
- $curReadReportInterval = 1000; #number of rows between progress reports
+ $reportCurReadProgress = true; # whether or not to give progress reports while reading IDs from cur table
+ $curReadReportInterval = 1000; # number of rows between progress reports
- $reportLinksConvProgress = true; #whether or not to give progress reports during conversion
- $linksConvInsertInterval = 1000; #number of rows per INSERT
+ $reportLinksConvProgress = true; # whether or not to give progress reports during conversion
+ $linksConvInsertInterval = 1000; # number of rows per INSERT
$initialRowOffset = 0;
- #$finalRowOffset = 0; # not used yet; highest row number from links table to process
+ # $finalRowOffset = 0; # not used yet; highest row number from links table to process
# Overwrite the old links table with the new one. If this is set to false,
# the new table will be left at links_temp.
$logPerformance = false; # output performance data to a file
$perfLogFilename = "convLinksPerf.txt";
- #--------------------------------------------------------------------
+ # --------------------------------------------------------------------
$dbw = wfGetDB( DB_MASTER );
- list ($cur, $links, $links_temp, $links_backup) = $dbw->tableNamesN( 'cur', 'links', 'links_temp', 'links_backup' );
+ list ( $cur, $links, $links_temp, $links_backup ) = $dbw->tableNamesN( 'cur', 'links', 'links_temp', 'links_backup' );
// Get database-agnostic limit clause
$sql_limit = $dbw->limitResult( "SELECT l_from FROM $links", 1 );
}
$res = $dbw->query( "SELECT COUNT(*) AS count FROM $links" );
- $row = $dbw->fetchObject($res);
+ $row = $dbw->fetchObject( $res );
$numRows = $row->count;
$dbw->freeResult( $res );
}
$ids[$title] = $row->cur_id;
$curRowsRead++;
- if ($reportCurReadProgress) {
- if (($curRowsRead % $curReadReportInterval) == 0) {
- performanceLog( $curRowsRead . " " . (getMicroTime() - $baseTime) . "\n" );
+ if ( $reportCurReadProgress ) {
+ if ( ( $curRowsRead % $curReadReportInterval ) == 0 ) {
+ performanceLog( $curRowsRead . " " . ( getMicroTime() - $baseTime ) . "\n" );
wfOut( "\t$curRowsRead rows of $cur table read.\n" );
}
}
$dbw->freeResult( $res );
$dbw->bufferResults( true );
wfOut( "Finished loading IDs.\n\n" );
- performanceLog( "Took " . (getMicroTime() - $baseTime) . " seconds to load IDs.\n\n" );
- #--------------------------------------------------------------------
+ performanceLog( "Took " . ( getMicroTime() - $baseTime ) . " seconds to load IDs.\n\n" );
+ # --------------------------------------------------------------------
# Now, step through the links table (in chunks of $linksConvInsertInterval rows),
# convert, and write to the new table.
performanceLog( "Processing $numRows rows from $links table...\n" );
performanceLog( "rows inserted vs seconds elapsed:\n" );
- for ($rowOffset = $initialRowOffset; $rowOffset < $numRows; $rowOffset += $linksConvInsertInterval) {
+ for ( $rowOffset = $initialRowOffset; $rowOffset < $numRows; $rowOffset += $linksConvInsertInterval ) {
$sqlRead = "SELECT * FROM $links ";
- $sqlRead = $dbw->limitResult($sqlRead, $linksConvInsertInterval,$rowOffset);
- $res = $dbw->query($sqlRead);
+ $sqlRead = $dbw->limitResult( $sqlRead, $linksConvInsertInterval, $rowOffset );
+ $res = $dbw->query( $sqlRead );
if ( $noKeys ) {
- $sqlWrite = array("INSERT INTO $links_temp (l_from,l_to) VALUES ");
+ $sqlWrite = array( "INSERT INTO $links_temp (l_from,l_to) VALUES " );
} else {
- $sqlWrite = array("INSERT IGNORE INTO $links_temp (l_from,l_to) VALUES ");
+ $sqlWrite = array( "INSERT IGNORE INTO $links_temp (l_from,l_to) VALUES " );
}
$tuplesAdded = 0; # no tuples added to INSERT yet
- while ( $row = $dbw->fetchObject($res) ) {
+ while ( $row = $dbw->fetchObject( $res ) ) {
$fromTitle = $row->l_from;
if ( array_key_exists( $fromTitle, $ids ) ) { # valid title
$from = $ids[$fromTitle];
$numBadLinks++;
}
}
- $dbw->freeResult($res);
- #wfOut( "rowOffset: $rowOffset\ttuplesAdded: $tuplesAdded\tnumBadLinks: $numBadLinks\n" );
+ $dbw->freeResult( $res );
+ # wfOut( "rowOffset: $rowOffset\ttuplesAdded: $tuplesAdded\tnumBadLinks: $numBadLinks\n" );
if ( $tuplesAdded != 0 ) {
- if ($reportLinksConvProgress) {
+ if ( $reportLinksConvProgress ) {
wfOut( "Inserting $tuplesAdded tuples into $links_temp..." );
}
- $dbw->query( implode("",$sqlWrite) );
+ $dbw->query( implode( "", $sqlWrite ) );
$totalTuplesInserted += $tuplesAdded;
- if ($reportLinksConvProgress)
+ if ( $reportLinksConvProgress )
wfOut( " done. Total $totalTuplesInserted tuples inserted.\n" );
- performanceLog( $totalTuplesInserted . " " . (getMicroTime() - $baseTime) . "\n" );
+ performanceLog( $totalTuplesInserted . " " . ( getMicroTime() - $baseTime ) . "\n" );
}
}
wfOut( "$totalTuplesInserted valid titles and $numBadLinks invalid titles were processed.\n\n" );
performanceLog( "$totalTuplesInserted valid titles and $numBadLinks invalid titles were processed.\n" );
- performanceLog( "Total execution time: " . (getMicroTime() - $startTime) . " seconds.\n" );
+ performanceLog( "Total execution time: " . ( getMicroTime() - $startTime ) . " seconds.\n" );
if ( $logPerformance ) { fclose ( $fh ); }
}
- #--------------------------------------------------------------------
+ # --------------------------------------------------------------------
if ( $overwriteLinksTable ) {
$dbConn = Database::newFromParams( $wgDBserver, $wgDBadminuser, $wgDBadminpassword, $wgDBname );
- if (!($dbConn->isOpen())) {
+ if ( !( $dbConn->isOpen() ) ) {
wfOut( "Opening connection to database failed.\n" );
return;
}
# Check for existing links_backup, and delete it if it exists.
wfOut( "Dropping backup links table if it exists..." );
- $dbConn->query( "DROP TABLE IF EXISTS $links_backup", DB_MASTER);
+ $dbConn->query( "DROP TABLE IF EXISTS $links_backup", DB_MASTER );
wfOut( " done.\n" );
# Swap in the new table, and move old links table to links_backup
}
}
-#--------------------------------------------------------------------
+# --------------------------------------------------------------------
function createTempTable() {
global $wgDBserver, $wgDBadminuser, $wgDBadminpassword, $wgDBname;
global $noKeys;
$dbConn = Database::newFromParams( $wgDBserver, $wgDBadminuser, $wgDBadminpassword, $wgDBname );
- if (!($dbConn->isOpen())) {
+ if ( !( $dbConn->isOpen() ) ) {
wfOut( "Opening connection to database failed.\n" );
return;
}
$links_temp = $dbConn->tableName( 'links_temp' );
wfOut( "Dropping temporary links table if it exists..." );
- $dbConn->query( "DROP TABLE IF EXISTS $links_temp");
+ $dbConn->query( "DROP TABLE IF EXISTS $links_temp" );
wfOut( " done.\n" );
wfOut( "Creating temporary links table..." );
if ( $noKeys ) {
$dbConn->query( "CREATE TABLE $links_temp ( " .
"l_from int(8) unsigned NOT NULL default '0', " .
- "l_to int(8) unsigned NOT NULL default '0')");
+ "l_to int(8) unsigned NOT NULL default '0')" );
} else {
$dbConn->query( "CREATE TABLE $links_temp ( " .
"l_from int(8) unsigned NOT NULL default '0', " .
"l_to int(8) unsigned NOT NULL default '0', " .
"UNIQUE KEY l_from(l_from,l_to), " .
- "KEY (l_to))");
+ "KEY (l_to))" );
}
wfOut( " done.\n\n" );
}
}
function getMicroTime() { # return time in seconds, with microsecond accuracy
- list($usec, $sec) = explode(" ", microtime());
- return ((float)$usec + (float)$sec);
+ list( $usec, $sec ) = explode( " ", microtime() );
+ return ( (float)$usec + (float)$sec );
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class ConvertLinks extends Maintenance {
public function execute() {
global $wgDBtype;
- if( $wgDBtype == 'postgres' ) {
+ if ( $wgDBtype == 'postgres' ) {
$this->output( "Links table already ok on Postgres.\n" );
return;
}
global $wgLang, $wgDBserver, $wgDBadminuser, $wgDBadminpassword, $wgDBname;
global $noKeys, $logPerformance, $fh;
- $tuplesAdded = $numBadLinks = $curRowsRead = 0; #counters etc
+ $tuplesAdded = $numBadLinks = $curRowsRead = 0; # counters etc
$totalTuplesInserted = 0; # total tuples INSERTed into links_temp
-
- $reportCurReadProgress = true; #whether or not to give progress reports while reading IDs from cur table
- $curReadReportInterval = 1000; #number of rows between progress reports
-
- $reportLinksConvProgress = true; #whether or not to give progress reports during conversion
- $linksConvInsertInterval = 1000; #number of rows per INSERT
-
+
+ $reportCurReadProgress = true; # whether or not to give progress reports while reading IDs from cur table
+ $curReadReportInterval = 1000; # number of rows between progress reports
+
+ $reportLinksConvProgress = true; # whether or not to give progress reports during conversion
+ $linksConvInsertInterval = 1000; # number of rows per INSERT
+
$initialRowOffset = 0;
- #$finalRowOffset = 0; # not used yet; highest row number from links table to process
-
+ # $finalRowOffset = 0; # not used yet; highest row number from links table to process
+
# Overwrite the old links table with the new one. If this is set to false,
# the new table will be left at links_temp.
$overwriteLinksTable = true;
$logPerformance = false; # output performance data to a file
$perfLogFilename = "convLinksPerf.txt";
- #--------------------------------------------------------------------
-
+ # --------------------------------------------------------------------
+
$dbw = wfGetDB( DB_MASTER );
- list ($cur, $links, $links_temp, $links_backup) = $dbw->tableNamesN( 'cur', 'links', 'links_temp', 'links_backup' );
+ list ( $cur, $links, $links_temp, $links_backup ) = $dbw->tableNamesN( 'cur', 'links', 'links_temp', 'links_backup' );
$res = $dbw->query( "SELECT l_from FROM $links LIMIT 1" );
if ( $dbw->fieldType( $res, 0 ) == "int" ) {
}
$res = $dbw->query( "SELECT COUNT(*) AS count FROM $links" );
- $row = $dbw->fetchObject($res);
+ $row = $dbw->fetchObject( $res );
$numRows = $row->count;
$dbw->freeResult( $res );
}
$ids[$title] = $row->cur_id;
$curRowsRead++;
- if ($reportCurReadProgress) {
- if (($curRowsRead % $curReadReportInterval) == 0) {
- $this->performanceLog( $curRowsRead . " " . ($this->getMicroTime() - $baseTime) . "\n" );
+ if ( $reportCurReadProgress ) {
+ if ( ( $curRowsRead % $curReadReportInterval ) == 0 ) {
+ $this->performanceLog( $curRowsRead . " " . ( $this->getMicroTime() - $baseTime ) . "\n" );
$this->output( "\t$curRowsRead rows of $cur table read.\n" );
}
}
$dbw->freeResult( $res );
$dbw->bufferResults( true );
$this->output( "Finished loading IDs.\n\n" );
- $this->performanceLog( "Took " . ($this->getMicroTime() - $baseTime) . " seconds to load IDs.\n\n" );
- #--------------------------------------------------------------------
-
+ $this->performanceLog( "Took " . ( $this->getMicroTime() - $baseTime ) . " seconds to load IDs.\n\n" );
+ # --------------------------------------------------------------------
+
# Now, step through the links table (in chunks of $linksConvInsertInterval rows),
# convert, and write to the new table.
$this->createTempTable();
$this->performanceLog( "Processing $numRows rows from $links table...\n" );
$this->performanceLog( "rows inserted vs seconds elapsed:\n" );
- for ($rowOffset = $initialRowOffset; $rowOffset < $numRows; $rowOffset += $linksConvInsertInterval) {
+ for ( $rowOffset = $initialRowOffset; $rowOffset < $numRows; $rowOffset += $linksConvInsertInterval ) {
$sqlRead = "SELECT * FROM $links ";
- $sqlRead = $dbw->limitResult($sqlRead, $linksConvInsertInterval,$rowOffset);
- $res = $dbw->query($sqlRead);
+ $sqlRead = $dbw->limitResult( $sqlRead, $linksConvInsertInterval, $rowOffset );
+ $res = $dbw->query( $sqlRead );
if ( $noKeys ) {
- $sqlWrite = array("INSERT INTO $links_temp (l_from,l_to) VALUES ");
+ $sqlWrite = array( "INSERT INTO $links_temp (l_from,l_to) VALUES " );
} else {
- $sqlWrite = array("INSERT IGNORE INTO $links_temp (l_from,l_to) VALUES ");
+ $sqlWrite = array( "INSERT IGNORE INTO $links_temp (l_from,l_to) VALUES " );
}
$tuplesAdded = 0; # no tuples added to INSERT yet
- while ( $row = $dbw->fetchObject($res) ) {
+ while ( $row = $dbw->fetchObject( $res ) ) {
$fromTitle = $row->l_from;
if ( array_key_exists( $fromTitle, $ids ) ) { # valid title
$from = $ids[$fromTitle];
$numBadLinks++;
}
}
- $dbw->freeResult($res);
- #$this->output( "rowOffset: $rowOffset\ttuplesAdded: $tuplesAdded\tnumBadLinks: $numBadLinks\n" );
+ $dbw->freeResult( $res );
+ # $this->output( "rowOffset: $rowOffset\ttuplesAdded: $tuplesAdded\tnumBadLinks: $numBadLinks\n" );
if ( $tuplesAdded != 0 ) {
- if ($reportLinksConvProgress) {
+ if ( $reportLinksConvProgress ) {
$this->output( "Inserting $tuplesAdded tuples into $links_temp..." );
}
- $dbw->query( implode("",$sqlWrite) );
+ $dbw->query( implode( "", $sqlWrite ) );
$totalTuplesInserted += $tuplesAdded;
- if ($reportLinksConvProgress)
+ if ( $reportLinksConvProgress )
$this->output( " done. Total $totalTuplesInserted tuples inserted.\n" );
- $this->performanceLog( $totalTuplesInserted . " " . ($this->getMicroTime() - $baseTime) . "\n" );
+ $this->performanceLog( $totalTuplesInserted . " " . ( $this->getMicroTime() - $baseTime ) . "\n" );
}
}
$this->output( "$totalTuplesInserted valid titles and $numBadLinks invalid titles were processed.\n\n" );
$this->performanceLog( "$totalTuplesInserted valid titles and $numBadLinks invalid titles were processed.\n" );
- $this->performanceLog( "Total execution time: " . ($this->getMicroTime() - $startTime) . " seconds.\n" );
+ $this->performanceLog( "Total execution time: " . ( $this->getMicroTime() - $startTime ) . " seconds.\n" );
if ( $logPerformance ) { fclose ( $fh ); }
}
- #--------------------------------------------------------------------
-
+ # --------------------------------------------------------------------
+
if ( $overwriteLinksTable ) {
$dbConn = Database::newFromParams( $wgDBserver, $wgDBadminuser, $wgDBadminpassword, $wgDBname );
- if (!($dbConn->isOpen())) {
+ if ( !( $dbConn->isOpen() ) ) {
$this->output( "Opening connection to database failed.\n" );
return;
}
# Check for existing links_backup, and delete it if it exists.
$this->output( "Dropping backup links table if it exists..." );
- $dbConn->query( "DROP TABLE IF EXISTS $links_backup", DB_MASTER);
+ $dbConn->query( "DROP TABLE IF EXISTS $links_backup", DB_MASTER );
$this->output( " done.\n" );
# Swap in the new table, and move old links table to links_backup
global $noKeys;
$dbConn = Database::newFromParams( $wgDBserver, $wgDBadminuser, $wgDBadminpassword, $wgDBname );
- if (!($dbConn->isOpen())) {
+ if ( !( $dbConn->isOpen() ) ) {
$this->output( "Opening connection to database failed.\n" );
return;
}
$links_temp = $dbConn->tableName( 'links_temp' );
$this->output( "Dropping temporary links table if it exists..." );
- $dbConn->query( "DROP TABLE IF EXISTS $links_temp");
+ $dbConn->query( "DROP TABLE IF EXISTS $links_temp" );
$this->output( " done.\n" );
$this->output( "Creating temporary links table..." );
if ( $noKeys ) {
$dbConn->query( "CREATE TABLE $links_temp ( " .
"l_from int(8) unsigned NOT NULL default '0', " .
- "l_to int(8) unsigned NOT NULL default '0')");
+ "l_to int(8) unsigned NOT NULL default '0')" );
} else {
$dbConn->query( "CREATE TABLE $links_temp ( " .
"l_from int(8) unsigned NOT NULL default '0', " .
"l_to int(8) unsigned NOT NULL default '0', " .
"UNIQUE KEY l_from(l_from,l_to), " .
- "KEY (l_to))");
+ "KEY (l_to))" );
}
$this->output( " done.\n\n" );
}
}
private function getMicroTime() { # return time in seconds, with microsecond accuracy
- list($usec, $sec) = explode(" ", microtime());
- return ((float)$usec + (float)$sec);
+ list( $usec, $sec ) = explode( " ", microtime() );
+ return ( (float)$usec + (float)$sec );
}
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class ConvertUserOptions extends Maintenance {
$id = 0;
$dbw = wfGetDB( DB_MASTER );
- while ($id !== null) {
- $idCond = 'user_id>'.$dbw->addQuotes( $id );
- $optCond = "user_options!=".$dbw->addQuotes( '' ); // For compatibility
+ while ( $id !== null ) {
+ $idCond = 'user_id>' . $dbw->addQuotes( $id );
+ $optCond = "user_options!=" . $dbw->addQuotes( '' ); // For compatibility
$res = $dbw->select( 'user', '*',
array( $optCond, $idCond ), __METHOD__,
array( 'LIMIT' => 50, 'FOR UPDATE' ) );
wfWaitForSlaves( 1 );
- if ($id)
+ if ( $id )
$this->output( "--Converted to ID $id\n" );
}
$this->output( "Conversion done. Converted " . $this->mConversionCount . " user records.\n" );
* @author Rob Church <robchur@gmail.com>
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class CreateAndPromote extends Maintenance {
}
public function execute() {
- $username = $this->getArg(0);
- $password = $this->getArg(1);
+ $username = $this->getArg( 0 );
+ $password = $this->getArg( 1 );
$this->output( wfWikiID() . ": Creating and promoting User:{$username}..." );
$user = User::newFromName( $username );
- if( !is_object( $user ) ) {
+ if ( !is_object( $user ) ) {
$this->error( "invalid username.", true );
- } elseif( 0 != $user->idForName() ) {
+ } elseif ( 0 != $user->idForName() ) {
$this->error( "account exists.", true );
}
# Try to set the password
try {
$user->setPassword( $password );
- } catch( PasswordError $pwe ) {
+ } catch ( PasswordError $pwe ) {
$this->error( $pwe->getText(), true );
}
# Promote user
$user->addGroup( 'sysop' );
- if( $this->hasOption( 'bureaucrat' ) )
+ if ( $this->hasOption( 'bureaucrat' ) )
$user->addGroup( 'bureaucrat' );
# Increment site_stats.ss_users
*/
class DeleteArchivedFilesImplementation {
- static public function doDelete($output, $force) {
+ static public function doDelete( $output, $force ) {
# Data should come off the master, wrapped in a transaction
$dbw = wfGetDB( DB_MASTER );
$dbw->begin();
$output->handleOutput( "Searching for and deleting archived files...\n" );
$res = $dbw->query( "SELECT fa_id,fa_storage_group,fa_storage_key FROM $tbl_arch" );
$count = 0;
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$key = $row->fa_storage_key;
$group = $row->fa_storage_group;
$id = $row->fa_id;
- $path = $repo->getZonePath( 'deleted' ).'/'.$repo->getDeletedHashPath($key).$key;
+ $path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
$sha1 = substr( $key, 0, strcspn( $key, '.' ) );
// Check if the file is used anywhere...
$inuse = $dbw->selectField( 'oldimage', '1',
array( 'oi_sha1' => $sha1,
- 'oi_deleted & '.File::DELETED_FILE => File::DELETED_FILE ),
+ 'oi_deleted & ' . File::DELETED_FILE => File::DELETED_FILE ),
__METHOD__,
array( 'FOR UPDATE' )
);
- if ( $path && file_exists($path) && !$inuse ) {
- unlink($path); // delete
+ if ( $path && file_exists( $path ) && !$inuse ) {
+ unlink( $path ); // delete
$count++;
$dbw->query( "DELETE FROM $tbl_arch WHERE fa_id = $id" );
} else {
* Based on deleteOldRevisions.php by Rob Church
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
-require_once( dirname(__FILE__) . '/deleteArchivedFiles.inc' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/deleteArchivedFiles.inc' );
class DeleteArchivedFiles extends Maintenance {
public function __construct() {
$this->addOption( 'force', 'Force deletion of rows from filearchive' );
}
- public function handleOutput($str) {
- return $this->output($str);
+ public function handleOutput( $str ) {
+ return $this->output( $str );
}
public function execute() {
- if( !$this->hasOption('delete') ) {
+ if ( !$this->hasOption( 'delete' ) ) {
$this->output( "Use --delete to actually confirm this script\n" );
return;
}
$force = $this->hasOption( 'force' );
- DeleteArchivedFilesImplementation::doDelete($this, $force);
+ DeleteArchivedFilesImplementation::doDelete( $this, $force );
}
}
* purgeRedundantText(). See Maintenance for a description of
* those methods.
*/
- static public function doDelete($maint) {
+ static public function doDelete( $maint ) {
$dbw = wfGetDB( DB_MASTER );
$dbw->begin();
# This bit's done
# Purge redundant text records
$dbw->commit();
- if( $deletedRows ) {
+ if ( $deletedRows ) {
$maint->purgeRedundantText( true );
}
}
* Shamelessly stolen from deleteOldRevisions.php by Rob Church :)
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
-require_once( dirname(__FILE__) . '/deleteArchivedRevisions.inc' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/deleteArchivedRevisions.inc' );
class DeleteArchivedRevisions extends Maintenance {
public function __construct() {
$this->addOption( 'delete', 'Performs the deletion' );
}
- public function handleOutput($str) {
- $this->output($str);
+ public function handleOutput( $str ) {
+ $this->output( $str );
}
public function execute() {
$this->output( "Delete archived revisions\n\n" );
# Data should come off the master, wrapped in a transaction
- if( $this->hasOption('delete') ) {
- DeleteArchivedRevisionsImplementation::doDelete($this);
+ if ( $this->hasOption( 'delete' ) ) {
+ DeleteArchivedRevisionsImplementation::doDelete( $this );
} else {
$dbw = wfGetDB( DB_MASTER );
$res = $dbw->selectRow( 'archive', 'COUNT(*) as count', array(), __FUNCTION__ );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class DeleteBatch extends Maintenance {
$user = $this->getOption( 'u', 'Delete page script' );
$reason = $this->getOption( 'r', '' );
$interval = $this->getOption( 'i', 0 );
- if( $this->hasArg() ) {
+ if ( $this->hasArg() ) {
$file = fopen( $this->getArg(), 'r' );
} else {
$file = $this->getStdin();
}
# Setup
- if( !$file ) {
+ if ( !$file ) {
$this->error( "Unable to read file, exiting", true );
}
$wgUser = User::newFromName( $user );
$this->output( "Invalid title '$line' on line $linenum\n" );
continue;
}
- if( !$page->exists() ) {
+ if ( !$page->exists() ) {
$this->output( "Skipping nonexistent page '$line'\n" );
continue;
}
$this->output( $page->getPrefixedText() );
$dbw->begin();
- if( $page->getNamespace() == NS_FILE ) {
+ if ( $page->getNamespace() == NS_FILE ) {
$art = new ImagePage( $page );
$img = wfFindFile( $art->mTitle );
- if( !$img || !$img->delete( $reason ) ) {
+ if ( !$img || !$img->delete( $reason ) ) {
$this->output( "FAILED to delete image file... " );
}
} else {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class DeleteDefaultMessages extends Maintenance {
public function __construct() {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class DeleteImageCache extends Maintenance {
public function __construct() {
public function execute() {
global $wgMemc;
- $until = preg_replace( "/[^\d]/", '', $this->getOption('until') );
- $sleep = (int)$this->getOption('sleep') * 1000; // milliseconds
+ $until = preg_replace( "/[^\d]/", '', $this->getOption( 'until' ) );
+ $sleep = (int)$this->getOption( 'sleep' ) * 1000; // milliseconds
ini_set( 'display_errors', false );
$total = $this->getImageCount();
foreach ( $res as $row ) {
- if ($i % $this->report == 0)
- $this->output( sprintf("%s: %13s done (%s)\n", wfWikiID(), "$i/$total", wfPercent( $i / $total * 100 ) ) );
+ if ( $i % $this->report == 0 )
+ $this->output( sprintf( "%s: %13s done (%s)\n", wfWikiID(), "$i/$total", wfPercent( $i / $total * 100 ) ) );
$md5 = md5( $row->img_name );
$wgMemc->delete( wfMemcKey( 'Image', $md5 ) );
- if ($sleep != 0)
+ if ( $sleep != 0 )
usleep( $sleep );
++$i;
* @author Rob Church <robchur@gmail.com>
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class DeleteOldRevisions extends Maintenance {
public function __construct() {
# Get "active" revisions from the page table
$this->output( "Searching for active revisions..." );
$res = $dbw->query( "SELECT page_latest FROM $tbl_pag{$pageIdClause}" );
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$cur[] = $row->page_latest;
}
$this->output( "done.\n" );
$this->output( "Searching for inactive revisions..." );
$set = implode( ', ', $cur );
$res = $dbw->query( "SELECT rev_id FROM $tbl_rev WHERE rev_id NOT IN ( $set ){$revPageClause}" );
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$old[] = $row->rev_id;
}
$this->output( "done.\n" );
$this->output( "$count old revisions found.\n" );
# Delete as appropriate
- if( $delete && $count ) {
+ if ( $delete && $count ) {
$this->output( "Deleting..." );
$set = implode( ', ', $old );
$dbw->query( "DELETE FROM $tbl_rev WHERE rev_id IN ( $set )" );
# This bit's done
# Purge redundant text records
$dbw->commit();
- if( $delete ) {
+ if ( $delete ) {
$this->purgeRedundantText( true );
}
}
* @todo More efficient cleanup of text records
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class DeleteOrphanedRevisions extends Maintenance {
public function __construct() {
public function execute() {
$this->output( "Delete Orphaned Revisions\n" );
- $report = $this->hasOption('report');
+ $report = $this->hasOption( 'report' );
$dbw = wfGetDB( DB_MASTER );
$dbw->begin();
# Stash 'em all up for deletion (if needed)
$revisions = array();
- foreach( $res as $row )
+ foreach ( $res as $row )
$revisions[] = $row->rev_id;
$dbw->freeResult( $res );
$count = count( $revisions );
$this->output( "found {$count}.\n" );
# Nothing to do?
- if( $report || $count == 0 ) {
+ if ( $report || $count == 0 ) {
$dbw->commit();
- exit(0);
+ exit( 0 );
}
# Delete each revision
* @param $db Database class (needs to be a master)
*/
private function deleteRevs( $id, &$dbw ) {
- if( !is_array( $id ) )
+ if ( !is_array( $id ) )
$id = array( $id );
$dbw->delete( 'revision', array( 'rev_id' => $id ), __METHOD__ );
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class DeleteRevision extends Maintenance {
}
public function execute() {
- if( count( $this->mArgs ) == 0 ) {
+ if ( count( $this->mArgs ) == 0 ) {
$this->error( "No revisions specified", true );
}
- $this->output( "Deleting revision(s) " . implode( ',', $this->mArgs ) .
+ $this->output( "Deleting revision(s) " . implode( ',', $this->mArgs ) .
" from " . wfWikiID() . "...\n" );
$dbw = wfGetDB( DB_MASTER );
public function execute() {
global $wgServer;
$this->output( "Deleting self externals from $wgServer\n" );
- $db = wfGetDB(DB_MASTER);
- while (1) {
+ $db = wfGetDB( DB_MASTER );
+ while ( 1 ) {
wfWaitForSlaves( 2 );
$db->commit();
- $q = $db->limitResult( "DELETE /* deleteSelfExternals */ FROM externallinks WHERE el_to"
+ $q = $db->limitResult( "DELETE /* deleteSelfExternals */ FROM externallinks WHERE el_to"
. $db->buildLike( $wgServer . '/', $db->anyString() ), $this->mBatchSize );
$this->output( "Deleting a batch\n" );
- $db->query($q);
- if (!$db->affectedRows()) exit(0);
+ $db->query( $q );
+ if ( !$db->affectedRows() ) exit( 0 );
}
}
}
exit( 1 );
}
-if( !$maintClass || !class_exists( $maintClass ) ) {
+if ( !$maintClass || !class_exists( $maintClass ) ) {
echo "\$maintClass is not set or is set to a non-existent class.\n";
exit( 1 );
}
-if( defined( 'MW_NO_SETUP' ) ) {
+if ( defined( 'MW_NO_SETUP' ) ) {
return;
}
// Load settings, using wikimedia-mode if needed
// Fixme: replace this hack with general farm-friendly code
-if( file_exists( "$IP/wmf-config/wikimedia-mode" ) ) {
+if ( file_exists( "$IP/wmf-config/wikimedia-mode" ) ) {
# TODO FIXME! Wikimedia-specific stuff needs to go away to an ext
# Maybe a hook?
global $cluster;
require_once( "$IP/includes/SiteConfiguration.php" );
require( "$IP/wmf-config/wgConf.php" );
$maintenance->loadWikimediaSettings();
- require( $IP.'/wmf-config/CommonSettings.php' );
+ require( $IP . '/wmf-config/CommonSettings.php' );
} else {
require_once( $maintenance->loadSettings() );
}
require_once( "$IP/maintenance/install-utils.inc" );
// Much much faster startup than creating a title object
-$wgTitle = null;
+$wgTitle = null;
// Do the work
try {
// Potentially debug globals
$maintenance->globals();
-} catch( MWException $mwe ) {
+} catch ( MWException $mwe ) {
echo( $mwe->getText() );
exit( 1 );
}
$optionsWithArgs = array( 'pagelist', 'start', 'end' );
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
require_once( 'backup.inc' );
$dumper = new BackupDumper( $argv );
-if( isset( $options['quiet'] ) ) {
+if ( isset( $options['quiet'] ) ) {
$dumper->reporting = false;
}
$dumper->pages = array_filter( $pages, create_function( '$x', 'return $x !== "";' ) );
}
-if( isset( $options['start'] ) ) {
+if ( isset( $options['start'] ) ) {
$dumper->startId = intval( $options['start'] );
}
-if( isset( $options['end'] ) ) {
+if ( isset( $options['end'] ) ) {
$dumper->endId = intval( $options['end'] );
}
$dumper->skipHeader = isset( $options['skip-header'] );
$textMode = isset( $options['stub'] ) ? WikiExporter::STUB : WikiExporter::TEXT;
-if( isset( $options['full'] ) ) {
+if ( isset( $options['full'] ) ) {
$dumper->dump( WikiExporter::FULL, $textMode );
-} elseif( isset( $options['current'] ) ) {
+} elseif ( isset( $options['current'] ) ) {
$dumper->dump( WikiExporter::CURRENT, $textMode );
-} elseif( isset( $options['stable'] ) ) {
+} elseif ( isset( $options['stable'] ) ) {
$dumper->dump( WikiExporter::STABLE, $textMode );
-} elseif( isset( $options['logs'] ) ) {
+} elseif ( isset( $options['logs'] ) ) {
$dumper->dump( WikiExporter::LOGS );
} else {
$dumper->progress( <<<ENDS
# Special case prefix rewrites, for the benefit of Swedish which uses s:t
# as an abbreviation for saint
$prefixRewrites = array(
- 'svwiki' => array ( 's' => 'src'),
- );
+ 'svwiki' => array ( 's' => 'src' ),
+ );
# Construct a list of reserved prefixes
$reserved = array();
foreach ( $languageAliases as $alias => $lang ) {
$reserved[$alias] = 1;
}
- foreach( $sites as $site ) {
+ foreach ( $sites as $site ) {
$reserved[$site->lateral] = 1;
}
if ( empty( $reserved[$prefix] ) ) {
$imap = array( "iw_prefix" => $prefix, "iw_url" => $url, "iw_local" => $local );
- makeLink ($imap, "__global");
+ makeLink ( $imap, "__global" );
}
}
}
# Exclude Wikipedia for Wikipedia
- makeLink ( array ('iw_prefix' => 'wikipedia', 'is_url' => null ), "_wiki" );
+ makeLink ( array ( 'iw_prefix' => 'wikipedia', 'is_url' => null ), "_wiki" );
- #Multilanguage sites
- foreach ($sites as $site)
- makeLanguageLinks ( $site, "_".$site->suffix );
+ # Multilanguage sites
+ foreach ( $sites as $site )
+ makeLanguageLinks ( $site, "_" . $site->suffix );
foreach ( $dblist as $db ) {
# Special wiki
# Has interwiki links and interlanguage links to wikipedia
- makeLink( array( 'iw_prefix' => $db, 'iw_url' => "wiki"), "__sites" );
+ makeLink( array( 'iw_prefix' => $db, 'iw_url' => "wiki" ), "__sites" );
# Links to multilanguage sites
foreach ( $sites as $targetSite ) {
- makeLink( array( 'iw_prefix' => $targetSite->lateral,
- 'iw_url' =>$targetSite->getURL( 'en' ),
+ makeLink( array( 'iw_prefix' => $targetSite->lateral,
+ 'iw_url' => $targetSite->getURL( 'en' ),
'iw_local' => 1 ), $db );
}
} else {
# Find out which site this DB belongs to
$site = false;
- foreach( $sites as $candidateSite ) {
+ foreach ( $sites as $candidateSite ) {
$suffix = $candidateSite->suffix;
if ( preg_match( "/(.*)$suffix$/", $db, $matches ) ) {
$site = $candidateSite;
break;
}
}
- makeLink( array( 'iw_prefix' => $db, 'iw_url' => $site->suffix), "__sites" );
+ makeLink( array( 'iw_prefix' => $db, 'iw_url' => $site->suffix ), "__sites" );
if ( !$site ) {
print "Invalid database $db\n";
continue;
# Lateral links
foreach ( $sites as $targetSite ) {
if ( $targetSite->suffix != $site->suffix ) {
- makeLink( array( 'iw_prefix' => $targetSite->lateral,
- 'iw_url' => $targetSite->getURL( $lang ),
+ makeLink( array( 'iw_prefix' => $targetSite->lateral,
+ 'iw_url' => $targetSite->getURL( $lang ),
'iw_local' => 1 ), $db );
}
}
if ( $site->suffix == "wiki" ) {
- makeLink( array('iw_prefix' => 'w',
- 'iw_url' => "http://en.wikipedia.org/wiki/$1",
- 'iw_local' => 1), $db );
+ makeLink( array( 'iw_prefix' => 'w',
+ 'iw_url' => "http://en.wikipedia.org/wiki/$1",
+ 'iw_local' => 1 ), $db );
}
}
global $prefixRewrites, $dbFile;
if ( isset( $prefixRewrites[$source] ) && isset( $prefixRewrites[$source][$entry[0]] ) )
$entry[0] = $prefixRewrites[$source][$entry[0]];
- if (!array_key_exists("iw_prefix",$entry))
- $entry = array("iw_prefix" => $entry[0], "iw_url" => $entry[1], "iw_local" => $entry[2]);
- if ( array_key_exists($source,$prefixRewrites) &&
- array_key_exists($entry['iw_prefix'],$prefixRewrites[$source]))
+ if ( !array_key_exists( "iw_prefix", $entry ) )
+ $entry = array( "iw_prefix" => $entry[0], "iw_url" => $entry[1], "iw_local" => $entry[2] );
+ if ( array_key_exists( $source, $prefixRewrites ) &&
+ array_key_exists( $entry['iw_prefix'], $prefixRewrites[$source] ) )
$entry['iw_prefix'] = $prefixRewrites[$source][$entry['iw_prefix']];
- if ($dbFile)
- $dbFile->set( "{$source}:{$entry['iw_prefix']}", trim("{$entry['iw_local']} {$entry['iw_url']}") );
+ if ( $dbFile )
+ $dbFile->set( "{$source}:{$entry['iw_prefix']}", trim( "{$entry['iw_local']} {$entry['iw_url']}" ) );
else
print "{$source}:{$entry['iw_prefix']} {$entry['iw_url']} {$entry['iw_local']}\n";
$oldCwd = getcwd();
$optionsWithArgs = array( "o" );
-require_once( dirname(__FILE__) . '/commandLine.inc' );
-require( dirname(__FILE__)."/dumpInterwiki.inc" );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
+require( dirname( __FILE__ ) . "/dumpInterwiki.inc" );
chdir( $oldCwd );
# Output
if ( isset( $options['o'] ) ) {
# To database specified with -o
$dbFile = CdbWriter::open( $options['o'] );
-}
+}
getRebuildInterwikiDump();
* @ingroup Mainatenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class DumpLinks extends Maintenance {
public function __construct() {
array( 'ORDER BY' => 'page_id' ) );
$lastPage = null;
- foreach( $result as $row ) {
- if( $lastPage != $row->page_id ) {
- if( isset( $lastPage ) ) {
+ foreach ( $result as $row ) {
+ if ( $lastPage != $row->page_id ) {
+ if ( isset( $lastPage ) ) {
$this->output( "\n" );
}
$page = Title::makeTitle( $row->page_namespace, $row->page_title );
$link = Title::makeTitle( $row->pl_namespace, $row->pl_title );
$this->output( " " . $link->getPrefixedUrl() );
}
- if( isset( $lastPage ) )
+ if ( isset( $lastPage ) )
$this->output( "\n" );
}
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class DumpSisterSites extends Maintenance {
public function __construct() {
),
__METHOD__ );
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
$title = Title::makeTitle( $row->page_namespace, $row->page_title );
$url = $title->getFullUrl();
$text = $title->getPrefixedText();
$originalDir = getcwd();
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
require_once( 'backup.inc' );
/**
var $failures = 0;
var $maxFailures = 200;
var $failureTimeout = 5; // Seconds to sleep after db failure
-
+
var $php = "php";
var $spawn = false;
var $spawnProc = false;
# Notice messages will foul up your XML output even if they're
# relatively harmless.
- if( ini_get( 'display_errors' ) )
+ if ( ini_get( 'display_errors' ) )
ini_set( 'display_errors', 'stderr' );
$this->initProgress( $this->history );
$input = fopen( $this->input, "rt" );
$result = $this->readDump( $input );
- if( WikiError::isError( $result ) ) {
+ if ( WikiError::isError( $result ) ) {
wfDie( $result->getMessage() );
}
- if( $this->spawnProc ) {
+ if ( $this->spawnProc ) {
$this->closeSpawn();
}
break;
case 'spawn':
$this->spawn = true;
- if( $val ) {
+ if ( $val ) {
$this->php = $val;
}
break;
* Overridden to include prefetch ratio if enabled.
*/
function showReport() {
- if( !$this->prefetch ) {
+ if ( !$this->prefetch ) {
return parent::showReport();
}
- if( $this->reporting ) {
+ if ( $this->reporting ) {
$delta = wfTime() - $this->startTime;
$now = wfTimestamp( TS_DB );
- if( $delta ) {
+ if ( $delta ) {
$rate = $this->pageCount / $delta;
$revrate = $this->revCount / $delta;
$portion = $this->revCount / $this->maxCount;
$bufferSize = 512 * 1024;
do {
$chunk = fread( $input, $bufferSize );
- if( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
+ if ( !xml_parse( $parser, $chunk, feof( $input ) ) ) {
wfDebug( "TextDumpPass::readDump encountered XML parsing error\n" );
return new WikiXmlError( $parser, 'XML import parse failure', $chunk, $offset );
}
$offset += strlen( $chunk );
- } while( $chunk !== false && !feof( $input ) );
+ } while ( $chunk !== false && !feof( $input ) );
xml_parser_free( $parser );
return true;
function getText( $id ) {
$this->fetchCount++;
- if( isset( $this->prefetch ) ) {
+ if ( isset( $this->prefetch ) ) {
$text = $this->prefetch->prefetch( $this->thisPage, $this->thisRev );
- if( $text === null ) {
+ if ( $text === null ) {
// Entry missing from prefetch dump
- } elseif( $text === "" ) {
+ } elseif ( $text === "" ) {
// Blank entries may indicate that the prior dump was broken.
// To be safe, reload it.
} else {
}
private function doGetText( $id ) {
- if( $this->spawn ) {
+ if ( $this->spawn ) {
return $this->getTextSpawned( $id );
} else {
return $this->getTextDbSafe( $id );
* may not survive a long-term server outage.
*/
private function getTextDbSafe( $id ) {
- while( true ) {
+ while ( true ) {
try {
$text = $this->getTextDb( $id );
- $ex = new MWException("Graceful storage failure");
- } catch (DBQueryError $ex) {
+ $ex = new MWException( "Graceful storage failure" );
+ } catch ( DBQueryError $ex ) {
$text = false;
}
- if( $text === false ) {
+ if ( $text === false ) {
$this->failures++;
- if( $this->failures > $this->maxFailures ) {
+ if ( $this->failures > $this->maxFailures ) {
throw $ex;
} else {
$this->progress( "Database failure $this->failures " .
array( 'old_id' => $id ),
'TextPassDumper::getText' );
$text = Revision::getRevisionText( $row );
- if( $text === false ) {
+ if ( $text === false ) {
return false;
}
$stripped = str_replace( "\r", "", $text );
private function getTextSpawned( $id ) {
wfSuppressWarnings();
- if( !$this->spawnProc ) {
+ if ( !$this->spawnProc ) {
// First time?
$this->openSpawn();
}
- while( true ) {
+ while ( true ) {
$text = $this->getTextSpawnedOnce( $id );
- if( !is_string( $text ) ) {
- $this->progress("Database subprocess failed. Respawning...");
+ if ( !is_string( $text ) ) {
+ $this->progress( "Database subprocess failed. Respawning..." );
$this->closeSpawn();
sleep( $this->failureTimeout );
$this->progress( "Spawning database subprocess: $cmd" );
$this->spawnProc = proc_open( $cmd, $spec, $pipes );
- if( !$this->spawnProc ) {
+ if ( !$this->spawnProc ) {
// shit
$this->progress( "Subprocess spawn failed." );
return false;
private function closeSpawn() {
wfSuppressWarnings();
- if( $this->spawnRead )
+ if ( $this->spawnRead )
fclose( $this->spawnRead );
$this->spawnRead = false;
- if( $this->spawnWrite )
+ if ( $this->spawnWrite )
fclose( $this->spawnWrite );
$this->spawnWrite = false;
- if( $this->spawnErr )
+ if ( $this->spawnErr )
fclose( $this->spawnErr );
$this->spawnErr = false;
- if( $this->spawnProc )
+ if ( $this->spawnProc )
pclose( $this->spawnProc );
$this->spawnProc = false;
wfRestoreWarnings();
global $wgContLang;
$ok = fwrite( $this->spawnWrite, "$id\n" );
- //$this->progress( ">> $id" );
- if( !$ok ) return false;
+ // $this->progress( ">> $id" );
+ if ( !$ok ) return false;
$ok = fflush( $this->spawnWrite );
- //$this->progress( ">> [flush]" );
- if( !$ok ) return false;
+ // $this->progress( ">> [flush]" );
+ if ( !$ok ) return false;
$len = fgets( $this->spawnRead );
- //$this->progress( "<< " . trim( $len ) );
- if( $len === false ) return false;
+ // $this->progress( "<< " . trim( $len ) );
+ if ( $len === false ) return false;
$nbytes = intval( $len );
$text = "";
// Subprocess may not send everything at once, we have to loop.
- while( $nbytes > strlen( $text ) ) {
+ while ( $nbytes > strlen( $text ) ) {
$buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
- if( $buffer === false ) break;
+ if ( $buffer === false ) break;
$text .= $buffer;
}
$gotbytes = strlen( $text );
- if( $gotbytes != $nbytes ) {
- $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes ");
+ if ( $gotbytes != $nbytes ) {
+ $this->progress( "Expected $nbytes bytes from database subprocess, got $gotbytes " );
return false;
}
$this->clearOpenElement( null );
$this->lastName = $name;
- if( $name == 'revision' ) {
+ if ( $name == 'revision' ) {
$this->state = $name;
$this->egress->writeOpenPage( null, $this->buffer );
$this->buffer = "";
- } elseif( $name == 'page' ) {
+ } elseif ( $name == 'page' ) {
$this->state = $name;
- if( $this->atStart ) {
+ if ( $this->atStart ) {
$this->egress->writeOpenStream( $this->buffer );
$this->buffer = "";
$this->atStart = false;
}
}
- if( $name == "text" && isset( $attribs['id'] ) ) {
+ if ( $name == "text" && isset( $attribs['id'] ) ) {
$text = $this->getText( $attribs['id'] );
$this->openElement = array( $name, array( 'xml:space' => 'preserve' ) );
- if( strlen( $text ) > 0 ) {
+ if ( strlen( $text ) > 0 ) {
$this->characterData( $parser, $text );
}
} else {
}
function endElement( $parser, $name ) {
- if( $this->openElement ) {
+ if ( $this->openElement ) {
$this->clearOpenElement( "" );
} else {
$this->buffer .= "</$name>";
}
- if( $name == 'revision' ) {
+ if ( $name == 'revision' ) {
$this->egress->writeRevision( null, $this->buffer );
$this->buffer = "";
$this->thisRev = "";
- } elseif( $name == 'page' ) {
+ } elseif ( $name == 'page' ) {
$this->egress->writeClosePage( $this->buffer );
$this->buffer = "";
$this->thisPage = "";
- } elseif( $name == 'mediawiki' ) {
+ } elseif ( $name == 'mediawiki' ) {
$this->egress->writeCloseStream( $this->buffer );
$this->buffer = "";
}
function characterData( $parser, $data ) {
$this->clearOpenElement( null );
- if( $this->lastName == "id" ) {
- if( $this->state == "revision" ) {
+ if ( $this->lastName == "id" ) {
+ if ( $this->state == "revision" ) {
$this->thisRev .= $data;
- } elseif( $this->state == "page" ) {
+ } elseif ( $this->state == "page" ) {
$this->thisPage .= $data;
}
}
}
function clearOpenElement( $style ) {
- if( $this->openElement ) {
+ if ( $this->openElement ) {
$this->buffer .= Xml::element( $this->openElement[0], $this->openElement[1], $style );
$this->openElement = false;
}
$dumper = new TextPassDumper( $argv );
-if( true ) {
+if ( true ) {
$dumper->dump();
} else {
$dumper->progress( <<<ENDS
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class UploadDumper extends Maintenance {
public function __construct() {
$this->mShared = false;
$this->mSharedSupplement = false;
- if( $this->hasOption('local') ) {
+ if ( $this->hasOption( 'local' ) ) {
$this->mAction = 'fetchLocal';
}
- if( $this->hasOption('used') ) {
+ if ( $this->hasOption( 'used' ) ) {
$this->mAction = 'fetchUsed';
}
- if( $this->hasOption('shared') ) {
- if( $this->hasOption('used') ) {
+ if ( $this->hasOption( 'shared' ) ) {
+ if ( $this->hasOption( 'used' ) ) {
// Include shared-repo files in the used check
$this->mShared = true;
} else {
$this->mSharedSupplement = true;
}
}
- $this->{$this->mAction}( $this->mShared );
- if( $this->mSharedSupplement ) {
+ $this-> { $this->mAction } ( $this->mShared );
+ if ( $this->mSharedSupplement ) {
$this->fetchUsed( true );
}
}
ON il_to=img_name";
$result = $dbr->query( $sql );
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
$this->outputItem( $row->il_to, $shared );
}
$dbr->freeResult( $result );
'',
__METHOD__ );
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
$this->outputItem( $row->img_name, $shared );
}
$dbr->freeResult( $result );
function outputItem( $name, $shared ) {
$file = wfFindFile( $name );
- if( $file && $this->filterItem( $file, $shared ) ) {
+ if ( $file && $this->filterItem( $file, $shared ) ) {
$filename = $file->getFullPath();
$rel = wfRelativePath( $filename, $this->mBasePath );
$this->output( "$rel\n" );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class EditCLI extends Maintenance {
public function __construct() {
# Do the edit
$this->output( "Saving... " );
- $status = $wgArticle->doEdit( $text, $summary,
+ $status = $wgArticle->doEdit( $text, $summary,
( $minor ? EDIT_MINOR : 0 ) |
- ( $bot ? EDIT_FORCE_BOT : 0 ) |
+ ( $bot ? EDIT_FORCE_BOT : 0 ) |
( $autoSummary ? EDIT_AUTOSUMMARY : 0 ) |
( $noRC ? EDIT_SUPPRESS_RC : 0 ) );
if ( $status->isOK() ) {
* @ingroup Maintenance
*/
-$wgUseNormalUser = (bool)getenv('MW_WIKIUSER');
+$wgUseNormalUser = (bool)getenv( 'MW_WIKIUSER' );
$optionsWithArgs = array( 'd' );
}
}
-if ( function_exists( 'readline_add_history' )
- && posix_isatty( 0 /*STDIN*/ ) )
+if ( function_exists( 'readline_add_history' )
+ && posix_isatty( 0 /*STDIN*/ ) )
{
$useReadline = true;
} else {
readline_write_history( $historyFile );
}
$val = eval( $line . ";" );
- if( is_null( $val ) ) {
+ if ( is_null( $val ) ) {
echo "\n";
- } elseif( is_string( $val ) || is_numeric( $val ) ) {
+ } elseif ( is_string( $val ) || is_numeric( $val ) ) {
echo "$val\n";
} else {
var_dump( $val );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class FetchText extends Maintenance {
public function __construct() {
public function execute() {
$db = wfGetDB( DB_SLAVE );
$stdin = $this->getStdin();
- while( !feof( $stdin ) ) {
+ while ( !feof( $stdin ) ) {
$line = fgets( $stdin );
- if( $line === false ) {
+ if ( $line === false ) {
// We appear to have lost contact...
break;
}
$textId = intval( $line );
$text = $this->doGetText( $db, $textId );
- $this->output( strlen( $text ) . "\n". $text );
+ $this->output( strlen( $text ) . "\n" . $text );
}
}
array( 'old_id' => $id ),
'TextPassDumper::getText' );
$text = Revision::getRevisionText( $row );
- if( $text === false ) {
+ if ( $text === false ) {
return false;
}
return $text;
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public Licence 2.0 or later
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class FindHooks extends Maintenance {
public function __construct() {
$potential = array();
$bad = array();
$pathinc = array(
- $IP.'/',
- $IP.'/includes/',
- $IP.'/includes/api/',
- $IP.'/includes/db/',
- $IP.'/includes/diff/',
- $IP.'/includes/filerepo/',
- $IP.'/includes/parser/',
- $IP.'/includes/search/',
- $IP.'/includes/specials/',
- $IP.'/includes/upload/',
- $IP.'/languages/',
- $IP.'/maintenance/',
- $IP.'/skins/',
+ $IP . '/',
+ $IP . '/includes/',
+ $IP . '/includes/api/',
+ $IP . '/includes/db/',
+ $IP . '/includes/diff/',
+ $IP . '/includes/filerepo/',
+ $IP . '/includes/parser/',
+ $IP . '/includes/search/',
+ $IP . '/includes/specials/',
+ $IP . '/includes/upload/',
+ $IP . '/languages/',
+ $IP . '/maintenance/',
+ $IP . '/skins/',
);
- foreach( $pathinc as $dir ) {
+ foreach ( $pathinc as $dir ) {
$potential = array_merge( $potential, $this->getHooksFromPath( $dir ) );
$bad = array_merge( $bad, $this->getBadHooksFromPath( $dir ) );
}
$deprecated = array_diff( $documented, $potential );
// let's show the results:
- $this->printArray('Undocumented', $todo );
- $this->printArray('Documented and not found', $deprecated );
- $this->printArray('Unclear hook calls', $bad );
+ $this->printArray( 'Undocumented', $todo );
+ $this->printArray( 'Documented and not found', $deprecated );
+ $this->printArray( 'Unclear hook calls', $bad );
- if ( count( $todo ) == 0 && count( $deprecated ) == 0 && count( $bad ) == 0 )
+ if ( count( $todo ) == 0 && count( $deprecated ) == 0 && count( $bad ) == 0 )
$this->output( "Looks good!\n" );
}
* @return array of documented hooks
*/
private function getHooksFromDoc( $doc ) {
- if( $this->hasOption( 'online' ) ){
+ if ( $this->hasOption( 'online' ) ) {
// All hooks
$allhookdata = Http::get( 'http://www.mediawiki.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:MediaWiki_hooks&cmlimit=500&format=php' );
$allhookdata = unserialize( $allhookdata );
$allhooks = array();
- foreach( $allhookdata['query']['categorymembers'] as $page ) {
+ foreach ( $allhookdata['query']['categorymembers'] as $page ) {
$found = preg_match( '/Manual\:Hooks\/([a-zA-Z0-9- :]+)/', $page['title'], $matches );
- if( $found ) {
+ if ( $found ) {
$hook = str_replace( ' ', '_', $matches[1] );
$allhooks[] = $hook;
}
$oldhookdata = Http::get( 'http://www.mediawiki.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Removed_hooks&cmlimit=500&format=php' );
$oldhookdata = unserialize( $oldhookdata );
$removed = array();
- foreach( $oldhookdata['query']['categorymembers'] as $page ) {
+ foreach ( $oldhookdata['query']['categorymembers'] as $page ) {
$found = preg_match( '/Manual\:Hooks\/([a-zA-Z0-9- :]+)/', $page['title'], $matches );
- if( $found ) {
+ if ( $found ) {
$hook = str_replace( ' ', '_', $matches[1] );
$removed[] = $hook;
}
private function getHooksFromFile( $file ) {
$content = file_get_contents( $file );
$m = array();
- preg_match_all( '/wfRunHooks\(\s*([\'"])(.*?)\1/', $content, $m);
+ preg_match_all( '/wfRunHooks\(\s*([\'"])(.*?)\1/', $content, $m );
return $m[2];
}
*/
private function getHooksFromPath( $path ) {
$hooks = array();
- if( $dh = opendir($path) ) {
- while(($file = readdir($dh)) !== false) {
- if( filetype($path.$file) == 'file' ) {
- $hooks = array_merge( $hooks, $this->getHooksFromFile($path.$file) );
+ if ( $dh = opendir( $path ) ) {
+ while ( ( $file = readdir( $dh ) ) !== false ) {
+ if ( filetype( $path . $file ) == 'file' ) {
+ $hooks = array_merge( $hooks, $this->getHooksFromFile( $path . $file ) );
}
}
- closedir($dh);
+ closedir( $dh );
}
return $hooks;
}
$content = file_get_contents( $file );
$m = array();
# We want to skip the "function wfRunHooks()" one. :)
- preg_match_all( '/(?<!function )wfRunHooks\(\s*[^\s\'"].*/', $content, $m);
+ preg_match_all( '/(?<!function )wfRunHooks\(\s*[^\s\'"].*/', $content, $m );
$list = array();
- foreach( $m[0] as $match ){
+ foreach ( $m[0] as $match ) {
$list[] = $match . "(" . $file . ")";
}
return $list;
*/
private function getBadHooksFromPath( $path ) {
$hooks = array();
- if( $dh = opendir($path) ) {
- while(($file = readdir($dh)) !== false) {
+ if ( $dh = opendir( $path ) ) {
+ while ( ( $file = readdir( $dh ) ) !== false ) {
# We don't want to read this file as it contains bad calls to wfRunHooks()
- if( filetype( $path.$file ) == 'file' && !$path.$file == __FILE__ ) {
- $hooks = array_merge( $hooks, $this->getBadHooksFromFile($path.$file) );
+ if ( filetype( $path . $file ) == 'file' && !$path . $file == __FILE__ ) {
+ $hooks = array_merge( $hooks, $this->getBadHooksFromFile( $path . $file ) );
}
}
- closedir($dh);
+ closedir( $dh );
}
return $hooks;
}
* @param $sort Boolean : wheter to sort the array (Default: true)
*/
private function printArray( $msg, $arr, $sort = true ) {
- if($sort) asort($arr);
- foreach($arr as $v) $this->output( "$msg: $v\n" );
+ if ( $sort ) asort( $arr );
+ foreach ( $arr as $v ) $this->output( "$msg: $v\n" );
}
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class FixSlaveDesync extends Maintenance {
public function __construct() {
# Check for a corrupted page_latest
$dbw = wfGetDB( DB_MASTER );
$dbw->begin();
- $realLatest = $dbw->selectField( 'page', 'page_latest', array( 'page_id' => $pageID ),
+ $realLatest = $dbw->selectField( 'page', 'page_latest', array( 'page_id' => $pageID ),
__METHOD__, 'FOR UPDATE' );
- #list( $masterFile, $masterPos ) = $dbw->getMasterPos();
+ # list( $masterFile, $masterPos ) = $dbw->getMasterPos();
$found = false;
foreach ( $slaveIndexes as $i ) {
$db = wfGetDB( $i );
$dbw->commit();
sleep(10);
return;
- }*/
+ }*/
$latest = $db->selectField( 'page', 'page_latest', array( 'page_id' => $pageID ), __METHOD__ );
$max = $db->selectField( 'revision', 'MAX(rev_id)', false, __METHOD__ );
if ( $latest != $realLatest && $realLatest < $max ) {
}
# Find the missing revisions
- $res = $dbw->select( 'revision', array( 'rev_id' ), array( 'rev_page' => $pageID ),
+ $res = $dbw->select( 'revision', array( 'rev_id' ), array( 'rev_page' => $pageID ),
__METHOD__, 'FOR UPDATE' );
$masterIDs = array();
foreach ( $res as $row ) {
# Revision
$row = $dbFrom->selectRow( 'revision', '*', array( 'rev_id' => $rid ), __METHOD__ );
if ( $toMaster ) {
- $id = $dbw->selectField( 'revision', 'rev_id', array( 'rev_id' => $rid ),
+ $id = $dbw->selectField( 'revision', 'rev_id', array( 'rev_id' => $rid ),
__METHOD__, 'FOR UPDATE' );
if ( $id ) {
$this->output( "Revision already exists\n" );
if ( $found ) {
$this->output( "Fixing page_latest... " );
if ( $toMaster ) {
- #$dbw->update( 'page', array( 'page_latest' => $realLatest ), array( 'page_id' => $pageID ), __METHOD__ );
+ # $dbw->update( 'page', array( 'page_latest' => $realLatest ), array( 'page_id' => $pageID ), __METHOD__ );
} else {
foreach ( $slaveIndexes as $i ) {
$db = wfGetDB( $i );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class FixTimestamps extends Maintenance {
public function __construct() {
}
public function execute() {
- $offset = $this->getArg(0) * 3600;
- $start = $this->getArg(1);
- $end = $this->getArg(2);
+ $offset = $this->getArg( 0 ) * 3600;
+ $start = $this->getArg( 1 );
+ $end = $this->getArg( 2 );
$grace = 60; // maximum normal clock offset
-
+
# Find bounding revision IDs
$dbw = wfGetDB( DB_MASTER );
$revisionTable = $dbw->tableName( 'revision' );
$numBadRevs = count( $badRevs );
if ( $numBadRevs > $numGoodRevs ) {
- $this->error(
+ $this->error(
"The majority of revisions in the search interval are marked as bad.
Are you sure the offset ($offset) has the right sign? Positive means the clock
good revisions to provide a majority reference.", true );
} elseif ( $numBadRevs == 0 ) {
$this->output( "No bad revisions found.\n" );
- exit(0);
+ exit( 0 );
}
- $this->output( sprintf( "Fixing %d revisions (%.2f%% of revisions in search interval)\n",
- $numBadRevs, $numBadRevs / ($numGoodRevs + $numBadRevs) * 100 ) );
+ $this->output( sprintf( "Fixing %d revisions (%.2f%% of revisions in search interval)\n",
+ $numBadRevs, $numBadRevs / ( $numGoodRevs + $numBadRevs ) * 100 ) );
$fixup = -$offset;
$sql = "UPDATE $revisionTable " .
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class FixUserRegistration extends Maintenance {
public function __construct() {
*/
-/////////////////////////// COMMAND LINE HELP ////////////////////////////////////
+// ///////////////////////// COMMAND LINE HELP ////////////////////////////////////
// This is a command line script, load MediaWiki env (gives command line options);
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
// if the user asked for an explanation of command line options.
if ( isset( $options["help"] ) ) {
// if we got command line options, check they look valid.
-$validOptions = array ("quiet", "base-url", "directory", "include-binary",
+$validOptions = array ( "quiet", "base-url", "directory", "include-binary",
"w3c-validate", "user", "password", "delete-passed-retests",
"rerun-failed-tests", "max-errors",
"max-runtime", "specific-test", "keep-passed-tests", "help" );
-if (!empty($options)) {
- $unknownArgs = array_diff (array_keys($options), $validOptions);
- foreach ($unknownArgs as $invalidArg) {
+if ( !empty( $options ) ) {
+ $unknownArgs = array_diff ( array_keys( $options ), $validOptions );
+ foreach ( $unknownArgs as $invalidArg ) {
print "Ignoring invalid command-line option: --$invalidArg\n";
}
}
-///////////////////////////// CONFIGURATION ////////////////////////////////////
+// /////////////////////////// CONFIGURATION ////////////////////////////////////
// URL to some wiki on which we can run our tests.
-if (!empty($options["base-url"])) {
- define("WIKI_BASE_URL", $options["base-url"]);
+if ( !empty( $options["base-url"] ) ) {
+ define( "WIKI_BASE_URL", $options["base-url"] );
} else {
- define("WIKI_BASE_URL", $wgServer . $wgScriptPath . '/');
+ define( "WIKI_BASE_URL", $wgServer . $wgScriptPath . '/' );
}
// The directory name where we store the output.
// Example for Windows: "c:\\temp\\wiki-fuzz"
-if (!empty($options["directory"])) {
- define("DIRECTORY", $options["directory"] );
+if ( !empty( $options["directory"] ) ) {
+ define( "DIRECTORY", $options["directory"] );
} else {
- define("DIRECTORY", "{$wgUploadDirectory}/fuzz-tests");
+ define( "DIRECTORY", "{$wgUploadDirectory}/fuzz-tests" );
}
// Should our test fuzz data include binary strings?
-define("INCLUDE_BINARY", isset($options["include-binary"]) );
+define( "INCLUDE_BINARY", isset( $options["include-binary"] ) );
// Whether we want to validate HTML output on the web.
// At the moment very few generated pages will validate, so not recommended.
-define("VALIDATE_ON_WEB", isset($options["w3c-validate"]) );
+define( "VALIDATE_ON_WEB", isset( $options["w3c-validate"] ) );
// URL to use to validate our output:
-define("VALIDATOR_URL", "http://validator.w3.org/check");
+define( "VALIDATOR_URL", "http://validator.w3.org/check" );
// Location of Tidy standalone executable.
-define("PATH_TO_TIDY", "/usr/bin/tidy");
+define( "PATH_TO_TIDY", "/usr/bin/tidy" );
// The name of a user who has edited on your wiki. Used
// when testing the Special:Contributions and Special:Userlogin page.
-if (!empty($options["user"])) {
- define("USER_ON_WIKI", $options["user"] );
+if ( !empty( $options["user"] ) ) {
+ define( "USER_ON_WIKI", $options["user"] );
} else {
- define("USER_ON_WIKI", "nickj");
+ define( "USER_ON_WIKI", "nickj" );
}
// The password of the above user. Used when testing the login page,
// and to do this we sometimes need to login successfully.
-if (!empty($options["password"])) {
- define("USER_PASSWORD", $options["password"] );
+if ( !empty( $options["password"] ) ) {
+ define( "USER_PASSWORD", $options["password"] );
} else {
// And no, this is not a valid password on any public wiki.
- define("USER_PASSWORD", "nickj");
+ define( "USER_PASSWORD", "nickj" );
}
// If we have a test that failed, and then we run it again, and it passes,
// do you want to delete it or keep it?
-define("DELETE_PASSED_RETESTS", isset($options["delete-passed-retests"]) );
+define( "DELETE_PASSED_RETESTS", isset( $options["delete-passed-retests"] ) );
// Do we want to rerun old saved tests at script startup?
// Set to true to help catch regressions, or false if you only want new stuff.
-define("RERUN_OLD_TESTS", isset($options["rerun-failed-tests"]) );
+define( "RERUN_OLD_TESTS", isset( $options["rerun-failed-tests"] ) );
// File where the database errors are logged. Should be defined in LocalSettings.php.
-define("DB_ERROR_LOG_FILE", $wgDBerrorLog );
+define( "DB_ERROR_LOG_FILE", $wgDBerrorLog );
// Run in chatty mode (all output, default), or run in quiet mode (only prints out details of failed tests)?
-define("QUIET", isset($options["quiet"]) );
+define( "QUIET", isset( $options["quiet"] ) );
// Keep all test files, even those that pass. Potentially useful to tracking input that causes something
// unusual to happen, if you don't know what "unusual" is until later.
-define("KEEP_PASSED_TESTS", isset($options["keep-passed-tests"]) );
+define( "KEEP_PASSED_TESTS", isset( $options["keep-passed-tests"] ) );
// The maximum runtime, if specified.
-if (!empty($options["max-runtime"]) && intval($options["max-runtime"])>0) {
- define("MAX_RUNTIME", intval($options["max-runtime"]) );
+if ( !empty( $options["max-runtime"] ) && intval( $options["max-runtime"] ) > 0 ) {
+ define( "MAX_RUNTIME", intval( $options["max-runtime"] ) );
}
// The maximum number of problems to find, if specified. Excludes retest errors.
-if (!empty($options["max-errors"]) && intval($options["max-errors"])>0) {
- define("MAX_ERRORS", intval($options["max-errors"]) );
+if ( !empty( $options["max-errors"] ) && intval( $options["max-errors"] ) > 0 ) {
+ define( "MAX_ERRORS", intval( $options["max-errors"] ) );
}
// if the user has requested a specific test (instead of all tests), and the test they asked for looks valid.
-if (!empty($options["specific-test"])) {
- if (class_exists($options["specific-test"]) && get_parent_class($options["specific-test"])=="pageTest") {
- define("SPECIFIC_TEST", $options["specific-test"] );
+if ( !empty( $options["specific-test"] ) ) {
+ if ( class_exists( $options["specific-test"] ) && get_parent_class( $options["specific-test"] ) == "pageTest" ) {
+ define( "SPECIFIC_TEST", $options["specific-test"] );
}
else {
print "Ignoring invalid --specific-test\n";
}
// Define the file extensions we'll use:
-define("PHP_TEST" , ".test.php");
-define("CURL_TEST", ".curl.sh" );
-define("DATA_FILE", ".data.bin");
-define("INFO_FILE", ".info.txt");
-define("HTML_FILE", ".wiki_preview.html");
+define( "PHP_TEST" , ".test.php" );
+define( "CURL_TEST", ".curl.sh" );
+define( "DATA_FILE", ".data.bin" );
+define( "INFO_FILE", ".info.txt" );
+define( "HTML_FILE", ".wiki_preview.html" );
// If it goes wrong, we want to know about it.
-error_reporting(E_ALL | E_STRICT);
+error_reporting( E_ALL | E_STRICT );
-//////////////// A CLASS THAT GENERATES RANDOM NASTY WIKI & HTML STRINGS //////////////////////
+// ////////////// A CLASS THAT GENERATES RANDOM NASTY WIKI & HTML STRINGS //////////////////////
class wikiFuzz {
// Only some HTML tags are understood with params by MediaWiki, the rest are ignored.
// List the tags that accept params below, as well as what those params are.
public static $data = array(
- "B" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "CAPTION" => array("CLASS", "ID", "STYLE", "align", "lang", "dir", "title"),
- "CENTER" => array("CLASS", "STYLE", "ID", "lang", "dir", "title"),
- "DIV" => array("CLASS", "STYLE", "ID", "align", "lang", "dir", "title"),
- "FONT" => array("CLASS", "STYLE", "ID", "lang", "dir", "title", "face", "size", "color"),
- "H1" => array("STYLE", "CLASS", "ID", "align", "lang", "dir", "title"),
- "H2" => array("STYLE", "CLASS", "ID", "align", "lang", "dir", "title"),
- "HR" => array("STYLE", "CLASS", "ID", "WIDTH", "lang", "dir", "title", "size", "noshade"),
- "LI" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", "type", "value"),
- "TABLE" => array("STYLE", "CLASS", "ID", "BGCOLOR", "WIDTH", "ALIGN", "BORDER", "CELLPADDING",
- "CELLSPACING", "lang", "dir", "title", "summary", "frame", "rules"),
- "TD" => array("STYLE", "CLASS", "ID", "BGCOLOR", "WIDTH", "ALIGN", "COLSPAN", "ROWSPAN",
+ "B" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "CAPTION" => array( "CLASS", "ID", "STYLE", "align", "lang", "dir", "title" ),
+ "CENTER" => array( "CLASS", "STYLE", "ID", "lang", "dir", "title" ),
+ "DIV" => array( "CLASS", "STYLE", "ID", "align", "lang", "dir", "title" ),
+ "FONT" => array( "CLASS", "STYLE", "ID", "lang", "dir", "title", "face", "size", "color" ),
+ "H1" => array( "STYLE", "CLASS", "ID", "align", "lang", "dir", "title" ),
+ "H2" => array( "STYLE", "CLASS", "ID", "align", "lang", "dir", "title" ),
+ "HR" => array( "STYLE", "CLASS", "ID", "WIDTH", "lang", "dir", "title", "size", "noshade" ),
+ "LI" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", "type", "value" ),
+ "TABLE" => array( "STYLE", "CLASS", "ID", "BGCOLOR", "WIDTH", "ALIGN", "BORDER", "CELLPADDING",
+ "CELLSPACING", "lang", "dir", "title", "summary", "frame", "rules" ),
+ "TD" => array( "STYLE", "CLASS", "ID", "BGCOLOR", "WIDTH", "ALIGN", "COLSPAN", "ROWSPAN",
"VALIGN", "abbr", "axis", "headers", "scope", "nowrap", "height", "lang",
- "dir", "title", "char", "charoff"),
- "TH" => array("STYLE", "CLASS", "ID", "BGCOLOR", "WIDTH", "ALIGN", "COLSPAN", "ROWSPAN",
- "VALIGN", "abbr", "axis", "headers", "scope", "nowrap", "height", "lang",
- "dir", "title", "char", "charoff"),
- "TR" => array("CLASS", "STYLE", "ID", "BGCOLOR", "ALIGN", "VALIGN", "lang", "dir", "title", "char", "charoff"),
- "UL" => array("CLASS", "STYLE", "ID", "lang", "dir", "title", "type"),
- "P" => array("style", "class", "id", "align", "lang", "dir", "title"),
- "blockquote" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", "cite"),
- "span" => array("CLASS", "ID", "STYLE", "align", "lang", "dir", "title"),
- "code" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "tt" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "small" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "big" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "s" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "u" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "del" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", "datetime", "cite"),
- "ins" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", "datetime", "cite"),
- "sub" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "sup" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "ol" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", "type", "start"),
- "br" => array("CLASS", "ID", "STYLE", "title", "clear"),
- "cite" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "var" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "dl" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "ruby" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "rt" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "rp" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "dt" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "dl" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "em" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "strong" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "i" => array("CLASS", "ID", "STYLE", "lang", "dir", "title"),
- "thead" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", 'align', 'char', 'charoff', 'valign'),
- "tfoot" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", 'align', 'char', 'charoff', 'valign'),
- "tbody" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", 'align', 'char', 'charoff', 'valign'),
- "colgroup" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", 'align', 'char', 'charoff', 'valign', 'span', 'width'),
- "col" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", 'align', 'char', 'charoff', 'valign', 'span', 'width'),
- "pre" => array("CLASS", "ID", "STYLE", "lang", "dir", "title", "width"),
+ "dir", "title", "char", "charoff" ),
+ "TH" => array( "STYLE", "CLASS", "ID", "BGCOLOR", "WIDTH", "ALIGN", "COLSPAN", "ROWSPAN",
+ "VALIGN", "abbr", "axis", "headers", "scope", "nowrap", "height", "lang",
+ "dir", "title", "char", "charoff" ),
+ "TR" => array( "CLASS", "STYLE", "ID", "BGCOLOR", "ALIGN", "VALIGN", "lang", "dir", "title", "char", "charoff" ),
+ "UL" => array( "CLASS", "STYLE", "ID", "lang", "dir", "title", "type" ),
+ "P" => array( "style", "class", "id", "align", "lang", "dir", "title" ),
+ "blockquote" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", "cite" ),
+ "span" => array( "CLASS", "ID", "STYLE", "align", "lang", "dir", "title" ),
+ "code" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "tt" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "small" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "big" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "s" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "u" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "del" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", "datetime", "cite" ),
+ "ins" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", "datetime", "cite" ),
+ "sub" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "sup" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "ol" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", "type", "start" ),
+ "br" => array( "CLASS", "ID", "STYLE", "title", "clear" ),
+ "cite" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "var" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "dl" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "ruby" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "rt" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "rp" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "dt" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "dl" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "em" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "strong" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "i" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title" ),
+ "thead" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", 'align', 'char', 'charoff', 'valign' ),
+ "tfoot" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", 'align', 'char', 'charoff', 'valign' ),
+ "tbody" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", 'align', 'char', 'charoff', 'valign' ),
+ "colgroup" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", 'align', 'char', 'charoff', 'valign', 'span', 'width' ),
+ "col" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", 'align', 'char', 'charoff', 'valign', 'span', 'width' ),
+ "pre" => array( "CLASS", "ID", "STYLE", "lang", "dir", "title", "width" ),
// extension tags that accept parameters:
- "sort" => array("order", "class"),
- "ref" => array("name"),
- "categorytree" => array("hideroot", "mode", "style"),
- "chemform" => array("link", "wikilink", "query"),
- "section" => array("begin", "new"),
+ "sort" => array( "order", "class" ),
+ "ref" => array( "name" ),
+ "categorytree" => array( "hideroot", "mode", "style" ),
+ "chemform" => array( "link", "wikilink", "query" ),
+ "section" => array( "begin", "new" ),
// older MW transclusion.
- "transclude" => array("page"),
+ "transclude" => array( "page" ),
);
// The types of the HTML that we will be testing were defined above
// Some attribute values.
- static private $other = array("&","=",":","?","\"","\n","%n%n%n%n%n%n%n%n%n%n%n%n","\\");
+ static private $other = array( "&", "=", ":", "?", "\"", "\n", "%n%n%n%n%n%n%n%n%n%n%n%n", "\\" );
static private $ints = array(
// various numbers
- "0","-1","127","-7897","89000","808080","90928345",
- "0xfffffff","ffff",
+ "0", "-1", "127", "-7897", "89000", "808080", "90928345",
+ "0xfffffff", "ffff",
// Different ways of saying: '
"'", // Long UTF-8 Unicode encoding
// MediaWiki to do something other than just print that literal text.
static private $ext = array(
// links, templates, parameters.
- "[[", "]]", "{{", "}}", "|", "[", "]", "{{{", "}}}", "|]]",
+ "[[", "]]", "{{", "}}", "|", "[", "]", "{{{", "}}}", "|]]",
// wiki tables.
"\n{|", "\n|}",
"=", "==", "===", "====", "=====", "======",
// lists (ordered and unordered) and indentation.
- "\n*", "*", "\n:", ":",
+ "\n*", "*", "\n:", ":",
"\n#", "#",
// definition lists (dl, dt, dd), newline, and newline with pre, and a tab.
"\0", // null character
"  ", // spaces and meta characters
"'';!--\"<XSS>=&{()}", // compact injection of XSS & SQL tester
-
+
// various NULL fields
"%00",
"�",
"-----", "\n-----",
// signature, redirect, bold, italics.
- "~~~~", "#REDIRECT [[", "'''", "''",
+ "~~~~", "#REDIRECT [[", "'''", "''",
// comments.
- "<!--", "-->",
+ "<!--", "-->",
// quotes.
"\"", "'",
"}}",
"{{INT:",
"}}",
- '{{SITENAME}}',
- "{{NS:",
+ '{{SITENAME}}',
+ "{{NS:",
"}}",
- "{{LOCALURL:",
+ "{{LOCALURL:",
"}}",
- "{{LOCALURLE:",
+ "{{LOCALURLE:",
"}}",
- "{{SCRIPTPATH}}",
- "{{GRAMMAR:gentiv|",
+ "{{SCRIPTPATH}}",
+ "{{GRAMMAR:gentiv|",
"}}",
"{{REVISIONID}}",
"{{SUBPAGENAME}}",
/**
** Randomly returns one element of the input array.
*/
- static public function chooseInput(array $input) {
- $randindex = wikiFuzz::randnum(count($input) - 1);
+ static public function chooseInput( array $input ) {
+ $randindex = wikiFuzz::randnum( count( $input ) - 1 );
return $input[$randindex];
}
/**
** Returns random number between finish and start.
*/
- static public function randnum($finish,$start=0) {
- return mt_rand($start,$finish);
+ static public function randnum( $finish, $start = 0 ) {
+ return mt_rand( $start, $finish );
}
/**
static private function randstring() {
$thestring = "";
- for ($i=0; $i<40; $i++) {
- $what = wikiFuzz::randnum(1);
+ for ( $i = 0; $i < 40; $i++ ) {
+ $what = wikiFuzz::randnum( 1 );
- if ($what == 0) { // include some random wiki syntax
- $which = wikiFuzz::randnum(count(wikiFuzz::$ext) - 1);
+ if ( $what == 0 ) { // include some random wiki syntax
+ $which = wikiFuzz::randnum( count( wikiFuzz::$ext ) - 1 );
$thestring .= wikiFuzz::$ext[$which];
}
else { // include some random text
- $char = INCLUDE_BINARY
+ $char = INCLUDE_BINARY
// Decimal version:
// "&#" . wikiFuzz::randnum(255) . ";"
// Hex version:
- ? "&#x" . str_pad(dechex(wikiFuzz::randnum(255)), wikiFuzz::randnum(2, 7), "0", STR_PAD_LEFT) . ";"
+ ? "&#x" . str_pad( dechex( wikiFuzz::randnum( 255 ) ), wikiFuzz::randnum( 2, 7 ), "0", STR_PAD_LEFT ) . ";"
// A truly binary version:
// ? chr(wikiFuzz::randnum(0,255))
- : chr(wikiFuzz::randnum(126,32));
+ : chr( wikiFuzz::randnum( 126, 32 ) );
- $length = wikiFuzz::randnum(8);
- $thestring .= str_repeat ($char, $length);
+ $length = wikiFuzz::randnum( 8 );
+ $thestring .= str_repeat ( $char, $length );
}
}
return $thestring;
** or random data from "other".
*/
static private function makestring() {
- $what = wikiFuzz::randnum(2);
- if ($what == 0) {
+ $what = wikiFuzz::randnum( 2 );
+ if ( $what == 0 ) {
return wikiFuzz::randstring();
}
- elseif ($what == 1) {
- return wikiFuzz::$ints[wikiFuzz::randnum(count(wikiFuzz::$ints) - 1)];
+ elseif ( $what == 1 ) {
+ return wikiFuzz::$ints[wikiFuzz::randnum( count( wikiFuzz::$ints ) - 1 )];
}
else {
- return wikiFuzz::$other[wikiFuzz::randnum(count(wikiFuzz::$other) - 1)];
+ return wikiFuzz::$other[wikiFuzz::randnum( count( wikiFuzz::$other ) - 1 )];
}
}
** Strips out the stuff that Mediawiki balks at in a page's title.
** Implementation copied/pasted from cleanupTable.inc & cleanupImages.php
*/
- static public function makeTitleSafe($str) {
+ static public function makeTitleSafe( $str ) {
$legalTitleChars = " %!\"$&'()*,\\-.\\/0-9:;=?@A-Z\\\\^_`a-z~\\x80-\\xFF";
return preg_replace_callback(
"/([^$legalTitleChars])/",
** Returns a string of fuzz text.
*/
static private function loop() {
- switch ( wikiFuzz::randnum(3) ) {
+ switch ( wikiFuzz::randnum( 3 ) ) {
case 1: // an opening tag, with parameters.
$string = "";
- $i = wikiFuzz::randnum(count(wikiFuzz::$types) - 1);
+ $i = wikiFuzz::randnum( count( wikiFuzz::$types ) - 1 );
$t = wikiFuzz::$types[$i];
$arr = wikiFuzz::$data[$t];
$string .= "<" . $t . " ";
- $num_params = min(wikiFuzz::$maxparams, count($arr));
- for ($z=0; $z<$num_params; $z++) {
- $badparam = $arr[wikiFuzz::randnum(count($arr) - 1)];
+ $num_params = min( wikiFuzz::$maxparams, count( $arr ) );
+ for ( $z = 0; $z < $num_params; $z++ ) {
+ $badparam = $arr[wikiFuzz::randnum( count( $arr ) - 1 )];
$badstring = wikiFuzz::makestring();
$string .= $badparam . "=" . wikiFuzz::getRandQuote() . $badstring . wikiFuzz::getRandQuote() . " ";
}
$string .= ">\n";
return $string;
case 2: // a closing tag.
- $i = wikiFuzz::randnum(count(wikiFuzz::$types) - 1);
- return "</". wikiFuzz::$types[$i] . ">";
+ $i = wikiFuzz::randnum( count( wikiFuzz::$types ) - 1 );
+ return "</" . wikiFuzz::$types[$i] . ">";
case 3: // a random string, between tags.
return wikiFuzz::makeString();
}
** Returns one of the three styles of random quote: ', ", and nothing.
*/
static private function getRandQuote() {
- switch ( wikiFuzz::randnum(3) ) {
+ switch ( wikiFuzz::randnum( 3 ) ) {
case 1 : return "'";
case 2 : return "\"";
default: return "";
/**
** Returns fuzz text, with the parameter indicating approximately how many lines of text you want.
*/
- static public function makeFuzz($maxtypes = 2) {
+ static public function makeFuzz( $maxtypes = 2 ) {
$page = "";
- for ($k=0; $k<$maxtypes; $k++) {
+ for ( $k = 0; $k < $maxtypes; $k++ ) {
$page .= wikiFuzz::loop();
}
return $page;
}
-//////// MEDIAWIKI PAGES TO TEST, AND HOW TO TEST THEM ///////
+// ////// MEDIAWIKI PAGES TO TEST, AND HOW TO TEST THEM ///////
/**
** A page test has just these things:
$this->params = array (
"action" => "submit",
- "wpMinoredit" => wikiFuzz::makeFuzz(2),
- "wpPreview" => wikiFuzz::makeFuzz(2),
- "wpSection" => wikiFuzz::makeFuzz(2),
- "wpEdittime" => wikiFuzz::makeFuzz(2),
- "wpSummary" => wikiFuzz::makeFuzz(2),
- "wpScrolltop" => wikiFuzz::makeFuzz(2),
- "wpStarttime" => wikiFuzz::makeFuzz(2),
- "wpAutoSummary" => wikiFuzz::makeFuzz(2),
- "wpTextbox1" => wikiFuzz::makeFuzz(40) // the main wiki text, need lots of this.
+ "wpMinoredit" => wikiFuzz::makeFuzz( 2 ),
+ "wpPreview" => wikiFuzz::makeFuzz( 2 ),
+ "wpSection" => wikiFuzz::makeFuzz( 2 ),
+ "wpEdittime" => wikiFuzz::makeFuzz( 2 ),
+ "wpSummary" => wikiFuzz::makeFuzz( 2 ),
+ "wpScrolltop" => wikiFuzz::makeFuzz( 2 ),
+ "wpStarttime" => wikiFuzz::makeFuzz( 2 ),
+ "wpAutoSummary" => wikiFuzz::makeFuzz( 2 ),
+ "wpTextbox1" => wikiFuzz::makeFuzz( 40 ) // the main wiki text, need lots of this.
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpSection"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpEdittime"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpSummary"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpScrolltop"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpStarttime"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpAutoSummary"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpTextbox1"]);
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpSection"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpEdittime"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpSummary"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpScrolltop"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpStarttime"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpAutoSummary"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpTextbox1"] );
}
}
$this->pagePath = "index.php?title=Special:Listusers";
$this->params = array (
- "title" => wikiFuzz::makeFuzz(2),
- "group" => wikiFuzz::makeFuzz(2),
- "username" => wikiFuzz::makeFuzz(2),
- "Go" => wikiFuzz::makeFuzz(2),
- "limit" => wikiFuzz::chooseInput( array("0", "-1", "---'----------0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- "offset" => wikiFuzz::chooseInput( array("0", "-1", "--------'-----0", "+1", "81343242346234234", wikiFuzz::makeFuzz(2)) )
+ "title" => wikiFuzz::makeFuzz( 2 ),
+ "group" => wikiFuzz::makeFuzz( 2 ),
+ "username" => wikiFuzz::makeFuzz( 2 ),
+ "Go" => wikiFuzz::makeFuzz( 2 ),
+ "limit" => wikiFuzz::chooseInput( array( "0", "-1", "---'----------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ "offset" => wikiFuzz::chooseInput( array( "0", "-1", "--------'-----0", "+1", "81343242346234234", wikiFuzz::makeFuzz( 2 ) ) )
);
}
}
$this->params = array (
"action" => "index.php?title=Special:Search",
- "ns0" => wikiFuzz::makeFuzz(2),
- "ns1" => wikiFuzz::makeFuzz(2),
- "ns2" => wikiFuzz::makeFuzz(2),
- "ns3" => wikiFuzz::makeFuzz(2),
- "ns4" => wikiFuzz::makeFuzz(2),
- "ns5" => wikiFuzz::makeFuzz(2),
- "ns6" => wikiFuzz::makeFuzz(2),
- "ns7" => wikiFuzz::makeFuzz(2),
- "ns8" => wikiFuzz::makeFuzz(2),
- "ns9" => wikiFuzz::makeFuzz(2),
- "ns10" => wikiFuzz::makeFuzz(2),
- "ns11" => wikiFuzz::makeFuzz(2),
- "ns12" => wikiFuzz::makeFuzz(2),
- "ns13" => wikiFuzz::makeFuzz(2),
- "ns14" => wikiFuzz::makeFuzz(2),
- "ns15" => wikiFuzz::makeFuzz(2),
- "redirs" => wikiFuzz::makeFuzz(2),
- "search" => wikiFuzz::makeFuzz(2),
- "offset" => wikiFuzz::chooseInput( array("", "0", "-1", "--------'-----0", "+1", "81343242346234234", wikiFuzz::makeFuzz(2)) ),
- "fulltext" => wikiFuzz::chooseInput( array("", "0", "1", "--------'-----0", "+1", wikiFuzz::makeFuzz(2)) ),
- "searchx" => wikiFuzz::chooseInput( array("", "0", "1", "--------'-----0", "+1", wikiFuzz::makeFuzz(2)) )
+ "ns0" => wikiFuzz::makeFuzz( 2 ),
+ "ns1" => wikiFuzz::makeFuzz( 2 ),
+ "ns2" => wikiFuzz::makeFuzz( 2 ),
+ "ns3" => wikiFuzz::makeFuzz( 2 ),
+ "ns4" => wikiFuzz::makeFuzz( 2 ),
+ "ns5" => wikiFuzz::makeFuzz( 2 ),
+ "ns6" => wikiFuzz::makeFuzz( 2 ),
+ "ns7" => wikiFuzz::makeFuzz( 2 ),
+ "ns8" => wikiFuzz::makeFuzz( 2 ),
+ "ns9" => wikiFuzz::makeFuzz( 2 ),
+ "ns10" => wikiFuzz::makeFuzz( 2 ),
+ "ns11" => wikiFuzz::makeFuzz( 2 ),
+ "ns12" => wikiFuzz::makeFuzz( 2 ),
+ "ns13" => wikiFuzz::makeFuzz( 2 ),
+ "ns14" => wikiFuzz::makeFuzz( 2 ),
+ "ns15" => wikiFuzz::makeFuzz( 2 ),
+ "redirs" => wikiFuzz::makeFuzz( 2 ),
+ "search" => wikiFuzz::makeFuzz( 2 ),
+ "offset" => wikiFuzz::chooseInput( array( "", "0", "-1", "--------'-----0", "+1", "81343242346234234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "fulltext" => wikiFuzz::chooseInput( array( "", "0", "1", "--------'-----0", "+1", wikiFuzz::makeFuzz( 2 ) ) ),
+ "searchx" => wikiFuzz::chooseInput( array( "", "0", "1", "--------'-----0", "+1", wikiFuzz::makeFuzz( 2 ) ) )
);
}
}
$this->pagePath = "index.php?title=Special:Recentchanges";
$this->params = array (
- "action" => wikiFuzz::makeFuzz(2),
- "title" => wikiFuzz::makeFuzz(2),
- "namespace" => wikiFuzz::chooseInput( range(-1, 15) ),
- "Go" => wikiFuzz::makeFuzz(2),
- "invert" => wikiFuzz::chooseInput( array("-1", "---'----------0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- "hideanons" => wikiFuzz::chooseInput( array("-1", "------'-------0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- 'limit' => wikiFuzz::chooseInput( array("0", "-1", "---------'----0", "+1", "81340909772349234", wikiFuzz::makeFuzz(2)) ),
- "days" => wikiFuzz::chooseInput( array("-1", "----------'---0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- "hideminor" => wikiFuzz::chooseInput( array("-1", "-----------'--0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- "hidebots" => wikiFuzz::chooseInput( array("-1", "---------'----0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- "hideliu" => wikiFuzz::chooseInput( array("-1", "-------'------0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- "hidepatrolled" => wikiFuzz::chooseInput( array("-1", "-----'--------0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- "hidemyself" => wikiFuzz::chooseInput( array("-1", "--'-----------0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- 'categories_any'=> wikiFuzz::chooseInput( array("-1", "--'-----------0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- 'categories' => wikiFuzz::chooseInput( array("-1", "--'-----------0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- 'feed' => wikiFuzz::chooseInput( array("-1", "--'-----------0", "+1", "8134", wikiFuzz::makeFuzz(2)) )
+ "action" => wikiFuzz::makeFuzz( 2 ),
+ "title" => wikiFuzz::makeFuzz( 2 ),
+ "namespace" => wikiFuzz::chooseInput( range( -1, 15 ) ),
+ "Go" => wikiFuzz::makeFuzz( 2 ),
+ "invert" => wikiFuzz::chooseInput( array( "-1", "---'----------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ "hideanons" => wikiFuzz::chooseInput( array( "-1", "------'-------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'limit' => wikiFuzz::chooseInput( array( "0", "-1", "---------'----0", "+1", "81340909772349234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "days" => wikiFuzz::chooseInput( array( "-1", "----------'---0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ "hideminor" => wikiFuzz::chooseInput( array( "-1", "-----------'--0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ "hidebots" => wikiFuzz::chooseInput( array( "-1", "---------'----0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ "hideliu" => wikiFuzz::chooseInput( array( "-1", "-------'------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ "hidepatrolled" => wikiFuzz::chooseInput( array( "-1", "-----'--------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ "hidemyself" => wikiFuzz::chooseInput( array( "-1", "--'-----------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'categories_any' => wikiFuzz::chooseInput( array( "-1", "--'-----------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'categories' => wikiFuzz::chooseInput( array( "-1", "--'-----------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'feed' => wikiFuzz::chooseInput( array( "-1", "--'-----------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) )
);
}
}
$this->params = array (
"title" => "Special:Prefixindex",
- "namespace" => wikiFuzz::randnum(-10,101),
- "Go" => wikiFuzz::makeFuzz(2)
+ "namespace" => wikiFuzz::randnum( -10, 101 ),
+ "Go" => wikiFuzz::makeFuzz( 2 )
);
// sometimes we want 'prefix', sometimes we want 'from', and sometimes we want nothing.
- if (wikiFuzz::randnum(3) == 0) {
- $this->params["prefix"] = wikiFuzz::chooseInput( array("-1", "-----'--------0", "+++--+1",
- wikiFuzz::randnum(-10,8134), wikiFuzz::makeFuzz(2)) );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) {
+ $this->params["prefix"] = wikiFuzz::chooseInput( array( "-1", "-----'--------0", "+++--+1",
+ wikiFuzz::randnum( -10, 8134 ), wikiFuzz::makeFuzz( 2 ) ) );
}
- if (wikiFuzz::randnum(3) == 0) {
- $this->params["from"] = wikiFuzz::chooseInput( array("-1", "-----'--------0", "+++--+1",
- wikiFuzz::randnum(-10,8134), wikiFuzz::makeFuzz(2)) );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) {
+ $this->params["from"] = wikiFuzz::chooseInput( array( "-1", "-----'--------0", "+++--+1",
+ wikiFuzz::randnum( -10, 8134 ), wikiFuzz::makeFuzz( 2 ) ) );
}
}
}
$this->params = array (
"action" => "index.php?title=Special:MIMEsearch",
- "mime" => wikiFuzz::makeFuzz(3),
- 'limit' => wikiFuzz::chooseInput( array("0", "-1", "-------'------0", "+1", "81342321351235325", wikiFuzz::makeFuzz(2)) ),
- 'offset' => wikiFuzz::chooseInput( array("0", "-1", "-----'--------0", "+1", "81341231235365252234324", wikiFuzz::makeFuzz(2)) )
+ "mime" => wikiFuzz::makeFuzz( 3 ),
+ 'limit' => wikiFuzz::chooseInput( array( "0", "-1", "-------'------0", "+1", "81342321351235325", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'offset' => wikiFuzz::chooseInput( array( "0", "-1", "-----'--------0", "+1", "81341231235365252234324", wikiFuzz::makeFuzz( 2 ) ) )
);
}
}
$this->pagePath = "index.php?title=Special:Log";
$this->params = array (
- "type" => wikiFuzz::chooseInput( array("", wikiFuzz::makeFuzz(2)) ),
- "par" => wikiFuzz::makeFuzz(2),
- "user" => wikiFuzz::makeFuzz(2),
- "page" => wikiFuzz::makeFuzz(2),
- "from" => wikiFuzz::makeFuzz(2),
- "until" => wikiFuzz::makeFuzz(2),
- "title" => wikiFuzz::makeFuzz(2)
+ "type" => wikiFuzz::chooseInput( array( "", wikiFuzz::makeFuzz( 2 ) ) ),
+ "par" => wikiFuzz::makeFuzz( 2 ),
+ "user" => wikiFuzz::makeFuzz( 2 ),
+ "page" => wikiFuzz::makeFuzz( 2 ),
+ "from" => wikiFuzz::makeFuzz( 2 ),
+ "until" => wikiFuzz::makeFuzz( 2 ),
+ "title" => wikiFuzz::makeFuzz( 2 )
);
}
}
*/
class successfulUserLoginTest extends pageTest {
function __construct() {
- $this->pagePath = "index.php?title=Special:Userlogin&action=submitlogin&type=login&returnto=" . wikiFuzz::makeFuzz(2);
+ $this->pagePath = "index.php?title=Special:Userlogin&action=submitlogin&type=login&returnto=" . wikiFuzz::makeFuzz( 2 );
$this->params = array (
"wpName" => USER_ON_WIKI,
// sometimes real password, sometimes not:
- 'wpPassword' => wikiFuzz::chooseInput( array( wikiFuzz::makeFuzz(2), USER_PASSWORD ) ),
- 'wpRemember' => wikiFuzz::makeFuzz(2)
+ 'wpPassword' => wikiFuzz::chooseInput( array( wikiFuzz::makeFuzz( 2 ), USER_PASSWORD ) ),
+ 'wpRemember' => wikiFuzz::makeFuzz( 2 )
);
- $this->cookie = "wikidb_session=" . wikiFuzz::chooseInput( array("1" , wikiFuzz::makeFuzz(2) ) );
+ $this->cookie = "wikidb_session=" . wikiFuzz::chooseInput( array( "1" , wikiFuzz::makeFuzz( 2 ) ) );
}
}
$this->pagePath = "index.php?title=Special:Userlogin";
$this->params = array (
- 'wpRetype' => wikiFuzz::makeFuzz(2),
- 'wpRemember' => wikiFuzz::makeFuzz(2),
- 'wpRealName' => wikiFuzz::makeFuzz(2),
- 'wpPassword' => wikiFuzz::makeFuzz(2),
- 'wpName' => wikiFuzz::makeFuzz(2),
- 'wpMailmypassword'=> wikiFuzz::makeFuzz(2),
- 'wpLoginattempt' => wikiFuzz::makeFuzz(2),
- 'wpEmail' => wikiFuzz::makeFuzz(2),
- 'wpDomain' => wikiFuzz::chooseInput( array("", "local", wikiFuzz::makeFuzz(2)) ),
- 'wpCreateaccountMail' => wikiFuzz::chooseInput( array("", wikiFuzz::makeFuzz(2)) ),
- 'wpCreateaccount' => wikiFuzz::chooseInput( array("", wikiFuzz::makeFuzz(2)) ),
- 'wpCookieCheck' => wikiFuzz::chooseInput( array("", wikiFuzz::makeFuzz(2)) ),
- 'type' => wikiFuzz::chooseInput( array("signup", "login", "", wikiFuzz::makeFuzz(2)) ),
- 'returnto' => wikiFuzz::makeFuzz(2),
- 'action' => wikiFuzz::chooseInput( array("", "submitlogin", wikiFuzz::makeFuzz(2)) )
+ 'wpRetype' => wikiFuzz::makeFuzz( 2 ),
+ 'wpRemember' => wikiFuzz::makeFuzz( 2 ),
+ 'wpRealName' => wikiFuzz::makeFuzz( 2 ),
+ 'wpPassword' => wikiFuzz::makeFuzz( 2 ),
+ 'wpName' => wikiFuzz::makeFuzz( 2 ),
+ 'wpMailmypassword' => wikiFuzz::makeFuzz( 2 ),
+ 'wpLoginattempt' => wikiFuzz::makeFuzz( 2 ),
+ 'wpEmail' => wikiFuzz::makeFuzz( 2 ),
+ 'wpDomain' => wikiFuzz::chooseInput( array( "", "local", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpCreateaccountMail' => wikiFuzz::chooseInput( array( "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpCreateaccount' => wikiFuzz::chooseInput( array( "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpCookieCheck' => wikiFuzz::chooseInput( array( "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'type' => wikiFuzz::chooseInput( array( "signup", "login", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'returnto' => wikiFuzz::makeFuzz( 2 ),
+ 'action' => wikiFuzz::chooseInput( array( "", "submitlogin", wikiFuzz::makeFuzz( 2 ) ) )
);
- $this->cookie = "wikidb_session=" . wikiFuzz::chooseInput( array("1" , wikiFuzz::makeFuzz(2) ) );
+ $this->cookie = "wikidb_session=" . wikiFuzz::chooseInput( array( "1" , wikiFuzz::makeFuzz( 2 ) ) );
}
}
$this->pagePath = "index.php?title=Special:Ipblocklist";
$this->params = array (
- 'wpUnblockAddress'=> wikiFuzz::makeFuzz(2),
- 'ip' => wikiFuzz::chooseInput( array("20398702394", "", "Nickj2", wikiFuzz::makeFuzz(2),
+ 'wpUnblockAddress' => wikiFuzz::makeFuzz( 2 ),
+ 'ip' => wikiFuzz::chooseInput( array( "20398702394", "", "Nickj2", wikiFuzz::makeFuzz( 2 ),
// something like an IP address, sometimes invalid:
- ( wikiFuzz::randnum(300,-20) . "." . wikiFuzz::randnum(300,-20) . "."
- . wikiFuzz::randnum(300,-20) . "." .wikiFuzz::randnum(300,-20) ) ) ),
- 'id' => wikiFuzz::makeFuzz(2),
- 'wpUnblockReason' => wikiFuzz::makeFuzz(2),
- 'action' => wikiFuzz::chooseInput( array(wikiFuzz::makeFuzz(2), "success", "submit", "unblock") ),
- 'wpEditToken' => wikiFuzz::makeFuzz(2),
- 'wpBlock' => wikiFuzz::chooseInput( array(wikiFuzz::makeFuzz(2), "") ),
- 'limit' => wikiFuzz::chooseInput( array("0", "-1", "--------'-----0", "+1",
- "09700982312351132098234", wikiFuzz::makeFuzz(2)) ),
- 'offset' => wikiFuzz::chooseInput( array("0", "-1", "------'-------0", "+1",
- "09700980982341535324234234", wikiFuzz::makeFuzz(2)) )
+ ( wikiFuzz::randnum( 300, -20 ) . "." . wikiFuzz::randnum( 300, -20 ) . "."
+ . wikiFuzz::randnum( 300, -20 ) . "." . wikiFuzz::randnum( 300, -20 ) ) ) ),
+ 'id' => wikiFuzz::makeFuzz( 2 ),
+ 'wpUnblockReason' => wikiFuzz::makeFuzz( 2 ),
+ 'action' => wikiFuzz::chooseInput( array( wikiFuzz::makeFuzz( 2 ), "success", "submit", "unblock" ) ),
+ 'wpEditToken' => wikiFuzz::makeFuzz( 2 ),
+ 'wpBlock' => wikiFuzz::chooseInput( array( wikiFuzz::makeFuzz( 2 ), "" ) ),
+ 'limit' => wikiFuzz::chooseInput( array( "0", "-1", "--------'-----0", "+1",
+ "09700982312351132098234", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'offset' => wikiFuzz::chooseInput( array( "0", "-1", "------'-------0", "+1",
+ "09700980982341535324234234", wikiFuzz::makeFuzz( 2 ) ) )
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(4) == 0) unset($this->params["action"]);
- if (wikiFuzz::randnum(3) == 0) unset($this->params["ip"]);
- if (wikiFuzz::randnum(2) == 0) unset($this->params["id"]);
- if (wikiFuzz::randnum(3) == 0) unset($this->params["wpUnblockAddress"]);
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["action"] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["ip"] );
+ if ( wikiFuzz::randnum( 2 ) == 0 ) unset( $this->params["id"] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["wpUnblockAddress"] );
}
}
$this->pagePath = "index.php?title=Special:Newimages";
$this->params = array (
- 'hidebots' => wikiFuzz::chooseInput( array(wikiFuzz::makeFuzz(2), "1", "", "-1") ),
- 'wpIlMatch' => wikiFuzz::makeFuzz(2),
- 'until' => wikiFuzz::makeFuzz(2),
- 'from' => wikiFuzz::makeFuzz(2)
+ 'hidebots' => wikiFuzz::chooseInput( array( wikiFuzz::makeFuzz( 2 ), "1", "", "-1" ) ),
+ 'wpIlMatch' => wikiFuzz::makeFuzz( 2 ),
+ 'until' => wikiFuzz::makeFuzz( 2 ),
+ 'from' => wikiFuzz::makeFuzz( 2 )
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(6) == 0) unset($this->params["until"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["from"]);
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["until"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["from"] );
}
}
$this->pagePath = "index.php?title=Special:Imagelist";
$this->params = array (
- 'sort' => wikiFuzz::chooseInput( array("bysize", "byname" , "bydate", wikiFuzz::makeFuzz(2)) ),
- 'limit' => wikiFuzz::chooseInput( array("0", "-1", "--------'-----0", "+1", "09700982312351132098234", wikiFuzz::makeFuzz(2)) ),
- 'offset' => wikiFuzz::chooseInput( array("0", "-1", "------'-------0", "+1", "09700980982341535324234234", wikiFuzz::makeFuzz(2)) ),
- 'wpIlMatch' => wikiFuzz::makeFuzz(2)
+ 'sort' => wikiFuzz::chooseInput( array( "bysize", "byname" , "bydate", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'limit' => wikiFuzz::chooseInput( array( "0", "-1", "--------'-----0", "+1", "09700982312351132098234", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'offset' => wikiFuzz::chooseInput( array( "0", "-1", "------'-------0", "+1", "09700980982341535324234234", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpIlMatch' => wikiFuzz::makeFuzz( 2 )
);
}
}
$this->pagePath = "index.php?title=Special:Export";
$this->params = array (
- 'action' => wikiFuzz::chooseInput( array("submit", "", wikiFuzz::makeFuzz(2)) ),
- 'pages' => wikiFuzz::makeFuzz(2),
- 'curonly' => wikiFuzz::chooseInput( array("", "0", "-1", wikiFuzz::makeFuzz(2)) ),
- 'listauthors' => wikiFuzz::chooseInput( array("", "0", "-1", wikiFuzz::makeFuzz(2)) ),
- 'history' => wikiFuzz::chooseInput( array("0", "-1", "------'-------0", "+1", "09700980982341535324234234", wikiFuzz::makeFuzz(2)) ),
+ 'action' => wikiFuzz::chooseInput( array( "submit", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'pages' => wikiFuzz::makeFuzz( 2 ),
+ 'curonly' => wikiFuzz::chooseInput( array( "", "0", "-1", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'listauthors' => wikiFuzz::chooseInput( array( "", "0", "-1", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'history' => wikiFuzz::chooseInput( array( "0", "-1", "------'-------0", "+1", "09700980982341535324234234", wikiFuzz::makeFuzz( 2 ) ) ),
);
// For the time being, need to disable "submit" action as Tidy barfs on MediaWiki's XML export.
- if ($this->params['action'] == 'submit') $this->params['action'] = '';
+ if ( $this->params['action'] == 'submit' ) $this->params['action'] = '';
// Sometimes remove the history field.
- if (wikiFuzz::randnum(2) == 0) unset($this->params["history"]);
+ if ( wikiFuzz::randnum( 2 ) == 0 ) unset( $this->params["history"] );
// page does not produce HTML.
- $this->tidyValidate = false;
+ $this->tidyValidate = false;
}
}
$this->pagePath = "index.php?title=Special:Booksources";
$this->params = array (
- 'go' => wikiFuzz::makeFuzz(2),
+ 'go' => wikiFuzz::makeFuzz( 2 ),
// ISBN codes have to contain some semi-numeric stuff or will be ignored:
- 'isbn' => "0X0" . wikiFuzz::makeFuzz(2)
+ 'isbn' => "0X0" . wikiFuzz::makeFuzz( 2 )
);
}
}
$this->pagePath = "index.php?title=Special%3AAllpages";
$this->params = array (
- 'from' => wikiFuzz::makeFuzz(2),
- 'namespace' => wikiFuzz::chooseInput( range(-1, 15) ),
- 'go' => wikiFuzz::makeFuzz(2)
+ 'from' => wikiFuzz::makeFuzz( 2 ),
+ 'namespace' => wikiFuzz::chooseInput( range( -1, 15 ) ),
+ 'go' => wikiFuzz::makeFuzz( 2 )
);
}
}
$this->pagePath = "index.php?title=Main_Page&action=history";
$this->params = array (
- 'limit' => wikiFuzz::chooseInput( array("-1", "0", "-------'------0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- 'offset' => wikiFuzz::chooseInput( array("-1", "0", "------'-------0", "+1", "9823412312312412435", wikiFuzz::makeFuzz(2)) ),
- "go" => wikiFuzz::chooseInput( array("first", "last", wikiFuzz::makeFuzz(2)) ),
- "dir" => wikiFuzz::chooseInput( array("prev", "next", wikiFuzz::makeFuzz(2)) ),
- "diff" => wikiFuzz::chooseInput( array("-1", "--------'-----0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- "oldid" => wikiFuzz::chooseInput( array("prev", "-1", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- "feed" => wikiFuzz::makeFuzz(2)
+ 'limit' => wikiFuzz::chooseInput( array( "-1", "0", "-------'------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'offset' => wikiFuzz::chooseInput( array( "-1", "0", "------'-------0", "+1", "9823412312312412435", wikiFuzz::makeFuzz( 2 ) ) ),
+ "go" => wikiFuzz::chooseInput( array( "first", "last", wikiFuzz::makeFuzz( 2 ) ) ),
+ "dir" => wikiFuzz::chooseInput( array( "prev", "next", wikiFuzz::makeFuzz( 2 ) ) ),
+ "diff" => wikiFuzz::chooseInput( array( "-1", "--------'-----0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ "oldid" => wikiFuzz::chooseInput( array( "prev", "-1", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ "feed" => wikiFuzz::makeFuzz( 2 )
);
}
}
$this->pagePath = "index.php?title=Special:Contributions/" . USER_ON_WIKI;
$this->params = array (
- 'target' => wikiFuzz::chooseInput( array(wikiFuzz::makeFuzz(2), "newbies", USER_ON_WIKI) ),
- 'namespace' => wikiFuzz::chooseInput( array(-1, 15, 1, wikiFuzz::makeFuzz(2)) ),
- 'offset' => wikiFuzz::chooseInput( array("0", "-1", "------'-------0", "+1", "982342131232131231241", wikiFuzz::makeFuzz(2)) ),
- 'bot' => wikiFuzz::chooseInput( array("", "-1", "0", "1", wikiFuzz::makeFuzz(2)) ),
- 'go' => wikiFuzz::chooseInput( array("-1", 'prev', 'next', wikiFuzz::makeFuzz(2)) )
+ 'target' => wikiFuzz::chooseInput( array( wikiFuzz::makeFuzz( 2 ), "newbies", USER_ON_WIKI ) ),
+ 'namespace' => wikiFuzz::chooseInput( array( -1, 15, 1, wikiFuzz::makeFuzz( 2 ) ) ),
+ 'offset' => wikiFuzz::chooseInput( array( "0", "-1", "------'-------0", "+1", "982342131232131231241", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'bot' => wikiFuzz::chooseInput( array( "", "-1", "0", "1", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'go' => wikiFuzz::chooseInput( array( "-1", 'prev', 'next', wikiFuzz::makeFuzz( 2 ) ) )
);
}
}
$this->pagePath = "index.php?title=Main_Page";
$this->params = array (
- "useskin" => wikiFuzz::chooseInput( array("chick", "cologneblue", "myskin",
- "nostalgia", "simple", "standard", wikiFuzz::makeFuzz(2)) ),
- "uselang" => wikiFuzz::chooseInput( array( wikiFuzz::makeFuzz(2),
+ "useskin" => wikiFuzz::chooseInput( array( "chick", "cologneblue", "myskin",
+ "nostalgia", "simple", "standard", wikiFuzz::makeFuzz( 2 ) ) ),
+ "uselang" => wikiFuzz::chooseInput( array( wikiFuzz::makeFuzz( 2 ),
"ab", "af", "an", "ar", "arc", "as", "ast", "av", "ay", "az", "ba",
"bat-smg", "be", "bg", "bm", "bn", "bo", "bpy", "br", "bs", "ca",
"ce", "cs", "csb", "cv", "cy", "da", "de", "dv", "dz", "el", "en",
"eo", "es", "et", "eu", "fa", "fi", "fo", "fr", "fur", "fy", "ga",
- "gn", "gsw", "gu", "he", "hi", "hr", "hu", "ia", "id", "ii", "is",
- "it", "ja", "jv", "ka", "km", "kn", "ko", "ks", "ku", "kv", "la",
- "li", "lo", "lt", "lv", "mk", "ml", "ms", "nah", "nap", "nds",
- "nds-nl", "nl", "nn", "no", "non", "nv", "oc", "or", "os", "pa",
- "pl", "pms", "ps", "pt", "pt-br", "qu", "rmy", "ro", "ru", "sc",
+ "gn", "gsw", "gu", "he", "hi", "hr", "hu", "ia", "id", "ii", "is",
+ "it", "ja", "jv", "ka", "km", "kn", "ko", "ks", "ku", "kv", "la",
+ "li", "lo", "lt", "lv", "mk", "ml", "ms", "nah", "nap", "nds",
+ "nds-nl", "nl", "nn", "no", "non", "nv", "oc", "or", "os", "pa",
+ "pl", "pms", "ps", "pt", "pt-br", "qu", "rmy", "ro", "ru", "sc",
"sd", "sk", "sl", "sq", "sr", "sr-ec", "sr-el",
- "su", "sv", "ta", "te", "th", "tr", "tt", "ty", "tyv", "udm",
- "ug", "uk", "ur", "utf8", "vec", "vi", "wa", "xal", "yi", "za",
- "zh", "zh-cn", "zh-hk", "zh-sg", "zh-tw", "zh-tw") ),
- "returnto" => wikiFuzz::makeFuzz(2),
- "feed" => wikiFuzz::chooseInput( array("atom", "rss", wikiFuzz::makeFuzz(2)) ),
- "rcid" => wikiFuzz::makeFuzz(2),
- "action" => wikiFuzz::chooseInput( array("view", "raw", "render", wikiFuzz::makeFuzz(2), "markpatrolled") ),
- "printable" => wikiFuzz::makeFuzz(2),
- "oldid" => wikiFuzz::makeFuzz(2),
- "redirect" => wikiFuzz::makeFuzz(2),
- "diff" => wikiFuzz::makeFuzz(2),
- "search" => wikiFuzz::makeFuzz(2),
- "rdfrom" => wikiFuzz::makeFuzz(2), // things from Article.php from here on:
- "token" => wikiFuzz::makeFuzz(2),
- "tbid" => wikiFuzz::makeFuzz(2),
- "action" => wikiFuzz::chooseInput( array("purge", wikiFuzz::makeFuzz(2)) ),
- "wpReason" => wikiFuzz::makeFuzz(2),
- "wpEditToken" => wikiFuzz::makeFuzz(2),
- "from" => wikiFuzz::makeFuzz(2),
- "bot" => wikiFuzz::makeFuzz(2),
- "summary" => wikiFuzz::makeFuzz(2),
- "direction" => wikiFuzz::chooseInput( array("next", "prev", wikiFuzz::makeFuzz(2)) ),
- "section" => wikiFuzz::makeFuzz(2),
- "preload" => wikiFuzz::makeFuzz(2),
+ "su", "sv", "ta", "te", "th", "tr", "tt", "ty", "tyv", "udm",
+ "ug", "uk", "ur", "utf8", "vec", "vi", "wa", "xal", "yi", "za",
+ "zh", "zh-cn", "zh-hk", "zh-sg", "zh-tw", "zh-tw" ) ),
+ "returnto" => wikiFuzz::makeFuzz( 2 ),
+ "feed" => wikiFuzz::chooseInput( array( "atom", "rss", wikiFuzz::makeFuzz( 2 ) ) ),
+ "rcid" => wikiFuzz::makeFuzz( 2 ),
+ "action" => wikiFuzz::chooseInput( array( "view", "raw", "render", wikiFuzz::makeFuzz( 2 ), "markpatrolled" ) ),
+ "printable" => wikiFuzz::makeFuzz( 2 ),
+ "oldid" => wikiFuzz::makeFuzz( 2 ),
+ "redirect" => wikiFuzz::makeFuzz( 2 ),
+ "diff" => wikiFuzz::makeFuzz( 2 ),
+ "search" => wikiFuzz::makeFuzz( 2 ),
+ "rdfrom" => wikiFuzz::makeFuzz( 2 ), // things from Article.php from here on:
+ "token" => wikiFuzz::makeFuzz( 2 ),
+ "tbid" => wikiFuzz::makeFuzz( 2 ),
+ "action" => wikiFuzz::chooseInput( array( "purge", wikiFuzz::makeFuzz( 2 ) ) ),
+ "wpReason" => wikiFuzz::makeFuzz( 2 ),
+ "wpEditToken" => wikiFuzz::makeFuzz( 2 ),
+ "from" => wikiFuzz::makeFuzz( 2 ),
+ "bot" => wikiFuzz::makeFuzz( 2 ),
+ "summary" => wikiFuzz::makeFuzz( 2 ),
+ "direction" => wikiFuzz::chooseInput( array( "next", "prev", wikiFuzz::makeFuzz( 2 ) ) ),
+ "section" => wikiFuzz::makeFuzz( 2 ),
+ "preload" => wikiFuzz::makeFuzz( 2 ),
);
// Tidy does not know how to valid atom or rss, so exclude from testing for the time being.
- if ($this->params["feed"] == "atom") { unset($this->params["feed"]); }
- else if ($this->params["feed"] == "rss") { unset($this->params["feed"]); }
+ if ( $this->params["feed"] == "atom" ) { unset( $this->params["feed"] ); }
+ else if ( $this->params["feed"] == "rss" ) { unset( $this->params["feed"] ); }
// Raw pages cannot really be validated
- if ($this->params["action"] == "raw") unset($this->params["action"]);
+ if ( $this->params["action"] == "raw" ) unset( $this->params["action"] );
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(6) == 0) unset($this->params["rcid"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["diff"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["rdfrom"]);
- if (wikiFuzz::randnum(3) == 0) unset($this->params["oldid"]);
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["rcid"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["diff"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["rdfrom"] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["oldid"] );
// usually don't want action == purge.
- if (wikiFuzz::randnum(6) > 1) unset($this->params["action"]);
+ if ( wikiFuzz::randnum( 6 ) > 1 ) unset( $this->params["action"] );
}
}
// only really has one parameter
$this->params = array (
- "ot" => wikiFuzz::chooseInput( array("php", "html", wikiFuzz::makeFuzz(2)) )
+ "ot" => wikiFuzz::chooseInput( array( "php", "html", wikiFuzz::makeFuzz( 2 ) ) )
);
}
}
$this->pagePath = "index.php?title=Special:Newpages";
$this->params = array (
- "namespace" => wikiFuzz::chooseInput( range(-1, 15) ),
- "feed" => wikiFuzz::chooseInput( array("atom", "rss", wikiFuzz::makeFuzz(2)) ),
- 'limit' => wikiFuzz::chooseInput( array("-1", "0", "-------'------0", "+1", "8134", wikiFuzz::makeFuzz(2)) ),
- 'offset' => wikiFuzz::chooseInput( array("-1", "0", "------'-------0", "+1", "9823412312312412435", wikiFuzz::makeFuzz(2)) )
+ "namespace" => wikiFuzz::chooseInput( range( -1, 15 ) ),
+ "feed" => wikiFuzz::chooseInput( array( "atom", "rss", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'limit' => wikiFuzz::chooseInput( array( "-1", "0", "-------'------0", "+1", "8134", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'offset' => wikiFuzz::chooseInput( array( "-1", "0", "------'-------0", "+1", "9823412312312412435", wikiFuzz::makeFuzz( 2 ) ) )
);
// Tidy does not know how to valid atom or rss, so exclude from testing for the time being.
- if ($this->params["feed"] == "atom") { unset($this->params["feed"]); }
- else if ($this->params["feed"] == "rss") { unset($this->params["feed"]); }
+ if ( $this->params["feed"] == "atom" ) { unset( $this->params["feed"] ); }
+ else if ( $this->params["feed"] == "rss" ) { unset( $this->params["feed"] ); }
}
}
$this->pagePath = "redirect.php";
$this->params = array (
- "wpDropdown" => wikiFuzz::makeFuzz(2)
+ "wpDropdown" => wikiFuzz::makeFuzz( 2 )
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpDropdown"]);
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpDropdown"] );
}
}
class confirmEmail extends pageTest {
function __construct() {
// sometimes we send a bogus confirmation code, and sometimes we don't.
- $this->pagePath = "index.php?title=Special:Confirmemail" . wikiFuzz::chooseInput( array("", "/" . wikiFuzz::makeTitleSafe(wikiFuzz::makeFuzz(1)) ) );
+ $this->pagePath = "index.php?title=Special:Confirmemail" . wikiFuzz::chooseInput( array( "", "/" . wikiFuzz::makeTitleSafe( wikiFuzz::makeFuzz( 1 ) ) ) );
$this->params = array (
- "token" => wikiFuzz::makeFuzz(2)
+ "token" => wikiFuzz::makeFuzz( 2 )
);
}
}
$this->pagePath = "index.php?title=Special:Watchlist";
$this->params = array (
- "remove" => wikiFuzz::chooseInput( array("Remove checked items from watchlist", wikiFuzz::makeFuzz(2))),
- 'days' => wikiFuzz::chooseInput( array(0, -1, -230, "--", 3, 9, wikiFuzz::makeFuzz(2)) ),
- 'hideOwn' => wikiFuzz::chooseInput( array("", "0", "1", wikiFuzz::makeFuzz(2)) ),
- 'hideBots' => wikiFuzz::chooseInput( array("", "0", "1", wikiFuzz::makeFuzz(2)) ),
- 'namespace'=> wikiFuzz::chooseInput( array("", "0", "1", wikiFuzz::makeFuzz(2)) ),
- 'action' => wikiFuzz::chooseInput( array("submit", "clear", wikiFuzz::makeFuzz(2)) ),
- 'id[]' => wikiFuzz::makeFuzz(2),
- 'edit' => wikiFuzz::makeFuzz(2),
- 'token' => wikiFuzz::chooseInput( array("", "1243213", wikiFuzz::makeFuzz(2)) )
+ "remove" => wikiFuzz::chooseInput( array( "Remove checked items from watchlist", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'days' => wikiFuzz::chooseInput( array( 0, -1, -230, "--", 3, 9, wikiFuzz::makeFuzz( 2 ) ) ),
+ 'hideOwn' => wikiFuzz::chooseInput( array( "", "0", "1", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'hideBots' => wikiFuzz::chooseInput( array( "", "0", "1", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'namespace' => wikiFuzz::chooseInput( array( "", "0", "1", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'action' => wikiFuzz::chooseInput( array( "submit", "clear", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'id[]' => wikiFuzz::makeFuzz( 2 ),
+ 'edit' => wikiFuzz::makeFuzz( 2 ),
+ 'token' => wikiFuzz::chooseInput( array( "", "1243213", wikiFuzz::makeFuzz( 2 ) ) )
);
// sometimes we specifiy "reset", and sometimes we don't.
- if (wikiFuzz::randnum(3) == 0) $this->params["reset"] = wikiFuzz::chooseInput( array("", "0", "1", wikiFuzz::makeFuzz(2)) );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) $this->params["reset"] = wikiFuzz::chooseInput( array( "", "0", "1", wikiFuzz::makeFuzz( 2 ) ) );
}
}
$this->params = array ( );
// sometimes we specify "ip", and sometimes we don't.
- if (wikiFuzz::randnum(1) == 0) {
- $this->params["ip"] = wikiFuzz::chooseInput( array("10.12.41.213", wikiFuzz::randnum(-10,8134), wikiFuzz::makeFuzz(2)) );
+ if ( wikiFuzz::randnum( 1 ) == 0 ) {
+ $this->params["ip"] = wikiFuzz::chooseInput( array( "10.12.41.213", wikiFuzz::randnum( -10, 8134 ), wikiFuzz::makeFuzz( 2 ) ) );
}
}
}
$this->pagePath = "index.php?title=Special:Movepage";
$this->params = array (
- "action" => wikiFuzz::chooseInput( array("success", "submit", "", wikiFuzz::makeFuzz(2)) ),
- 'wpEditToken' => wikiFuzz::chooseInput( array('', 0, 34987987, wikiFuzz::makeFuzz(2)) ),
- 'target' => wikiFuzz::chooseInput( array("x", wikiFuzz::makeTitleSafe(wikiFuzz::makeFuzz(2)) ) ),
- 'wpOldTitle' => wikiFuzz::chooseInput( array("z", wikiFuzz::makeTitleSafe(wikiFuzz::makeFuzz(2)), wikiFuzz::makeFuzz(2) ) ),
- 'wpNewTitle' => wikiFuzz::chooseInput( array("y", wikiFuzz::makeTitleSafe(wikiFuzz::makeFuzz(2)), wikiFuzz::makeFuzz(2) ) ),
- 'wpReason' => wikiFuzz::chooseInput( array(wikiFuzz::makeFuzz(2)) ),
- 'wpMovetalk' => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- 'wpDeleteAndMove' => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- 'wpConfirm' => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- 'talkmoved' => wikiFuzz::chooseInput( array("1", wikiFuzz::makeFuzz(2), "articleexists", 'notalkpage') ),
- 'oldtitle' => wikiFuzz::makeFuzz(2),
- 'newtitle' => wikiFuzz::makeFuzz(2),
- 'wpMovetalk' => wikiFuzz::chooseInput( array("1", "0", wikiFuzz::makeFuzz(2)) )
+ "action" => wikiFuzz::chooseInput( array( "success", "submit", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpEditToken' => wikiFuzz::chooseInput( array( '', 0, 34987987, wikiFuzz::makeFuzz( 2 ) ) ),
+ 'target' => wikiFuzz::chooseInput( array( "x", wikiFuzz::makeTitleSafe( wikiFuzz::makeFuzz( 2 ) ) ) ),
+ 'wpOldTitle' => wikiFuzz::chooseInput( array( "z", wikiFuzz::makeTitleSafe( wikiFuzz::makeFuzz( 2 ) ), wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpNewTitle' => wikiFuzz::chooseInput( array( "y", wikiFuzz::makeTitleSafe( wikiFuzz::makeFuzz( 2 ) ), wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpReason' => wikiFuzz::chooseInput( array( wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpMovetalk' => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpDeleteAndMove' => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpConfirm' => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'talkmoved' => wikiFuzz::chooseInput( array( "1", wikiFuzz::makeFuzz( 2 ), "articleexists", 'notalkpage' ) ),
+ 'oldtitle' => wikiFuzz::makeFuzz( 2 ),
+ 'newtitle' => wikiFuzz::makeFuzz( 2 ),
+ 'wpMovetalk' => wikiFuzz::chooseInput( array( "1", "0", wikiFuzz::makeFuzz( 2 ) ) )
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(2) == 0) unset($this->params["wpEditToken"]);
- if (wikiFuzz::randnum(3) == 0) unset($this->params["target"]);
- if (wikiFuzz::randnum(3) == 0) unset($this->params["wpNewTitle"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpReason"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpOldTitle"]);
+ if ( wikiFuzz::randnum( 2 ) == 0 ) unset( $this->params["wpEditToken"] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["target"] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["wpNewTitle"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpReason"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpOldTitle"] );
}
}
$this->pagePath = "index.php?title=Special:Undelete";
$this->params = array (
- "action" => wikiFuzz::chooseInput( array("submit", "", wikiFuzz::makeFuzz(2)) ),
- 'wpEditToken' => wikiFuzz::chooseInput( array('', 0, 34987987, wikiFuzz::makeFuzz(2)) ),
- 'target' => wikiFuzz::chooseInput( array("x", wikiFuzz::makeTitleSafe(wikiFuzz::makeFuzz(2)) ) ),
- 'timestamp' => wikiFuzz::chooseInput( array("125223", wikiFuzz::makeFuzz(2) ) ),
- 'file' => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- 'restore' => wikiFuzz::chooseInput( array("0", "1", wikiFuzz::makeFuzz(2)) ),
- 'preview' => wikiFuzz::chooseInput( array("0", "1", wikiFuzz::makeFuzz(2)) ),
- 'wpComment' => wikiFuzz::makeFuzz(2)
+ "action" => wikiFuzz::chooseInput( array( "submit", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpEditToken' => wikiFuzz::chooseInput( array( '', 0, 34987987, wikiFuzz::makeFuzz( 2 ) ) ),
+ 'target' => wikiFuzz::chooseInput( array( "x", wikiFuzz::makeTitleSafe( wikiFuzz::makeFuzz( 2 ) ) ) ),
+ 'timestamp' => wikiFuzz::chooseInput( array( "125223", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'file' => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'restore' => wikiFuzz::chooseInput( array( "0", "1", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'preview' => wikiFuzz::chooseInput( array( "0", "1", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpComment' => wikiFuzz::makeFuzz( 2 )
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(2) == 0) unset($this->params["wpEditToken"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["target"]);
- if (wikiFuzz::randnum(1) == 0) unset($this->params["restore"]);
- if (wikiFuzz::randnum(1) == 0) unset($this->params["preview"]);
+ if ( wikiFuzz::randnum( 2 ) == 0 ) unset( $this->params["wpEditToken"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["target"] );
+ if ( wikiFuzz::randnum( 1 ) == 0 ) unset( $this->params["restore"] );
+ if ( wikiFuzz::randnum( 1 ) == 0 ) unset( $this->params["preview"] );
}
}
$this->pagePath = "index.php?title=Special:Unlockdb";
$this->params = array (
- "action" => wikiFuzz::chooseInput( array("submit", "success", "", wikiFuzz::makeFuzz(2)) ),
- 'wpEditToken' => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
- 'wpLockConfirm' => wikiFuzz::chooseInput( array("0", "1", wikiFuzz::makeFuzz(2)) )
+ "action" => wikiFuzz::chooseInput( array( "submit", "success", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpEditToken' => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpLockConfirm' => wikiFuzz::chooseInput( array( "0", "1", wikiFuzz::makeFuzz( 2 ) ) )
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpEditToken"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["action"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpLockConfirm"]);
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpEditToken"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["action"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpLockConfirm"] );
}
}
$this->pagePath = "index.php?title=Special:Lockdb";
$this->params = array (
- "action" => wikiFuzz::chooseInput( array("submit", "success", "", wikiFuzz::makeFuzz(2)) ),
- 'wpEditToken' => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
- 'wpLockReason' => wikiFuzz::makeFuzz(2),
- 'wpLockConfirm'=> wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) )
+ "action" => wikiFuzz::chooseInput( array( "submit", "success", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpEditToken' => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpLockReason' => wikiFuzz::makeFuzz( 2 ),
+ 'wpLockConfirm' => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) )
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpEditToken"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["action"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpLockConfirm"]);
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpEditToken"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["action"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpLockConfirm"] );
}
}
$this->pagePath = "index.php?title=Special:Userrights";
$this->params = array (
- 'wpEditToken' => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
- 'user-editname' => wikiFuzz::chooseInput( array("Nickj2", "Nickj2\n<xyz>", wikiFuzz::makeFuzz(2)) ),
- 'ssearchuser' => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- 'saveusergroups'=> wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)), "Save User Groups"),
- 'member[]' => wikiFuzz::chooseInput( array("0", "bot", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- "available[]" => wikiFuzz::chooseInput( array("0", "sysop", "bureaucrat", "1", "++--34234", wikiFuzz::makeFuzz(2)) )
+ 'wpEditToken' => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'user-editname' => wikiFuzz::chooseInput( array( "Nickj2", "Nickj2\n<xyz>", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'ssearchuser' => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'saveusergroups' => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ), "Save User Groups" ),
+ 'member[]' => wikiFuzz::chooseInput( array( "0", "bot", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "available[]" => wikiFuzz::chooseInput( array( "0", "sysop", "bureaucrat", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) )
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(3) == 0) unset($this->params['ssearchuser']);
- if (wikiFuzz::randnum(3) == 0) unset($this->params['saveusergroups']);
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params['ssearchuser'] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params['saveusergroups'] );
}
}
$this->params = array (
"action" => "protect",
- 'wpEditToken' => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
- "mwProtect-level-edit" => wikiFuzz::chooseInput( array('', 'autoconfirmed', 'sysop', wikifuzz::makeFuzz(2)) ),
- "mwProtect-level-move" => wikiFuzz::chooseInput( array('', 'autoconfirmed', 'sysop', wikifuzz::makeFuzz(2)) ),
- "mwProtectUnchained" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- 'mwProtect-reason' => wikiFuzz::chooseInput( array("because it was there", wikifuzz::makeFuzz(2)) )
+ 'wpEditToken' => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ "mwProtect-level-edit" => wikiFuzz::chooseInput( array( '', 'autoconfirmed', 'sysop', wikifuzz::makeFuzz( 2 ) ) ),
+ "mwProtect-level-move" => wikiFuzz::chooseInput( array( '', 'autoconfirmed', 'sysop', wikifuzz::makeFuzz( 2 ) ) ),
+ "mwProtectUnchained" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'mwProtect-reason' => wikiFuzz::chooseInput( array( "because it was there", wikifuzz::makeFuzz( 2 ) ) )
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(3) == 0) unset($this->params["mwProtectUnchained"]);
- if (wikiFuzz::randnum(3) == 0) unset($this->params['mwProtect-reason']);
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["mwProtectUnchained"] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params['mwProtect-reason'] );
}
}
$this->pagePath = "index.php?title=Special:Blockip";
$this->params = array (
- "action" => wikiFuzz::chooseInput( array("submit", "", wikiFuzz::makeFuzz(2)) ),
- 'wpEditToken' => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
- "wpBlockAddress" => wikiFuzz::chooseInput( array("20398702394", "", "Nickj2", wikiFuzz::makeFuzz(2),
+ "action" => wikiFuzz::chooseInput( array( "submit", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ 'wpEditToken' => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ "wpBlockAddress" => wikiFuzz::chooseInput( array( "20398702394", "", "Nickj2", wikiFuzz::makeFuzz( 2 ),
// something like an IP address, sometimes invalid:
- ( wikiFuzz::randnum(300,-20) . "." . wikiFuzz::randnum(300,-20) . "."
- . wikiFuzz::randnum(300,-20) . "." .wikiFuzz::randnum(300,-20) ) ) ),
- "ip" => wikiFuzz::chooseInput( array("20398702394", "", "Nickj2", wikiFuzz::makeFuzz(2),
+ ( wikiFuzz::randnum( 300, -20 ) . "." . wikiFuzz::randnum( 300, -20 ) . "."
+ . wikiFuzz::randnum( 300, -20 ) . "." . wikiFuzz::randnum( 300, -20 ) ) ) ),
+ "ip" => wikiFuzz::chooseInput( array( "20398702394", "", "Nickj2", wikiFuzz::makeFuzz( 2 ),
// something like an IP address, sometimes invalid:
- ( wikiFuzz::randnum(300,-20) . "." . wikiFuzz::randnum(300,-20) . "."
- . wikiFuzz::randnum(300,-20) . "." .wikiFuzz::randnum(300,-20) ) ) ),
- "wpBlockOther" => wikiFuzz::chooseInput( array('', 'Nickj2', wikifuzz::makeFuzz(2)) ),
- "wpBlockExpiry" => wikiFuzz::chooseInput( array("other", "2 hours", "1 day", "3 days", "1 week", "2 weeks",
- "1 month", "3 months", "6 months", "1 year", "infinite", wikiFuzz::makeFuzz(2)) ),
- "wpBlockReason" => wikiFuzz::chooseInput( array("because it was there", wikifuzz::makeFuzz(2)) ),
- "wpAnonOnly" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- "wpCreateAccount" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- "wpBlock" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) )
+ ( wikiFuzz::randnum( 300, -20 ) . "." . wikiFuzz::randnum( 300, -20 ) . "."
+ . wikiFuzz::randnum( 300, -20 ) . "." . wikiFuzz::randnum( 300, -20 ) ) ) ),
+ "wpBlockOther" => wikiFuzz::chooseInput( array( '', 'Nickj2', wikifuzz::makeFuzz( 2 ) ) ),
+ "wpBlockExpiry" => wikiFuzz::chooseInput( array( "other", "2 hours", "1 day", "3 days", "1 week", "2 weeks",
+ "1 month", "3 months", "6 months", "1 year", "infinite", wikiFuzz::makeFuzz( 2 ) ) ),
+ "wpBlockReason" => wikiFuzz::chooseInput( array( "because it was there", wikifuzz::makeFuzz( 2 ) ) ),
+ "wpAnonOnly" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "wpCreateAccount" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "wpBlock" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) )
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpBlockOther"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpBlockExpiry"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpBlockReason"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpAnonOnly"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpCreateAccount"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["wpBlockAddress"]);
- if (wikiFuzz::randnum(4) == 0) unset($this->params["ip"]);
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpBlockOther"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpBlockExpiry"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpBlockReason"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpAnonOnly"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpCreateAccount"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["wpBlockAddress"] );
+ if ( wikiFuzz::randnum( 4 ) == 0 ) unset( $this->params["ip"] );
}
}
$this->pagePath = "index.php?title=Image:Small-email.png";
$this->params = array (
- "image" => wikiFuzz::chooseInput( array("Small-email.png", wikifuzz::makeFuzz(2)) ),
- "wpReason" => wikifuzz::makeFuzz(2),
- "oldimage" => wikiFuzz::chooseInput( array("Small-email.png", wikifuzz::makeFuzz(2)) ),
- "wpEditToken" => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
+ "image" => wikiFuzz::chooseInput( array( "Small-email.png", wikifuzz::makeFuzz( 2 ) ) ),
+ "wpReason" => wikifuzz::makeFuzz( 2 ),
+ "oldimage" => wikiFuzz::chooseInput( array( "Small-email.png", wikifuzz::makeFuzz( 2 ) ) ),
+ "wpEditToken" => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(6) == 0) unset($this->params["image"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpReason"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["oldimage"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpEditToken"]);
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["image"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpReason"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["oldimage"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpEditToken"] );
}
}
$this->pagePath = "index.php?title=Main_Page&action=delete";
$this->params = array (
- "wpEditToken" => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
- "wpReason" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- "wpConfirm" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
+ "wpEditToken" => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ "wpReason" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "wpConfirm" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(5) == 0) unset($this->params["wpReason"]);
- if (wikiFuzz::randnum(5) == 0) unset($this->params["wpEditToken"]);
- if (wikiFuzz::randnum(5) == 0) unset($this->params["wpConfirm"]);
+ if ( wikiFuzz::randnum( 5 ) == 0 ) unset( $this->params["wpReason"] );
+ if ( wikiFuzz::randnum( 5 ) == 0 ) unset( $this->params["wpEditToken"] );
+ if ( wikiFuzz::randnum( 5 ) == 0 ) unset( $this->params["wpConfirm"] );
}
}
$this->pagePath = "index.php?title=Special:Revisiondelete";
$this->params = array (
- "target" => wikiFuzz::chooseInput( array("Main Page", wikifuzz::makeFuzz(2)) ),
- "oldid" => wikifuzz::makeFuzz(2),
- "oldid[]" => wikifuzz::makeFuzz(2),
- "wpReason" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- "revdelete-hide-text" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- "revdelete-hide-comment" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- "revdelete-hide-user" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- "revdelete-hide-restricted" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
+ "target" => wikiFuzz::chooseInput( array( "Main Page", wikifuzz::makeFuzz( 2 ) ) ),
+ "oldid" => wikifuzz::makeFuzz( 2 ),
+ "oldid[]" => wikifuzz::makeFuzz( 2 ),
+ "wpReason" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "revdelete-hide-text" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "revdelete-hide-comment" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "revdelete-hide-user" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "revdelete-hide-restricted" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(3) == 0) unset($this->params["target"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["oldid"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["oldid[]"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["wpReason"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["revdelete-hide-text"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["revdelete-hide-comment"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["revdelete-hide-user"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["revdelete-hide-restricted"]);
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["target"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["oldid"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["oldid[]"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["wpReason"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["revdelete-hide-text"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["revdelete-hide-comment"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["revdelete-hide-user"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["revdelete-hide-restricted"] );
}
}
$this->params = array (
"action" => "submit",
- "source" => wikiFuzz::chooseInput( array("upload", "interwiki", wikifuzz::makeFuzz(2)) ),
- "MAX_FILE_SIZE" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikifuzz::makeFuzz(2)) ),
- "xmlimport" => wikiFuzz::chooseInput( array("/var/www/hosts/mediawiki/wiki/AdminSettings.php", "1", "++--34234", wikiFuzz::makeFuzz(2)) ),
- "namespace" => wikiFuzz::chooseInput( array(wikiFuzz::randnum(30,-6), wikiFuzz::makeFuzz(2)) ),
- "interwiki" => wikiFuzz::makeFuzz(2),
- "interwikiHistory" => wikiFuzz::makeFuzz(2),
- "frompage" => wikiFuzz::makeFuzz(2),
+ "source" => wikiFuzz::chooseInput( array( "upload", "interwiki", wikifuzz::makeFuzz( 2 ) ) ),
+ "MAX_FILE_SIZE" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikifuzz::makeFuzz( 2 ) ) ),
+ "xmlimport" => wikiFuzz::chooseInput( array( "/var/www/hosts/mediawiki/wiki/AdminSettings.php", "1", "++--34234", wikiFuzz::makeFuzz( 2 ) ) ),
+ "namespace" => wikiFuzz::chooseInput( array( wikiFuzz::randnum( 30, -6 ), wikiFuzz::makeFuzz( 2 ) ) ),
+ "interwiki" => wikiFuzz::makeFuzz( 2 ),
+ "interwikiHistory" => wikiFuzz::makeFuzz( 2 ),
+ "frompage" => wikiFuzz::makeFuzz( 2 ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(6) == 0) unset($this->params["action"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["source"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["MAX_FILE_SIZE"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["xmlimport"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["interwiki"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["interwikiHistory"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["frompage"]);
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["action"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["source"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["MAX_FILE_SIZE"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["xmlimport"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["interwiki"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["interwikiHistory"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["frompage"] );
// Note: Need to do a file upload to fully test this Special page.
}
$this->pagePath = "thumb.php";
$this->params = array (
- "f" => wikiFuzz::chooseInput( array("..", "\\", "small-email.png", wikifuzz::makeFuzz(2)) ),
- "w" => wikiFuzz::chooseInput( array("80", wikiFuzz::randnum(6000,-200), wikifuzz::makeFuzz(2)) ),
- "r" => wikiFuzz::chooseInput( array("0", wikifuzz::makeFuzz(2)) ),
+ "f" => wikiFuzz::chooseInput( array( "..", "\\", "small-email.png", wikifuzz::makeFuzz( 2 ) ) ),
+ "w" => wikiFuzz::chooseInput( array( "80", wikiFuzz::randnum( 6000, -200 ), wikifuzz::makeFuzz( 2 ) ) ),
+ "r" => wikiFuzz::chooseInput( array( "0", wikifuzz::makeFuzz( 2 ) ) ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(6) == 0) unset($this->params["f"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["w"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["r"]);
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["f"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["w"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["r"] );
}
}
$this->pagePath = "trackback.php";
$this->params = array (
- "url" => wikifuzz::makeFuzz(2),
- "blog_name" => wikiFuzz::chooseInput( array("80", wikiFuzz::randnum(6000,-200), wikifuzz::makeFuzz(2)) ),
- "article" => wikiFuzz::chooseInput( array("Main Page", wikifuzz::makeFuzz(2)) ),
- "title" => wikiFuzz::chooseInput( array("Main Page", wikifuzz::makeFuzz(2)) ),
- "excerpt" => wikifuzz::makeFuzz(2),
+ "url" => wikifuzz::makeFuzz( 2 ),
+ "blog_name" => wikiFuzz::chooseInput( array( "80", wikiFuzz::randnum( 6000, -200 ), wikifuzz::makeFuzz( 2 ) ) ),
+ "article" => wikiFuzz::chooseInput( array( "Main Page", wikifuzz::makeFuzz( 2 ) ) ),
+ "title" => wikiFuzz::chooseInput( array( "Main Page", wikifuzz::makeFuzz( 2 ) ) ),
+ "excerpt" => wikifuzz::makeFuzz( 2 ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(3) == 0) unset($this->params["title"]);
- if (wikiFuzz::randnum(3) == 0) unset($this->params["excerpt"]);
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["title"] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["excerpt"] );
// page does not produce HTML.
- $this->tidyValidate = false;
+ $this->tidyValidate = false;
}
}
$this->pagePath = "profileinfo.php";
$this->params = array (
- "expand" => wikifuzz::makeFuzz(2),
- "sort" => wikiFuzz::chooseInput( array("time", "count", "name", wikifuzz::makeFuzz(2)) ),
- "filter" => wikiFuzz::chooseInput( array("Main Page", wikifuzz::makeFuzz(2)) ),
+ "expand" => wikifuzz::makeFuzz( 2 ),
+ "sort" => wikiFuzz::chooseInput( array( "time", "count", "name", wikifuzz::makeFuzz( 2 ) ) ),
+ "filter" => wikiFuzz::chooseInput( array( "Main Page", wikifuzz::makeFuzz( 2 ) ) ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(3) == 0) unset($this->params["sort"]);
- if (wikiFuzz::randnum(3) == 0) unset($this->params["filter"]);
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["sort"] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["filter"] );
}
}
$this->pagePath = "index.php?title=Special:Cite";
$this->params = array (
- "page" => wikiFuzz::chooseInput( array("\" onmouseover=\"alert(1);\"", "Main Page", wikifuzz::makeFuzz(2)) ),
- "id" => wikiFuzz::chooseInput( array("-1", "0", "------'-------0", "+1", "-9823412312312412435", wikiFuzz::makeFuzz(2)) ),
+ "page" => wikiFuzz::chooseInput( array( "\" onmouseover=\"alert(1);\"", "Main Page", wikifuzz::makeFuzz( 2 ) ) ),
+ "id" => wikiFuzz::chooseInput( array( "-1", "0", "------'-------0", "+1", "-9823412312312412435", wikiFuzz::makeFuzz( 2 ) ) ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(6) == 0) unset($this->params["page"]);
- if (wikiFuzz::randnum(6) == 0) unset($this->params["id"]);
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["page"] );
+ if ( wikiFuzz::randnum( 6 ) == 0 ) unset( $this->params["id"] );
}
}
$this->pagePath = "index.php?title=Special:Filepath";
$this->params = array (
- "file" => wikiFuzz::chooseInput( array("Small-email.png", "Small-email.png" . wikifuzz::makeFuzz(1), wikiFuzz::makeFuzz(2)) ),
+ "file" => wikiFuzz::chooseInput( array( "Small-email.png", "Small-email.png" . wikifuzz::makeFuzz( 1 ), wikiFuzz::makeFuzz( 2 ) ) ),
);
}
}
$this->pagePath = "index.php?title=Special:Makebot";
$this->params = array (
- "username" => wikiFuzz::chooseInput( array("Nickj2", "192.168.0.2", wikifuzz::makeFuzz(1) ) ),
- "dosearch" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikifuzz::makeFuzz(2)) ),
- "grant" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikifuzz::makeFuzz(2)) ),
- "comment" => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
- "token" => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
+ "username" => wikiFuzz::chooseInput( array( "Nickj2", "192.168.0.2", wikifuzz::makeFuzz( 1 ) ) ),
+ "dosearch" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikifuzz::makeFuzz( 2 ) ) ),
+ "grant" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikifuzz::makeFuzz( 2 ) ) ),
+ "comment" => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ "token" => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(2) == 0) unset($this->params["dosearch"]);
- if (wikiFuzz::randnum(2) == 0) unset($this->params["grant"]);
- if (wikiFuzz::randnum(5) == 0) unset($this->params["token"]);
+ if ( wikiFuzz::randnum( 2 ) == 0 ) unset( $this->params["dosearch"] );
+ if ( wikiFuzz::randnum( 2 ) == 0 ) unset( $this->params["grant"] );
+ if ( wikiFuzz::randnum( 5 ) == 0 ) unset( $this->params["token"] );
}
}
$this->pagePath = "index.php?title=Special:Makesysop";
$this->params = array (
- "wpMakesysopUser" => wikiFuzz::chooseInput( array("Nickj2", "192.168.0.2", wikifuzz::makeFuzz(1) ) ),
- "action" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikifuzz::makeFuzz(2)) ),
- "wpMakesysopSubmit" => wikiFuzz::chooseInput( array("0", "1", "++--34234", wikifuzz::makeFuzz(2)) ),
- "wpEditToken" => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
- "wpSetBureaucrat" => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
+ "wpMakesysopUser" => wikiFuzz::chooseInput( array( "Nickj2", "192.168.0.2", wikifuzz::makeFuzz( 1 ) ) ),
+ "action" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikifuzz::makeFuzz( 2 ) ) ),
+ "wpMakesysopSubmit" => wikiFuzz::chooseInput( array( "0", "1", "++--34234", wikifuzz::makeFuzz( 2 ) ) ),
+ "wpEditToken" => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
+ "wpSetBureaucrat" => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(3) == 0) unset($this->params["wpMakesysopSubmit"]);
- if (wikiFuzz::randnum(3) == 0) unset($this->params["wpEditToken"]);
- if (wikiFuzz::randnum(3) == 0) unset($this->params["wpSetBureaucrat"]);
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["wpMakesysopSubmit"] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["wpEditToken"] );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) unset( $this->params["wpSetBureaucrat"] );
}
}
$this->pagePath = "index.php?title=Special:Renameuser";
$this->params = array (
- "oldusername" => wikiFuzz::chooseInput( array("Nickj2", "192.168.0.2", wikifuzz::makeFuzz(1) ) ),
- "newusername" => wikiFuzz::chooseInput( array("Nickj2", "192.168.0.2", wikifuzz::makeFuzz(1) ) ),
- "token" => wikiFuzz::chooseInput( array("20398702394", "", wikiFuzz::makeFuzz(2)) ),
+ "oldusername" => wikiFuzz::chooseInput( array( "Nickj2", "192.168.0.2", wikifuzz::makeFuzz( 1 ) ) ),
+ "newusername" => wikiFuzz::chooseInput( array( "Nickj2", "192.168.0.2", wikifuzz::makeFuzz( 1 ) ) ),
+ "token" => wikiFuzz::chooseInput( array( "20398702394", "", wikiFuzz::makeFuzz( 2 ) ) ),
);
}
}
$this->pagePath = "index.php?title=Special%3ALinksearch";
$this->params = array (
- "target" => wikifuzz::makeFuzz(2),
+ "target" => wikifuzz::makeFuzz( 2 ),
);
// sometimes we don't want to specify certain parameters.
- if (wikiFuzz::randnum(10) == 0) unset($this->params["target"]);
+ if ( wikiFuzz::randnum( 10 ) == 0 ) unset( $this->params["target"] );
}
}
$this->pagePath = "index.php?title=Special:CategoryTree";
$this->params = array (
- "target" => wikifuzz::makeFuzz(2),
- "from" => wikifuzz::makeFuzz(2),
- "until" => wikifuzz::makeFuzz(2),
- "showas" => wikifuzz::makeFuzz(2),
- "mode" => wikiFuzz::chooseInput( array("pages", "categories", "all", wikifuzz::makeFuzz(2)) ),
+ "target" => wikifuzz::makeFuzz( 2 ),
+ "from" => wikifuzz::makeFuzz( 2 ),
+ "until" => wikifuzz::makeFuzz( 2 ),
+ "showas" => wikifuzz::makeFuzz( 2 ),
+ "mode" => wikiFuzz::chooseInput( array( "pages", "categories", "all", wikifuzz::makeFuzz( 2 ) ) ),
);
// sometimes we do want to specify certain parameters.
- if (wikiFuzz::randnum(5) == 0) $this->params["notree"] = wikiFuzz::chooseInput( array("1", 0, "", wikiFuzz::makeFuzz(2)) );
+ if ( wikiFuzz::randnum( 5 ) == 0 ) $this->params["notree"] = wikiFuzz::chooseInput( array( "1", 0, "", wikiFuzz::makeFuzz( 2 ) ) );
}
}
);
// values for different formats usually start with either letters or numbers.
- switch ($format) {
+ switch ( $format ) {
case 'Name' : $value = "A"; break;
case 'InChI' :
case 'SMILES' :
}
// and then we append the fuzz input.
- $this->params = array ($format => $value . wikifuzz::makeFuzz(2) );
+ $this->params = array ( $format => $value . wikifuzz::makeFuzz( 2 ) );
}
}
// API login mode.
private static function loginMode() {
- $arr = array ( "lgname" => wikifuzz::makeFuzz(2),
- "lgpassword" => wikifuzz::makeFuzz(2),
+ $arr = array ( "lgname" => wikifuzz::makeFuzz( 2 ),
+ "lgpassword" => wikifuzz::makeFuzz( 2 ),
);
// sometimes we want to specify the extra "lgdomain" parameter.
- if (wikiFuzz::randnum(3) == 0) {
- $arr["lgdomain"] = wikiFuzz::chooseInput( array("1", 0, "", wikiFuzz::makeFuzz(2)) );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) {
+ $arr["lgdomain"] = wikiFuzz::chooseInput( array( "1", 0, "", wikiFuzz::makeFuzz( 2 ) ) );
}
return $arr;
// API OpenSearch mode.
private static function opensearchMode() {
- return array ("search" => wikifuzz::makeFuzz(2));
+ return array ( "search" => wikifuzz::makeFuzz( 2 ) );
}
// API watchlist feed mode.
private static function feedwatchlistMode() {
// FIXME: add "wikifuzz::makeFuzz(2)" as possible value below?
- return array ("feedformat" => wikiFuzz::chooseInput( array("rss", "atom") ) );
+ return array ( "feedformat" => wikiFuzz::chooseInput( array( "rss", "atom" ) ) );
}
// API query mode.
// Suspect this will stuff up the tests more, but need to check.
$params = array (
// FIXME: More titles.
- "titles" => wikiFuzz::chooseInput( array("Main Page")),
+ "titles" => wikiFuzz::chooseInput( array( "Main Page" ) ),
// FIXME: More pageids.
"pageids" => 1,
- "prop" => wikiFuzz::chooseInput( array("info", "revisions", "watchlist")),
- "list" => wikiFuzz::chooseInput( array("allpages", "logevents", "watchlist", "usercontribs", "recentchanges", "backlinks", "embeddedin", "imagelinks") ),
- "meta" => wikiFuzz::chooseInput( array("siteinfo")),
- "generator" => wikiFuzz::chooseInput( array("allpages", "logevents", "watchlist", "info", "revisions") ),
- "siprop" => wikiFuzz::chooseInput( array("general", "namespaces", "general|namespaces") ),
+ "prop" => wikiFuzz::chooseInput( array( "info", "revisions", "watchlist" ) ),
+ "list" => wikiFuzz::chooseInput( array( "allpages", "logevents", "watchlist", "usercontribs", "recentchanges", "backlinks", "embeddedin", "imagelinks" ) ),
+ "meta" => wikiFuzz::chooseInput( array( "siteinfo" ) ),
+ "generator" => wikiFuzz::chooseInput( array( "allpages", "logevents", "watchlist", "info", "revisions" ) ),
+ "siprop" => wikiFuzz::chooseInput( array( "general", "namespaces", "general|namespaces" ) ),
);
// Add extra parameters based on what list choice we got.
- switch ($params["list"]) {
- case "usercontribs" : self::addListParams ($params, "uc", array("limit", "start", "end", "user", "dir") ); break;
- case "allpages" : self::addListParams ($params, "ap", array("from", "prefix", "namespace", "filterredir", "limit") ); break;
- case "watchlist" : self::addListParams ($params, "wl", array("allrev", "start", "end", "namespace", "dir", "limit", "prop") ); break;
- case "logevents" : self::addListParams ($params, "le", array("limit", "type", "start", "end", "user", "dir") ); break;
- case "recentchanges": self::addListParams ($params, "rc", array("limit", "prop", "show", "namespace", "start", "end", "dir") ); break;
- case "backlinks" : self::addListParams ($params, "bl", array("continue", "namespace", "redirect", "limit") ); break;
- case "embeddedin" : self::addListParams ($params, "ei", array("continue", "namespace", "redirect", "limit") ); break;
- case "imagelinks" : self::addListParams ($params, "il", array("continue", "namespace", "redirect", "limit") ); break;
+ switch ( $params["list"] ) {
+ case "usercontribs" : self::addListParams ( $params, "uc", array( "limit", "start", "end", "user", "dir" ) ); break;
+ case "allpages" : self::addListParams ( $params, "ap", array( "from", "prefix", "namespace", "filterredir", "limit" ) ); break;
+ case "watchlist" : self::addListParams ( $params, "wl", array( "allrev", "start", "end", "namespace", "dir", "limit", "prop" ) ); break;
+ case "logevents" : self::addListParams ( $params, "le", array( "limit", "type", "start", "end", "user", "dir" ) ); break;
+ case "recentchanges": self::addListParams ( $params, "rc", array( "limit", "prop", "show", "namespace", "start", "end", "dir" ) ); break;
+ case "backlinks" : self::addListParams ( $params, "bl", array( "continue", "namespace", "redirect", "limit" ) ); break;
+ case "embeddedin" : self::addListParams ( $params, "ei", array( "continue", "namespace", "redirect", "limit" ) ); break;
+ case "imagelinks" : self::addListParams ( $params, "il", array( "continue", "namespace", "redirect", "limit" ) ); break;
}
- if ($params["prop"] == "revisions") {
- self::addListParams ($params, "rv", array("prop", "limit", "startid", "endid", "end", "dir") );
+ if ( $params["prop"] == "revisions" ) {
+ self::addListParams ( $params, "rv", array( "prop", "limit", "startid", "endid", "end", "dir" ) );
}
// Sometimes we want redirects, sometimes we don't.
- if (wikiFuzz::randnum(3) == 0) {
- $params["redirects"] = wikiFuzz::chooseInput( array("1", 0, "", wikiFuzz::makeFuzz(2)) );
+ if ( wikiFuzz::randnum( 3 ) == 0 ) {
+ $params["redirects"] = wikiFuzz::chooseInput( array( "1", 0, "", wikiFuzz::makeFuzz( 2 ) ) );
}
return $params;
}
// Adds all the elements to the array, using the specified prefix.
- private static function addListParams(&$array, $prefix, $elements) {
- foreach ($elements as $element) {
- $array[$prefix . $element] = self::getParamDetails($element);
+ private static function addListParams( &$array, $prefix, $elements ) {
+ foreach ( $elements as $element ) {
+ $array[$prefix . $element] = self::getParamDetails( $element );
}
}
// For a given element name, returns the data for that element.
- private static function getParamDetails($element) {
- switch ($element) {
+ private static function getParamDetails( $element ) {
+ switch ( $element ) {
case 'startid' :
case 'endid' :
case 'start' :
case 'end' :
- case 'limit' : return wikiFuzz::chooseInput( array("0", "-1", "---'----------0", "+1", "8134", "320742734234235", "20060230121212", wikiFuzz::randnum(9000, -100), wikiFuzz::makeFuzz(2)) );
- case 'dir' : return wikiFuzz::chooseInput( array("newer", "older", wikifuzz::makeFuzz(2) ) );
- case 'user' : return wikiFuzz::chooseInput( array(USER_ON_WIKI, wikifuzz::makeFuzz(2) ) );
- case 'namespace' : return wikiFuzz::chooseInput( array(-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 200000, wikifuzz::makeFuzz(2)) );
- case 'filterredir': return wikiFuzz::chooseInput( array("all", "redirects", "nonredirectsallpages", wikifuzz::makeFuzz(2)) );
- case 'allrev' : return wikiFuzz::chooseInput( array("1", 0, "", wikiFuzz::makeFuzz(2)) );
- case 'prop' : return wikiFuzz::chooseInput( array("user", "comment", "timestamp", "patrol", "flags", "user|user|comment|flags", wikifuzz::makeFuzz(2) ) );
- case 'type' : return wikiFuzz::chooseInput( array("block", "protect", "rights", "delete", "upload", "move", "import", "renameuser", "newusers", "makebot", wikifuzz::makeFuzz(2) ) );
- case 'hide' : return wikiFuzz::chooseInput( array("minor", "bots", "anons", "liu", "liu|bots|", wikifuzz::makeFuzz(2) ) );
- case 'show' : return wikiFuzz::chooseInput( array('minor', '!minor', 'bot', '!bot', 'anon', '!anon', wikifuzz::makeFuzz(2) ) );
- default : return wikifuzz::makeFuzz(2);
+ case 'limit' : return wikiFuzz::chooseInput( array( "0", "-1", "---'----------0", "+1", "8134", "320742734234235", "20060230121212", wikiFuzz::randnum( 9000, -100 ), wikiFuzz::makeFuzz( 2 ) ) );
+ case 'dir' : return wikiFuzz::chooseInput( array( "newer", "older", wikifuzz::makeFuzz( 2 ) ) );
+ case 'user' : return wikiFuzz::chooseInput( array( USER_ON_WIKI, wikifuzz::makeFuzz( 2 ) ) );
+ case 'namespace' : return wikiFuzz::chooseInput( array( -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 200000, wikifuzz::makeFuzz( 2 ) ) );
+ case 'filterredir': return wikiFuzz::chooseInput( array( "all", "redirects", "nonredirectsallpages", wikifuzz::makeFuzz( 2 ) ) );
+ case 'allrev' : return wikiFuzz::chooseInput( array( "1", 0, "", wikiFuzz::makeFuzz( 2 ) ) );
+ case 'prop' : return wikiFuzz::chooseInput( array( "user", "comment", "timestamp", "patrol", "flags", "user|user|comment|flags", wikifuzz::makeFuzz( 2 ) ) );
+ case 'type' : return wikiFuzz::chooseInput( array( "block", "protect", "rights", "delete", "upload", "move", "import", "renameuser", "newusers", "makebot", wikifuzz::makeFuzz( 2 ) ) );
+ case 'hide' : return wikiFuzz::chooseInput( array( "minor", "bots", "anons", "liu", "liu|bots|", wikifuzz::makeFuzz( 2 ) ) );
+ case 'show' : return wikiFuzz::chooseInput( array( 'minor', '!minor', 'bot', '!bot', 'anon', '!anon', wikifuzz::makeFuzz( 2 ) ) );
+ default : return wikifuzz::makeFuzz( 2 );
}
}
function __construct() {
$this->pagePath = "api.php";
- $modes = array ("help",
+ $modes = array ( "help",
"login",
"opensearch",
"feedwatchlist",
- "query");
- $action = wikiFuzz::chooseInput( array_merge ($modes, array(wikifuzz::makeFuzz(2))) );
+ "query" );
+ $action = wikiFuzz::chooseInput( array_merge ( $modes, array( wikifuzz::makeFuzz( 2 ) ) ) );
- switch ($action) {
+ switch ( $action ) {
case "login" : $this->params = self::loginMode();
break;
case "opensearch" : $this->params = self::opensearchMode();
break;
case "query" : $this->params = self::queryMode();
break;
- case "help" :
+ case "help" :
default : // Do something random - "Crazy Ivan" mode.
$random_mode = wikiFuzz::chooseInput( $modes ) . "Mode";
// There is no "helpMode".
- if ($random_mode == "helpMode") $random_mode = "queryMode";
+ if ( $random_mode == "helpMode" ) $random_mode = "queryMode";
$this->params = self::$random_mode();
break;
}
$this->cookie = "wikidbUserID=10001; wikidbUserName=Test; wikidb_session=178df0fe68c75834643af65dec9ec98a; wikidbToken=1adc6753d62c44aec950c024d7ae0540";
// Output format
- $this->params["format"] = wikiFuzz::chooseInput( array("json", "jsonfm", "php", "phpfm",
- "wddx", "wddxfm", "xml", "xmlfm",
+ $this->params["format"] = wikiFuzz::chooseInput( array( "json", "jsonfm", "php", "phpfm",
+ "wddx", "wddxfm", "xml", "xmlfm",
"yaml", "yamlfm", "raw", "rawfm",
- wikifuzz::makeFuzz(2) ) );
+ wikifuzz::makeFuzz( 2 ) ) );
// Page does not produce HTML (sometimes).
$this->tidyValidate = false;
private function getGeSHiContent() {
return "<source lang=\"" . $this->getLang() . "\" "
- . (wikiFuzz::randnum(2) == 0 ? "line " : "")
- . (wikiFuzz::randnum(2) == 0 ? "strict " : "")
- . "start=" . wikiFuzz::chooseInput( array(wikiFuzz::randnum(-6000,6000), wikifuzz::makeFuzz(2)) )
+ . ( wikiFuzz::randnum( 2 ) == 0 ? "line " : "" )
+ . ( wikiFuzz::randnum( 2 ) == 0 ? "strict " : "" )
+ . "start=" . wikiFuzz::chooseInput( array( wikiFuzz::randnum( -6000, 6000 ), wikifuzz::makeFuzz( 2 ) ) )
. ">"
- . wikiFuzz::makeFuzz(2)
+ . wikiFuzz::makeFuzz( 2 )
. "</source>";
}
private function getLang() {
return wikiFuzz::chooseInput( array( "actionscript", "ada", "apache", "applescript", "asm", "asp", "autoit", "bash", "blitzbasic", "bnf", "c", "c_mac", "caddcl", "cadlisp",
- "cfdg", "cfm", "cpp", "cpp-qt", "csharp", "css", "d", "delphi", "diff", "div", "dos", "eiffel", "fortran", "freebasic", "gml", "groovy", "html4strict", "idl",
+ "cfdg", "cfm", "cpp", "cpp-qt", "csharp", "css", "d", "delphi", "diff", "div", "dos", "eiffel", "fortran", "freebasic", "gml", "groovy", "html4strict", "idl",
"ini", "inno", "io", "java", "java5", "javascript", "latex", "lisp", "lua", "matlab", "mirc", "mpasm", "mysql", "nsis", "objc", "ocaml", "ocaml-brief", "oobas",
"oracle8", "pascal", "perl", "php", "php-brief", "plsql", "python", "qbasic", "rails", "reg", "robots", "ruby", "sas", "scheme", "sdlbasic", "smalltalk", "smarty",
- "sql", "tcl", "text", "thinbasic", "tsql", "vb", "vbnet", "vhdl", "visualfoxpro", "winbatch", "xml", "xpp", "z80", wikifuzz::makeFuzz(1) ) );
+ "sql", "tcl", "text", "thinbasic", "tsql", "vb", "vbnet", "vhdl", "visualfoxpro", "winbatch", "xml", "xpp", "z80", wikifuzz::makeFuzz( 1 ) ) );
}
function __construct() {
/**
** selects a page test to run.
*/
-function selectPageTest($count) {
+function selectPageTest( $count ) {
// if the user only wants a specific test, then only ever give them that.
- if (defined("SPECIFIC_TEST")) {
+ if ( defined( "SPECIFIC_TEST" ) ) {
$testType = SPECIFIC_TEST;
return new $testType ();
}
// Some of the time we test Special pages, the remaining
// time we test using the standard edit page.
- switch ($count % 100) {
+ switch ( $count % 100 ) {
case 0 : return new successfulUserLoginTest();
case 1 : return new listusersTest();
case 2 : return new searchTest();
}
-/////////////////////// SAVING OUTPUT /////////////////////////
+// ///////////////////// SAVING OUTPUT /////////////////////////
/**
** Utility function for saving a file. Currently has no error checking.
*/
-function saveFile($data, $name) {
- file_put_contents($name, $data);
+function saveFile( $data, $name ) {
+ file_put_contents( $name, $data );
}
** This doesn't seem to always work though, and sometimes the output is too long
** to be a valid GET URL, so we also save in other formats.
*/
-function getAsURL(pageTest $test) {
- $used_question_mark = (strpos($test->getPagePath(), "?") !== false);
+function getAsURL( pageTest $test ) {
+ $used_question_mark = ( strpos( $test->getPagePath(), "?" ) !== false );
$retval = "http://get-to-post.nickj.org/?" . WIKI_BASE_URL . $test->getPagePath();
- foreach ($test->getParams() as $param => $value) {
- if (!$used_question_mark) {
+ foreach ( $test->getParams() as $param => $value ) {
+ if ( !$used_question_mark ) {
$retval .= "?";
$used_question_mark = true;
}
else {
$retval .= "&";
}
- $retval .= $param . "=" . urlencode($value);
+ $retval .= $param . "=" . urlencode( $value );
}
return $retval;
}
/**
** Saves a plain-text human-readable version of a test.
*/
-function saveTestAsText(pageTest $test, $filename) {
+function saveTestAsText( pageTest $test, $filename ) {
$str = "Test: " . $test->getPagePath();
- foreach ($test->getParams() as $param => $value) {
+ foreach ( $test->getParams() as $param => $value ) {
$str .= "\n$param: $value";
}
- $str .= "\nGet-to-post URL: " . getAsURL($test) . "\n";
- saveFile($str, $filename);
+ $str .= "\nGet-to-post URL: " . getAsURL( $test ) . "\n";
+ saveFile( $str, $filename );
}
** Saves a test as a standalone basic PHP script that shows this one problem.
** Resulting script requires PHP-Curl be installed in order to work.
*/
-function saveTestAsPHP(pageTest $test, $filename) {
+function saveTestAsPHP( pageTest $test, $filename ) {
$str = "<?php\n"
- . "\$params = " . var_export(escapeForCurl($test->getParams()), true) . ";\n"
+ . "\$params = " . var_export( escapeForCurl( $test->getParams() ), true ) . ";\n"
. "\$ch = curl_init();\n"
. "curl_setopt(\$ch, CURLOPT_POST, 1);\n"
. "curl_setopt(\$ch, CURLOPT_POSTFIELDS, \$params );\n"
- . "curl_setopt(\$ch, CURLOPT_URL, " . var_export(WIKI_BASE_URL . $test->getPagePath(), true) . ");\n"
+ . "curl_setopt(\$ch, CURLOPT_URL, " . var_export( WIKI_BASE_URL . $test->getPagePath(), true ) . ");\n"
. "curl_setopt(\$ch, CURLOPT_RETURNTRANSFER,1);\n"
- . ($test->getCookie() ? "curl_setopt(\$ch, CURLOPT_COOKIE, " . var_export($test->getCookie(), true) . ");\n" : "")
+ . ( $test->getCookie() ? "curl_setopt(\$ch, CURLOPT_COOKIE, " . var_export( $test->getCookie(), true ) . ");\n" : "" )
. "\$result=curl_exec(\$ch);\n"
. "curl_close (\$ch);\n"
. "print \$result;\n"
. "?>\n";
- saveFile($str, $filename);
+ saveFile( $str, $filename );
}
** Specifically, "<" and "@" need to be escaped if they are the first character,
** otherwise curl interprets these as meaning that we want to insert a file.
*/
-function escapeForCurl(array $input_params) {
+function escapeForCurl( array $input_params ) {
$output_params = array();
- foreach ($input_params as $param => $value) {
- if (strlen($value) > 0 && ( $value[0] == "@" || $value[0] == "<")) {
+ foreach ( $input_params as $param => $value ) {
+ if ( strlen( $value ) > 0 && ( $value[0] == "@" || $value[0] == "<" ) ) {
$value = "\\" . $value;
}
$output_params[$param] = $value;
** Saves a test as a standalone CURL shell script that shows this one problem.
** Resulting script requires standalone Curl be installed in order to work.
*/
-function saveTestAsCurl(pageTest $test, $filename) {
+function saveTestAsCurl( pageTest $test, $filename ) {
$str = "#!/bin/bash\n"
. "curl --silent --include --globoff \\\n"
- . ($test->getCookie() ? " --cookie " . escapeshellarg($test->getCookie()) . " \\\n" : "");
- foreach (escapeForCurl($test->getParams()) as $param => $value) {
- $str .= " -F " . escapeshellarg($param) . "=" . escapeshellarg($value) . " \\\n";
+ . ( $test->getCookie() ? " --cookie " . escapeshellarg( $test->getCookie() ) . " \\\n" : "" );
+ foreach ( escapeForCurl( $test->getParams() ) as $param => $value ) {
+ $str .= " -F " . escapeshellarg( $param ) . "=" . escapeshellarg( $value ) . " \\\n";
}
- $str .= " " . escapeshellarg(WIKI_BASE_URL . $test->getPagePath()); // beginning space matters.
+ $str .= " " . escapeshellarg( WIKI_BASE_URL . $test->getPagePath() ); // beginning space matters.
$str .= "\n";
- saveFile($str, $filename);
- chmod($filename, 0755); // make executable
+ saveFile( $str, $filename );
+ chmod( $filename, 0755 ); // make executable
}
/**
** Saves the internal data structure to file.
*/
-function saveTestData (pageTest $test, $filename) {
- saveFile(serialize($test), $filename);
+function saveTestData ( pageTest $test, $filename ) {
+ saveFile( serialize( $test ), $filename );
}
/**
** saves a test in the various formats.
*/
-function saveTest(pageTest $test, $testname) {
+function saveTest( pageTest $test, $testname ) {
$base_name = DIRECTORY . "/" . $testname;
- saveTestAsText($test, $base_name . INFO_FILE);
- saveTestAsPHP ($test, $base_name . PHP_TEST );
- saveTestAsCurl($test, $base_name . CURL_TEST);
- saveTestData ($test, $base_name . DATA_FILE);
+ saveTestAsText( $test, $base_name . INFO_FILE );
+ saveTestAsPHP ( $test, $base_name . PHP_TEST );
+ saveTestAsCurl( $test, $base_name . CURL_TEST );
+ saveTestData ( $test, $base_name . DATA_FILE );
}
-//////////////////// MEDIAWIKI OUTPUT /////////////////////////
+// ////////////////// MEDIAWIKI OUTPUT /////////////////////////
/**
** Asks MediaWiki for the HTML output of a test.
*/
-function wikiTestOutput(pageTest $test) {
+function wikiTestOutput( pageTest $test ) {
$ch = curl_init();
// specify the cookie, if required.
- if ($test->getCookie()) curl_setopt($ch, CURLOPT_COOKIE, $test->getCookie());
- curl_setopt($ch, CURLOPT_POST, 1); // save form using a POST
+ if ( $test->getCookie() ) curl_setopt( $ch, CURLOPT_COOKIE, $test->getCookie() );
+ curl_setopt( $ch, CURLOPT_POST, 1 ); // save form using a POST
- $params = escapeForCurl($test->getParams());
- curl_setopt($ch, CURLOPT_POSTFIELDS, $params ); // load the POST variables
+ $params = escapeForCurl( $test->getParams() );
+ curl_setopt( $ch, CURLOPT_POSTFIELDS, $params ); // load the POST variables
- curl_setopt($ch, CURLOPT_URL, WIKI_BASE_URL . $test->getPagePath() ); // set url to post to
- curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
+ curl_setopt( $ch, CURLOPT_URL, WIKI_BASE_URL . $test->getPagePath() ); // set url to post to
+ curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); // return into a variable
- $result=curl_exec ($ch);
+ $result = curl_exec ( $ch );
// if we encountered an error, then say so, and return an empty string.
- if (curl_error($ch)) {
- print "\nCurl error #: " . curl_errno($ch) . " - " . curl_error ($ch);
+ if ( curl_error( $ch ) ) {
+ print "\nCurl error #: " . curl_errno( $ch ) . " - " . curl_error ( $ch );
$result = "";
}
- curl_close ($ch);
+ curl_close ( $ch );
return $result;
}
-//////////////////// HTML VALIDATION /////////////////////////
+// ////////////////// HTML VALIDATION /////////////////////////
/*
** Asks the validator whether this is valid HTML, or not.
*/
-function validateHTML($text) {
+function validateHTML( $text ) {
- $params = array ("fragment" => $text);
+ $params = array ( "fragment" => $text );
$ch = curl_init();
- curl_setopt($ch, CURLOPT_POST, 1); // save form using a POST
- curl_setopt($ch, CURLOPT_POSTFIELDS, $params); // load the POST variables
- curl_setopt($ch, CURLOPT_URL, VALIDATOR_URL); // set url to post to
- curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
+ curl_setopt( $ch, CURLOPT_POST, 1 ); // save form using a POST
+ curl_setopt( $ch, CURLOPT_POSTFIELDS, $params ); // load the POST variables
+ curl_setopt( $ch, CURLOPT_URL, VALIDATOR_URL ); // set url to post to
+ curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); // return into a variable
- $result=curl_exec ($ch);
+ $result = curl_exec ( $ch );
// if we encountered an error, then log it, and exit.
- if (curl_error($ch)) {
- trigger_error("Curl error #: " . curl_errno($ch) . " - " . curl_error ($ch) );
- print "Curl error #: " . curl_errno($ch) . " - " . curl_error ($ch) . " - exiting.\n";
- exit(1);
+ if ( curl_error( $ch ) ) {
+ trigger_error( "Curl error #: " . curl_errno( $ch ) . " - " . curl_error ( $ch ) );
+ print "Curl error #: " . curl_errno( $ch ) . " - " . curl_error ( $ch ) . " - exiting.\n";
+ exit( 1 );
}
- curl_close ($ch);
+ curl_close ( $ch );
- $valid = (strpos($result, "Failed validation") === false ? true : false);
+ $valid = ( strpos( $result, "Failed validation" ) === false ? true : false );
- return array($valid, $result);
+ return array( $valid, $result );
}
/**
** Get tidy to check for no HTML errors in the output file (e.g. unescaped strings).
*/
-function tidyCheckFile($name) {
+function tidyCheckFile( $name ) {
$file = DIRECTORY . "/" . $name;
$command = PATH_TO_TIDY . " -output /tmp/out.html -quiet $file 2>&1";
$x = `$command`;
// Look for the most interesting Tidy errors and warnings.
- if ( strpos($x,"end of file while parsing attributes") !== false
- || strpos($x,"attribute with missing trailing quote mark") !== false
- || strpos($x,"missing '>' for end of tag") !== false
- || strpos($x,"Error:") !== false) {
+ if ( strpos( $x, "end of file while parsing attributes" ) !== false
+ || strpos( $x, "attribute with missing trailing quote mark" ) !== false
+ || strpos( $x, "missing '>' for end of tag" ) !== false
+ || strpos( $x, "Error:" ) !== false ) {
print "\nTidy found something - view details with: $command";
return false;
} else {
static $filesize;
// first time running this function
- if (!isset($filesize)) {
+ if ( !isset( $filesize ) ) {
// create log if it does not exist
- if (!file_exists(DB_ERROR_LOG_FILE)) {
- saveFile("", DB_ERROR_LOG_FILE);
+ if ( !file_exists( DB_ERROR_LOG_FILE ) ) {
+ saveFile( "", DB_ERROR_LOG_FILE );
}
- $filesize = filesize(DB_ERROR_LOG_FILE);
+ $filesize = filesize( DB_ERROR_LOG_FILE );
return false;
}
- $newsize = filesize(DB_ERROR_LOG_FILE);
+ $newsize = filesize( DB_ERROR_LOG_FILE );
// if the log has grown, then assume the current test caused it.
- if ($newsize != $filesize) {
+ if ( $newsize != $filesize ) {
$filesize = $newsize;
return true;
}
return false;
}
-////////////////// TOP-LEVEL PROBLEM-FINDING FUNCTION ////////////////////////
+// //////////////// TOP-LEVEL PROBLEM-FINDING FUNCTION ////////////////////////
/**
** takes a page test, and runs it and tests it for problems in the output.
** Returns: False on finding a problem, or True on no problems being found.
*/
-function runWikiTest(pageTest $test, &$testname, $can_overwrite = false) {
+function runWikiTest( pageTest $test, &$testname, $can_overwrite = false ) {
// by default don't overwrite a previous test of the same name.
- while ( ! $can_overwrite && file_exists(DIRECTORY . "/" . $testname . DATA_FILE)) {
- $testname .= "-" . mt_rand(0,9);
+ while ( ! $can_overwrite && file_exists( DIRECTORY . "/" . $testname . DATA_FILE ) ) {
+ $testname .= "-" . mt_rand( 0, 9 );
}
$filename = DIRECTORY . "/" . $testname . DATA_FILE;
// Store the time before and after, to find slow pages.
- $before = microtime(true);
+ $before = microtime( true );
// Get MediaWiki to give us the output of this test.
- $wiki_preview = wikiTestOutput($test);
+ $wiki_preview = wikiTestOutput( $test );
- $after = microtime(true);
+ $after = microtime( true );
// if we received no response, then that's interesting.
- if ($wiki_preview == "") {
+ if ( $wiki_preview == "" ) {
print "\nNo response received for: $filename";
return false;
}
// save output HTML to file.
$html_file = DIRECTORY . "/" . $testname . HTML_FILE;
- saveFile($wiki_preview, $html_file);
+ saveFile( $wiki_preview, $html_file );
// if there were PHP errors in the output, then that's interesting too.
- if ( strpos($wiki_preview, "<b>Warning</b>: " ) !== false
- || strpos($wiki_preview, "<b>Fatal error</b>: " ) !== false
- || strpos($wiki_preview, "<b>Notice</b>: " ) !== false
- || strpos($wiki_preview, "<b>Error</b>: " ) !== false
- || strpos($wiki_preview, "<b>Strict Standards:</b>") !== false
+ if ( strpos( $wiki_preview, "<b>Warning</b>: " ) !== false
+ || strpos( $wiki_preview, "<b>Fatal error</b>: " ) !== false
+ || strpos( $wiki_preview, "<b>Notice</b>: " ) !== false
+ || strpos( $wiki_preview, "<b>Error</b>: " ) !== false
+ || strpos( $wiki_preview, "<b>Strict Standards:</b>" ) !== false
) {
- $error = substr($wiki_preview, strpos($wiki_preview, "</b>:") + 7, 50);
+ $error = substr( $wiki_preview, strpos( $wiki_preview, "</b>:" ) + 7, 50 );
// Avoid probable PHP bug with bad session ids; http://bugs.php.net/bug.php?id=38224
- if ($error != "Unknown: The session id contains illegal character") {
+ if ( $error != "Unknown: The session id contains illegal character" ) {
print "\nPHP error/warning/notice in HTML output: $html_file ; $error";
return false;
}
}
// if there was a MediaWiki Backtrace message in the output, then that's also interesting.
- if( strpos($wiki_preview, "Backtrace:") !== false ) {
+ if ( strpos( $wiki_preview, "Backtrace:" ) !== false ) {
print "\nInternal MediaWiki error in HTML output: $html_file";
return false;
}
// if there was a Parser error comment in the output, then that's potentially interesting.
- if( strpos($wiki_preview, "!-- ERR") !== false ) {
+ if ( strpos( $wiki_preview, "!-- ERR" ) !== false ) {
print "\nParser Error comment in HTML output: $html_file";
return false;
}
// if a database error was logged, then that's definitely interesting.
- if( dbErrorLogged() ) {
+ if ( dbErrorLogged() ) {
print "\nDatabase Error logged for: $filename";
return false;
}
// validate result
$valid = true;
- if( VALIDATE_ON_WEB ) {
- list ($valid, $validator_output) = validateHTML($wiki_preview);
- if (!$valid) print "\nW3C web validation failed - view details with: html2text " . DIRECTORY . "/" . $testname . ".validator_output.html";
+ if ( VALIDATE_ON_WEB ) {
+ list ( $valid, $validator_output ) = validateHTML( $wiki_preview );
+ if ( !$valid ) print "\nW3C web validation failed - view details with: html2text " . DIRECTORY . "/" . $testname . ".validator_output.html";
}
// Get tidy to check the page, unless we already know it produces non-XHTML output.
- if( $test->tidyValidate() ) {
+ if ( $test->tidyValidate() ) {
$valid = tidyCheckFile( $testname . HTML_FILE ) && $valid;
}
// if it took more than 2 seconds to render, then it may be interesting too. (Possible DoS attack?)
- if (($after - $before) >= 2) {
- print "\nParticularly slow to render (" . round($after - $before, 2) . " seconds): $filename";
+ if ( ( $after - $before ) >= 2 ) {
+ print "\nParticularly slow to render (" . round( $after - $before, 2 ) . " seconds): $filename";
return false;
}
- if( $valid ) {
+ if ( $valid ) {
// Remove temp HTML file if test was valid:
unlink( $html_file );
- } elseif( VALIDATE_ON_WEB ) {
- saveFile($validator_output, DIRECTORY . "/" . $testname . ".validator_output.html");
+ } elseif ( VALIDATE_ON_WEB ) {
+ saveFile( $validator_output, DIRECTORY . "/" . $testname . ".validator_output.html" );
}
return $valid;
}
-/////////////////// RERUNNING OLD TESTS ///////////////////
+// ///////////////// RERUNNING OLD TESTS ///////////////////
/**
** We keep our failed tests so that they can be rerun.
function rerunPreviousTests() {
print "Retesting previously found problems.\n";
- $dir_contents = scandir (DIRECTORY);
+ $dir_contents = scandir ( DIRECTORY );
// sort file into the order a normal person would use.
- natsort ($dir_contents);
+ natsort ( $dir_contents );
- foreach ($dir_contents as $file) {
+ foreach ( $dir_contents as $file ) {
// if file is not a test, then skip it.
// Note we need to escape any periods or will be treated as "any character".
$matches = array();
- if (!ereg("(.*)" . str_replace(".", "\.", DATA_FILE) . "$", $file, $matches)) continue;
+ if ( !ereg( "(.*)" . str_replace( ".", "\.", DATA_FILE ) . "$", $file, $matches ) ) continue;
// reload the test.
$full_path = DIRECTORY . "/" . $file;
- $test = unserialize(file_get_contents($full_path));
+ $test = unserialize( file_get_contents( $full_path ) );
// if this is not a valid test, then skip it.
- if (! $test instanceof pageTest) {
+ if ( ! $test instanceof pageTest ) {
print "\nSkipping invalid test - $full_path";
continue;
}
// The date format is in Apache log format, which makes it easier to locate
// which retest caused which error in the Apache logs (only happens usually if
// apache segfaults).
- if (!QUIET) print "[" . date ("D M d H:i:s Y") . "] Retesting $file (" . get_class($test) . ")";
+ if ( !QUIET ) print "[" . date ( "D M d H:i:s Y" ) . "] Retesting $file (" . get_class( $test ) . ")";
// run test
$testname = $matches[1];
- $valid = runWikiTest($test, $testname, true);
+ $valid = runWikiTest( $test, $testname, true );
- if (!$valid) {
- saveTest($test, $testname);
- if (QUIET) {
- print "\nTest: " . get_class($test) . " ; Testname: $testname\n------";
+ if ( !$valid ) {
+ saveTest( $test, $testname );
+ if ( QUIET ) {
+ print "\nTest: " . get_class( $test ) . " ; Testname: $testname\n------";
} else {
print "\n";
}
}
else {
- if (!QUIET) print "\r";
- if (DELETE_PASSED_RETESTS) {
+ if ( !QUIET ) print "\r";
+ if ( DELETE_PASSED_RETESTS ) {
$prefix = DIRECTORY . "/" . $testname;
- if (is_file($prefix . DATA_FILE)) unlink($prefix . DATA_FILE);
- if (is_file($prefix . PHP_TEST )) unlink($prefix . PHP_TEST );
- if (is_file($prefix . CURL_TEST)) unlink($prefix . CURL_TEST);
- if (is_file($prefix . INFO_FILE)) unlink($prefix . INFO_FILE);
+ if ( is_file( $prefix . DATA_FILE ) ) unlink( $prefix . DATA_FILE );
+ if ( is_file( $prefix . PHP_TEST ) ) unlink( $prefix . PHP_TEST );
+ if ( is_file( $prefix . CURL_TEST ) ) unlink( $prefix . CURL_TEST );
+ if ( is_file( $prefix . INFO_FILE ) ) unlink( $prefix . INFO_FILE );
}
}
}
}
-////////////////////// MAIN LOOP ////////////////////////
+// //////////////////// MAIN LOOP ////////////////////////
// first check whether CURL is installed, because sometimes it's not.
-if( ! function_exists('curl_init') ) {
- die("Could not find 'curl_init' function. Is the curl extension compiled into PHP?\n");
+if ( ! function_exists( 'curl_init' ) ) {
+ die( "Could not find 'curl_init' function. Is the curl extension compiled into PHP?\n" );
}
// Initialization of types. wikiFuzz doesn't have a constructor because we want to
// access it staticly and not have any globals.
-wikiFuzz::$types = array_keys(wikiFuzz::$data);
+wikiFuzz::$types = array_keys( wikiFuzz::$data );
// Make directory if doesn't exist
-if (!is_dir(DIRECTORY)) {
- mkdir (DIRECTORY, 0700 );
+if ( !is_dir( DIRECTORY ) ) {
+ mkdir ( DIRECTORY, 0700 );
}
// otherwise, we first retest the things that we have found in previous runs
-else if (RERUN_OLD_TESTS) {
+else if ( RERUN_OLD_TESTS ) {
rerunPreviousTests();
}
// main loop.
-$start_time = date("U");
+$start_time = date( "U" );
$num_errors = 0;
-if (!QUIET) {
+if ( !QUIET ) {
print "Beginning main loop. Results are stored in the " . DIRECTORY . " directory.\n";
print "Press CTRL+C to stop testing.\n";
}
-for ($count=0; true; $count++) {
- if (!QUIET) {
+for ( $count = 0; true; $count++ ) {
+ if ( !QUIET ) {
// spinning progress indicator.
switch( $count % 4 ) {
case '0': print "\r/"; break;
}
// generate a page test to run.
- $test = selectPageTest($count);
+ $test = selectPageTest( $count );
- $mins = ( date("U") - $start_time ) / 60;
- if (!QUIET && $mins > 0) {
- print ". $num_errors poss errors. "
- . floor($mins) . " mins. "
- . round ($count / $mins, 0) . " tests/min. "
- . get_class($test); // includes the current test name.
+ $mins = ( date( "U" ) - $start_time ) / 60;
+ if ( !QUIET && $mins > 0 ) {
+ print ". $num_errors poss errors. "
+ . floor( $mins ) . " mins. "
+ . round ( $count / $mins, 0 ) . " tests/min. "
+ . get_class( $test ); // includes the current test name.
}
// run this test against MediaWiki, and see if the output was valid.
$testname = $count;
- $valid = runWikiTest($test, $testname, false);
+ $valid = runWikiTest( $test, $testname, false );
// save the failed test
if ( ! $valid ) {
- if (QUIET) {
- print "\nTest: " . get_class($test) . " ; Testname: $testname\n------";
+ if ( QUIET ) {
+ print "\nTest: " . get_class( $test ) . " ; Testname: $testname\n------";
} else {
print "\n";
}
- saveTest($test, $testname);
+ saveTest( $test, $testname );
$num_errors += 1;
} else if ( KEEP_PASSED_TESTS ) {
// print current time, with microseconds (matches "strace" format), and the test name.
- print " " . date("H:i:s.") . substr(current(explode(" ", microtime())), 2) . " " . $testname;
- saveTest($test, $testname);
+ print " " . date( "H:i:s." ) . substr( current( explode( " ", microtime() ) ), 2 ) . " " . $testname;
+ saveTest( $test, $testname );
}
// stop if we have reached max number of errors.
- if (defined("MAX_ERRORS") && $num_errors>=MAX_ERRORS) {
+ if ( defined( "MAX_ERRORS" ) && $num_errors >= MAX_ERRORS ) {
break;
}
// stop if we have reached max number of mins runtime.
- if (defined("MAX_RUNTIME") && $mins>=MAX_RUNTIME) {
+ if ( defined( "MAX_RUNTIME" ) && $mins >= MAX_RUNTIME ) {
break;
}
}
$optionsWithArgs = array( 'fake-job' );
-require( dirname(__FILE__).'/../commandLine.inc' );
-require( dirname(__FILE__).'/gearman.inc' );
+require( dirname( __FILE__ ) . '/../commandLine.inc' );
+require( dirname( __FILE__ ) . '/gearman.inc' );
if ( !$args ) {
$args = array( 'localhost' );
$startId = 0;
$endId = $dbr->selectField( 'page', 'MAX(page_id)', false, __METHOD__ );
while ( true ) {
- $res = $dbr->select(
- 'page',
+ $res = $dbr->select(
+ 'page',
array( 'page_namespace', 'page_title', 'page_id' ),
- array( 'page_id > ' . intval( $startId ) ),
+ array( 'page_id > ' . intval( $startId ) ),
__METHOD__,
- array( 'LIMIT' => $batchSize )
+ array( 'LIMIT' => $batchSize )
);
if ( $res->numRows() == 0 ) {
<?php
$optionsWithArgs = array( 'fake-job', 'procs' );
-require( dirname(__FILE__).'/../commandLine.inc' );
-require( dirname(__FILE__).'/gearman.inc' );
+require( dirname( __FILE__ ) . '/../commandLine.inc' );
+require( dirname( __FILE__ ) . '/gearman.inc' );
-ini_set('memory_limit', '150M' );
+ini_set( 'memory_limit', '150M' );
if ( isset( $options['procs'] ) ) {
$procs = $options['procs'];
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License 2.0 or later
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class GenerateSitemap extends Maintenance {
/**
* Create directory if it does not exist and return pathname with a trailing slash
*/
private static function init_path( $fspath ) {
- if( !isset( $fspath ) ) {
+ if ( !isset( $fspath ) ) {
return null;
}
# Create directory if needed
- if( $fspath && !is_dir( $fspath ) ) {
- wfMkdirParents( $fspath ) or die("Can not create directory $fspath.\n");
+ if ( $fspath && !is_dir( $fspath ) ) {
+ wfMkdirParents( $fspath ) or die( "Can not create directory $fspath.\n" );
}
- return realpath( $fspath ). DIRECTORY_SEPARATOR ;
+ return realpath( $fspath ) . DIRECTORY_SEPARATOR ;
}
/**
function generateNamespaces() {
// Only generate for specific namespaces if $wgSitemapNamespaces is an array.
global $wgSitemapNamespaces;
- if( is_array( $wgSitemapNamespaces ) ) {
+ if ( is_array( $wgSitemapNamespaces ) ) {
$this->namespaces = $wgSitemapNamespaces;
return;
}
$length += strlen( $entry );
$this->write( $this->file, $entry );
// generate pages for language variants
- if($wgContLang->hasVariants()){
+ if ( $wgContLang->hasVariants() ) {
$variants = $wgContLang->getVariants();
- foreach($variants as $vCode){
- if($vCode==$wgContLang->getCode()) continue; // we don't want default variant
- $entry = $this->fileEntry( $title->getFullURL('',$vCode), $date, $this->priority( $namespace ) );
+ foreach ( $variants as $vCode ) {
+ if ( $vCode == $wgContLang->getCode() ) continue; // we don't want default variant
+ $entry = $this->fileEntry( $title->getFullURL( '', $vCode ), $date, $this->priority( $namespace ) );
$length += strlen( $entry );
$this->write( $this->file, $entry );
}
*/
function sitemapFilename( $namespace, $count ) {
$ext = $this->compress ? '.gz' : '';
- return "sitemap-".wfWikiID()."-NS_$namespace-$count.xml$ext";
+ return "sitemap-" . wfWikiID() . "-NS_$namespace-$count.xml$ext";
}
/**
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class GetLagTimes extends Maintenance {
public function __construct() {
public function execute() {
$lb = wfGetLB();
- if( $lb->getServerCount() == 1 ) {
+ if ( $lb->getServerCount() == 1 ) {
$this->error( "This script dumps replication lag times, but you don't seem to have\n"
. "a multi-host db server configuration." );
} else {
$lags = $lb->getLagTimes();
- foreach( $lags as $n => $lag ) {
+ foreach ( $lags as $n => $lag ) {
$host = $lb->getServerName( $n );
- if( IP::isValid( $host ) ) {
+ if ( IP::isValid( $host ) ) {
$ip = $host;
$host = gethostbyaddr( $host );
} else {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class GetSlaveServer extends Maintenance {
public function __construct() {
}
public function execute() {
global $wgAllDBsAreLocalhost;
- if( $wgAllDBsAreLocalhost ) {
+ if ( $wgAllDBsAreLocalhost ) {
$host = 'localhost';
} else {
- if( $this->hasOption('group') ) {
- $db = wfGetDB( DB_SLAVE, $this->getOption('group') );
+ if ( $this->hasOption( 'group' ) ) {
+ $db = wfGetDB( DB_SLAVE, $this->getOption( 'group' ) );
$host = $db->getServer();
} else {
$lb = wfGetLB();
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class GetTextMaint extends Maintenance {
public function __construct() {
$titleText = $title->getPrefixedText();
$this->error( "Page $titleText does not exist.\n", true );
}
- $text = $rev->getText( $this->hasOption('show-private') ? Revision::RAW : Revision::FOR_PUBLIC );
+ $text = $rev->getText( $this->hasOption( 'show-private' ) ? Revision::RAW : Revision::FOR_PUBLIC );
if ( $text === false ) {
$titleText = $title->getPrefixedText();
$this->error( "Couldn't extract the text from $titleText.\n", true );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class HttpSessionDownload extends Maintenance {
public function __construct() {
}
public function execute() {
- wfProfileIn(__METHOD__);
+ wfProfileIn( __METHOD__ );
- //run the download:
- Http::doSessionIdDownload( $this->getOption('sid'), $this->getOption('usk') );
+ // run the download:
+ Http::doSessionIdDownload( $this->getOption( 'sid' ), $this->getOption( 'usk' ) );
// close up shop:
// Execute any deferred updates
// Shut down the database before exit
wfGetLBFactory()->shutdown();
- wfProfileOut(__METHOD__);
+ wfProfileOut( __METHOD__ );
}
}
$optionsWithArgs = array( 'report' );
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
/**
* @ingroup Maintenance
function handleRevision( $rev ) {
$title = $rev->getTitle();
- if( !$title ) {
+ if ( !$title ) {
$this->progress( "Got bogus revision with null title!" );
return;
}
$this->revCount++;
$this->report();
- if( !$this->dryRun ) {
+ if ( !$this->dryRun ) {
call_user_func( $this->importCallback, $rev );
}
}
function handleUpload( $revision ) {
- if( $this->uploads ) {
+ if ( $this->uploads ) {
$this->uploadCount++;
- //$this->report();
+ // $this->report();
$this->progress( "upload: " . $revision->getFilename() );
- if( !$this->dryRun ) {
+ if ( !$this->dryRun ) {
// bluuuh hack
- //call_user_func( $this->uploadCallback, $revision );
+ // call_user_func( $this->uploadCallback, $revision );
$dbw = wfGetDB( DB_MASTER );
return $dbw->deadlockLoop( array( $revision, 'importUpload' ) );
}
$this->revCount++;
$this->report();
- if( !$this->dryRun ) {
+ if ( !$this->dryRun ) {
call_user_func( $this->logItemCallback, $rev );
}
}
function report( $final = false ) {
- if( $final xor ( $this->pageCount % $this->reportingInterval == 0 ) ) {
+ if ( $final xor ( $this->pageCount % $this->reportingInterval == 0 ) ) {
$this->showReport();
}
}
function showReport() {
- if( $this->reporting ) {
+ if ( $this->reporting ) {
$delta = wfTime() - $this->startTime;
- if( $delta ) {
- $rate = sprintf("%.2f", $this->pageCount / $delta);
- $revrate = sprintf("%.2f", $this->revCount / $delta);
+ if ( $delta ) {
+ $rate = sprintf( "%.2f", $this->pageCount / $delta );
+ $revrate = sprintf( "%.2f", $this->revCount / $delta );
} else {
$rate = '-';
$revrate = '-';
}
# Logs dumps don't have page tallies
- if( $this->pageCount )
+ if ( $this->pageCount )
$this->progress( "$this->pageCount ($rate pages/sec $revrate revs/sec)" );
else
$this->progress( "$this->revCount ($revrate revs/sec)" );
}
- wfWaitForSlaves(5);
+ wfWaitForSlaves( 5 );
}
function progress( $string ) {
function importFromFile( $filename ) {
$t = true;
- if( preg_match( '/\.gz$/', $filename ) ) {
+ if ( preg_match( '/\.gz$/', $filename ) ) {
$filename = 'compress.zlib://' . $filename;
}
- elseif( preg_match( '/\.bz2$/', $filename ) ) {
+ elseif ( preg_match( '/\.bz2$/', $filename ) ) {
$filename = 'compress.bzip2://' . $filename;
}
- elseif( preg_match( '/\.7z$/', $filename ) ) {
+ elseif ( preg_match( '/\.7z$/', $filename ) ) {
$filename = 'mediawiki.compress.7z://' . $filename;
$t = false;
}
- $file = fopen( $filename, $t ? 'rt' : 't' ); //our 7zip wrapper uses popen, which seems not to like two-letter modes
+ $file = fopen( $filename, $t ? 'rt' : 't' ); // our 7zip wrapper uses popen, which seems not to like two-letter modes
return $this->importFromHandle( $file );
}
}
}
-if( wfReadOnly() ) {
+if ( wfReadOnly() ) {
wfDie( "Wiki is in read-only mode; you'll need to disable it for import to work.\n" );
}
$reader = new BackupReader();
-if( isset( $options['quiet'] ) ) {
+if ( isset( $options['quiet'] ) ) {
$reader->reporting = false;
}
-if( isset( $options['report'] ) ) {
+if ( isset( $options['report'] ) ) {
$reader->reportingInterval = intval( $options['report'] );
}
-if( isset( $options['dry-run'] ) ) {
+if ( isset( $options['dry-run'] ) ) {
$reader->dryRun = true;
}
-if( isset( $options['debug'] ) ) {
+if ( isset( $options['debug'] ) ) {
$reader->debug = true;
}
-if( isset( $options['uploads'] ) ) {
+if ( isset( $options['uploads'] ) ) {
$reader->uploads = true; // experimental!
}
-if( isset( $args[0] ) ) {
+if ( isset( $args[0] ) ) {
$result = $reader->importFromFile( $args[0] );
} else {
$result = $reader->importFromStdin();
}
-if( WikiError::isError( $result ) ) {
+if ( WikiError::isError( $result ) ) {
echo $result->getMessage() . "\n";
} else {
echo "Done!\n";
* @return mixed Array of filenames on success, or false on failure
*/
function findFiles( $dir, $exts ) {
- if( is_dir( $dir ) ) {
- if( $dhl = opendir( $dir ) ) {
+ if ( is_dir( $dir ) ) {
+ if ( $dhl = opendir( $dir ) ) {
$files = array();
- while( ( $file = readdir( $dhl ) ) !== false ) {
- if( is_file( $dir . '/' . $file ) ) {
+ while ( ( $file = readdir( $dhl ) ) !== false ) {
+ if ( is_file( $dir . '/' . $file ) ) {
list( /* $name */, $ext ) = splitFilename( $dir . '/' . $file );
- if( array_search( strtolower( $ext ), $exts ) !== false )
+ if ( array_search( strtolower( $ext ), $exts ) !== false )
$files[] = $dir . '/' . $file;
}
}
}
# FIXME: Access the api in a saner way and performing just one query (preferably batching files too).
-function getFileCommentFromSourceWiki($wiki_host, $file) {
+function getFileCommentFromSourceWiki( $wiki_host, $file ) {
$url = $wiki_host . '/api.php?action=query&format=xml&titles=File:' . rawurlencode( $file ) . '&prop=imageinfo&&iiprop=comment';
- $body = Http::get($url);
- if (preg_match('#<ii comment="([^"]*)" />#', $body, $matches) == 0) {
+ $body = Http::get( $url );
+ if ( preg_match( '#<ii comment="([^"]*)" />#', $body, $matches ) == 0 ) {
return false;
}
return html_entity_decode( $matches[1] );
}
-function getFileUserFromSourceWiki($wiki_host, $file) {
+function getFileUserFromSourceWiki( $wiki_host, $file ) {
$url = $wiki_host . '/api.php?action=query&format=xml&titles=File:' . rawurlencode( $file ) . '&prop=imageinfo&&iiprop=user';
- $body = Http::get($url);
- if (preg_match('#<ii user="([^"]*)" />#', $body, $matches) == 0) {
+ $body = Http::get( $url );
+ if ( preg_match( '#<ii user="([^"]*)" />#', $body, $matches ) == 0 ) {
return false;
}
*/
$optionsWithArgs = array( 'extensions', 'comment', 'comment-file', 'comment-ext', 'user', 'license', 'sleep', 'limit', 'from', 'source-wiki-url' );
-require_once( dirname(__FILE__) . '/commandLine.inc' );
-require_once( dirname(__FILE__) . '/importImages.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/importImages.inc' );
$processed = $added = $ignored = $skipped = $overwritten = $failed = 0;
echo( "Import Images\n\n" );
# Need a path
-if( count( $args ) > 0 ) {
+if ( count( $args ) > 0 ) {
$dir = $args[0];
# Check Protection
- if (isset($options['protect']) && isset($options['unprotect']))
- die("Cannot specify both protect and unprotect. Only 1 is allowed.\n");
+ if ( isset( $options['protect'] ) && isset( $options['unprotect'] ) )
+ die( "Cannot specify both protect and unprotect. Only 1 is allowed.\n" );
-if (isset($options['protect']) && $options['protect'] == 1)
- die("You must specify a protection option.\n");
+if ( isset( $options['protect'] ) && $options['protect'] == 1 )
+ die( "You must specify a protection option.\n" );
# Prepare the list of allowed extensions
global $wgFileExtensions;
$user = isset( $options['user'] )
? User::newFromName( $options['user'] )
: User::newFromName( 'Maintenance script' );
- if( !$user instanceof User )
+ if ( !$user instanceof User )
$user = User::newFromName( 'Maintenance script' );
$wgUser = $user;
# Get block check. If a value is given, this specified how often the check is performed
if ( isset( $options['check-userblock'] ) ) {
if ( !$options['check-userblock'] ) $checkUserBlock = 1;
- else $checkUserBlock = (int)$options['check-userblock'];
+ else $checkUserBlock = (int)$options['check-userblock'];
} else {
$checkUserBlock = false;
}
# Get sleep time.
$sleep = @$options['sleep'];
- if ( $sleep ) $sleep = (int)$sleep;
+ if ( $sleep ) $sleep = (int)$sleep;
# Get limit number
$limit = @$options['limit'];
- if ( $limit ) $limit = (int)$limit;
+ if ( $limit ) $limit = (int)$limit;
# Get the upload comment
$comment = NULL;
$license = isset( $options['license'] ) ? $options['license'] : '';
# Batch "upload" operation
- if( ( $count = count( $files ) ) > 0 ) {
+ if ( ( $count = count( $files ) ) > 0 ) {
- foreach( $files as $file ) {
+ foreach ( $files as $file ) {
$base = wfBaseName( $file );
# Validate a title
$title = Title::makeTitleSafe( NS_FILE, $base );
- if( !is_object( $title ) ) {
+ if ( !is_object( $title ) ) {
echo( "{$base} could not be imported; a valid title cannot be produced\n" );
continue;
}
}
if ( $checkUserBlock && ( ( $processed % $checkUserBlock ) == 0 ) ) {
- $user->clearInstanceCache( 'name' ); //reload from DB!
+ $user->clearInstanceCache( 'name' ); // reload from DB!
if ( $user->isBlocked() ) {
echo( $user->getName() . " was blocked! Aborting.\n" );
break;
# Check existence
$image = wfLocalFile( $title );
- if( $image->exists() ) {
- if( isset( $options['overwrite'] ) ) {
+ if ( $image->exists() ) {
+ if ( isset( $options['overwrite'] ) ) {
echo( "{$base} exists, overwriting..." );
$svar = 'overwritten';
} else {
} else {
if ( isset( $options['skip-dupes'] ) ) {
$repo = $image->getRepo();
- $sha1 = File::sha1Base36( $file ); #XXX: we end up calculating this again when actually uploading. that sucks.
+ $sha1 = File::sha1Base36( $file ); # XXX: we end up calculating this again when actually uploading. that sucks.
$dupes = $repo->findBySha1( $sha1 );
$svar = 'added';
}
- if (isset( $options['source-wiki-url'])) {
+ if ( isset( $options['source-wiki-url'] ) ) {
/* find comment text directly from source wiki, through MW's API */
- $real_comment = getFileCommentFromSourceWiki($options['source-wiki-url'], $base);
- if ($real_comment === false)
+ $real_comment = getFileCommentFromSourceWiki( $options['source-wiki-url'], $base );
+ if ( $real_comment === false )
$commentText = $comment;
else
$commentText = $real_comment;
/* find user directly from source wiki, through MW's API */
- $real_user = getFileUserFromSourceWiki($options['source-wiki-url'], $base);
- if ($real_user === false) {
+ $real_user = getFileUserFromSourceWiki( $options['source-wiki-url'], $base );
+ if ( $real_user === false ) {
$wgUser = $user;
} else {
- $wgUser = User::newFromName($real_user);
- if ($wgUser === false) {
+ $wgUser = User::newFromName( $real_user );
+ if ( $wgUser === false ) {
# user does not exist in target wiki
- echo ("failed: user '$real_user' does not exist in target wiki.");
+ echo ( "failed: user '$real_user' does not exist in target wiki." );
continue;
}
}
echo( " publishing {$file} by '" . $wgUser->getName() . "', comment '$commentText'... " );
} else {
$archive = $image->publish( $file );
- if( WikiError::isError( $archive ) || !$archive->isGood() ) {
+ if ( WikiError::isError( $archive ) || !$archive->isGood() ) {
echo( "failed.\n" );
$failed++;
continue;
global $wgRestrictionLevels;
- $protectLevel = isset($options['protect']) ? $options['protect'] : null;
+ $protectLevel = isset( $options['protect'] ) ? $options['protect'] : null;
if ( $protectLevel && in_array( $protectLevel, $wgRestrictionLevels ) ) {
$restrictions['move'] = $protectLevel;
$restrictions['edit'] = $protectLevel;
$doProtect = true;
}
- if (isset($options['unprotect'])) {
+ if ( isset( $options['unprotect'] ) ) {
$restrictions['move'] = '';
$restrictions['edit'] = '';
$doProtect = true;
} else if ( $image->recordUpload( $archive->value, $commentText, $license ) ) {
# We're done!
echo( "done.\n" );
- if ($doProtect) {
+ if ( $doProtect ) {
# Protect the file
$article = new Article( $title );
echo "\nWaiting for slaves...\n";
// Wait for slaves.
- sleep(2.0);
+ sleep( 2.0 );
wfWaitForSlaves( 1.0 );
echo( "\nSetting image restrictions ... " );
- if ( $article->updateRestrictions($restrictions) )
+ if ( $article->updateRestrictions( $restrictions ) )
echo( "done.\n" );
else
echo( "failed.\n" );
# Print out some statistics
echo( "\n" );
- foreach( array( 'count' => 'Found', 'limit' => 'Limit', 'ignored' => 'Ignored',
- 'added' => 'Added', 'skipped' => 'Skipped', 'overwritten' => 'Overwritten',
+ foreach ( array( 'count' => 'Found', 'limit' => 'Limit', 'ignored' => 'Ignored',
+ 'added' => 'Added', 'skipped' => 'Skipped', 'overwritten' => 'Overwritten',
'failed' => 'Failed' ) as $var => $desc ) {
- if( $$var > 0 )
+ if ( $$var > 0 )
echo( "{$desc}: {$$var}\n" );
}
showUsage();
}
-exit(0);
+exit( 0 );
function showUsage( $reason = false ) {
- if( $reason ) {
+ if ( $reason ) {
echo( $reason . "\n" );
}
For example, --source-wiki-url="http://en.wikipedia.org/"
TEXT;
- exit(1);
+ exit( 1 );
}
$options = array( 'help', 'nooverwrite', 'norc' );
$optionsWithArgs = array( 'title', 'user', 'comment' );
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
echo( "Import Text File\n\n" );
-if( count( $args ) < 1 || isset( $options['help'] ) ) {
+if ( count( $args ) < 1 || isset( $options['help'] ) ) {
showHelp();
} else {
$filename = $args[0];
echo( "Using {$filename}..." );
- if( is_file( $filename ) ) {
+ if ( is_file( $filename ) ) {
$title = isset( $options['title'] ) ? $options['title'] : titleFromFilename( $filename );
$title = Title::newFromURL( $title );
- if( is_object( $title ) ) {
+ if ( is_object( $title ) ) {
echo( "\nUsing title '" . $title->getPrefixedText() . "'..." );
- if( !$title->exists() || !isset( $options['nooverwrite'] ) ) {
+ if ( !$title->exists() || !isset( $options['nooverwrite'] ) ) {
$text = file_get_contents( $filename );
$user = isset( $options['user'] ) ? $options['user'] : 'Maintenance script';
$user = User::newFromName( $user );
- if( is_object( $user ) ) {
+ if ( is_object( $user ) ) {
echo( "\nUsing username '" . $user->getName() . "'..." );
$wgUser =& $user;
* @ingroup Maintenance
*/
-if( php_sapi_name() != 'cli' ) {
+if ( php_sapi_name() != 'cli' ) {
echo "Please customize the settings and run me from the command line.";
die( -1 );
}
/* globals */
$wgFieldSeparator = "\xb3"; # Some wikis may use different char
$FS = $wgFieldSeparator ;
- $FS1 = $FS."1" ;
- $FS2 = $FS."2" ;
- $FS3 = $FS."3" ;
+ $FS1 = $FS . "1" ;
+ $FS2 = $FS . "2" ;
+ $FS3 = $FS . "3" ;
# Unicode sanitization tools
require_once( dirname( dirname( __FILE__ ) ) . '/includes/normal/UtfNormal.php' );
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'other' );
- foreach( $letters as $letter ) {
+ foreach ( $letters as $letter ) {
$dir = "$wgRootDirectory/page/$letter";
- if( is_dir( $dir ) )
+ if ( is_dir( $dir ) )
importPageDirectory( $dir );
}
echo <<<XML
{
echo "\n<!-- Checking page directory " . xmlCommentSafe( $dir ) . " -->\n";
$mydir = opendir( $dir );
- while( $entry = readdir( $mydir ) ) {
+ while ( $entry = readdir( $mydir ) ) {
$m = array();
- if( preg_match( '/^(.+)\.db$/', $entry, $m ) ) {
+ if ( preg_match( '/^(.+)\.db$/', $entry, $m ) ) {
echo importPage( $prefix . $m[1] );
} else {
- if( is_dir( "$dir/$entry" ) ) {
- if( $entry != '.' && $entry != '..' ) {
+ if ( is_dir( "$dir/$entry" ) ) {
+ if ( $entry != '.' && $entry != '..' ) {
importPageDirectory( "$dir/$entry", "$entry/" );
}
} else {
function useModFilename( $title ) {
$c = substr( $title, 0, 1 );
- if(preg_match( '/[A-Z]/i', $c ) ) {
+ if ( preg_match( '/[A-Z]/i', $c ) ) {
return strtoupper( $c ) . "/$title";
}
return "other/$title";
function fetchPage( $title )
{
- global $FS1,$FS2,$FS3, $wgRootDirectory;
+ global $FS1, $FS2, $FS3, $wgRootDirectory;
$fname = $wgRootDirectory . "/page/" . useModFilename( $title ) . ".db";
- if( !file_exists( $fname ) ) {
+ if ( !file_exists( $fname ) ) {
echo "Couldn't open file '$fname' for page '$title'.\n";
die( -1 );
}
function fetchKeptPages( $title )
{
- global $FS1,$FS2,$FS3, $wgRootDirectory;
+ global $FS1, $FS2, $FS3, $wgRootDirectory;
$fname = $wgRootDirectory . "/keep/" . useModFilename( $title ) . ".kp";
- if( !file_exists( $fname ) ) return array();
+ if ( !file_exists( $fname ) ) return array();
$keptlist = explode( $FS1, file_get_contents( $fname ) );
array_shift( $keptlist ); # Drop the junk at beginning of file
$revisions = array();
- foreach( $keptlist as $rev ) {
+ foreach ( $keptlist as $rev ) {
$section = splitHash( $FS2, $rev );
$text = splitHash( $FS3, $section["data"] );
- if ( $text["text"] && $text["minor"] != "" && ( $section["ts"]*1 > 0 ) ) {
+ if ( $text["text"] && $text["minor"] != "" && ( $section["ts"] * 1 > 0 ) ) {
array_push( $revisions, array2object( array ( "text" => $text["text"] , "summary" => $text["summary"] ,
"minor" => $text["minor"] , "ts" => $section["ts"] ,
"username" => $section["username"] , "host" => $section["host"] ) ) );
function splitHash ( $sep , $str ) {
$temp = explode ( $sep , $str ) ;
$ret = array () ;
- for ( $i = 0; $i+1 < count ( $temp ) ; $i++ ) {
+ for ( $i = 0; $i + 1 < count ( $temp ) ; $i++ ) {
$ret[$temp[$i]] = $temp[++$i] ;
}
return $ret ;
{
global $usercache;
- if( $name ) {
- if( in_array( $name, $usercache ) ) {
+ if ( $name ) {
+ if ( in_array( $name, $usercache ) ) {
$userid = $usercache[$name];
} else {
# If we haven't imported user accounts
$newtitle = xmlsafe( str_replace( '_', ' ', recodeText( $title ) ) );
$munged = mungeFormat( $page->text );
- if( $munged != $page->text ) {
+ if ( $munged != $page->text ) {
/**
* Save a *new* revision with the conversion, and put the
* previous last version into the history.
# History
$revisions = array_merge( $revisions, fetchKeptPages( $title ) );
- if(count( $revisions ) == 0 ) {
+ if ( count( $revisions ) == 0 ) {
return NULL; // Was "$sql", which does not appear to be defined.
}
- foreach( $revisions as $rev ) {
+ foreach ( $revisions as $rev ) {
$text = xmlsafe( recodeText( $rev->text ) );
- $minor = ($rev->minor ? '<minor/>' : '');
+ $minor = ( $rev->minor ? '<minor/>' : '' );
list( /* $userid */ , $username ) = checkUserCache( $rev->username, $rev->host );
$username = xmlsafe( recodeText( $username ) );
$timestamp = xmlsafe( timestamp2ISO8601( $rev->ts ) );
return $string;
}
-function wfUtf8Sequence($codepoint) {
- if($codepoint < 0x80) return chr($codepoint);
- if($codepoint < 0x800) return chr($codepoint >> 6 & 0x3f | 0xc0) .
- chr($codepoint & 0x3f | 0x80);
- if($codepoint < 0x10000) return chr($codepoint >> 12 & 0x0f | 0xe0) .
- chr($codepoint >> 6 & 0x3f | 0x80) .
- chr($codepoint & 0x3f | 0x80);
- if($codepoint < 0x100000) return chr($codepoint >> 18 & 0x07 | 0xf0) . # Double-check this
- chr($codepoint >> 12 & 0x3f | 0x80) .
- chr($codepoint >> 6 & 0x3f | 0x80) .
- chr($codepoint & 0x3f | 0x80);
+function wfUtf8Sequence( $codepoint ) {
+ if ( $codepoint < 0x80 ) return chr( $codepoint );
+ if ( $codepoint < 0x800 ) return chr( $codepoint >> 6 & 0x3f | 0xc0 ) .
+ chr( $codepoint & 0x3f | 0x80 );
+ if ( $codepoint < 0x10000 ) return chr( $codepoint >> 12 & 0x0f | 0xe0 ) .
+ chr( $codepoint >> 6 & 0x3f | 0x80 ) .
+ chr( $codepoint & 0x3f | 0x80 );
+ if ( $codepoint < 0x100000 ) return chr( $codepoint >> 18 & 0x07 | 0xf0 ) . # Double-check this
+ chr( $codepoint >> 12 & 0x3f | 0x80 ) .
+ chr( $codepoint >> 6 & 0x3f | 0x80 ) .
+ chr( $codepoint & 0x3f | 0x80 );
# Doesn't yet handle outside the BMP
return "&#$codepoint;";
}
-function wfMungeToUtf8($string) {
+function wfMungeToUtf8( $string ) {
$string = preg_replace ( '/&#([0-9]+);/e', 'wfUtf8Sequence($1)', $string );
$string = preg_replace ( '/&#x([0-9a-f]+);/ie', 'wfUtf8Sequence(0x$1)', $string );
# Should also do named entities here
}
function timestamp2ISO8601( $ts ) {
- #2003-08-05T18:30:02Z
+ # 2003-08-05T18:30:02Z
return gmdate( 'Y-m-d', $ts ) . 'T' . gmdate( 'H:i:s', $ts ) . 'Z';
}
function array2object( $arr ) {
$o = (object)0;
- foreach( $arr as $x => $y ) {
+ foreach ( $arr as $x => $y ) {
$o->$x = $y;
}
return $o;
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class InitEditCount extends Maintenance {
public function __construct() {
// Autodetect mode...
$backgroundMode = count( $wgDBservers ) > 1 ||
- ($dbw instanceof DatabaseMySql && version_compare( $dbver, '4.1' ) < 0);
+ ( $dbw instanceof DatabaseMySql && version_compare( $dbver, '4.1' ) < 0 );
- if( $this->hasOption('background') ) {
+ if ( $this->hasOption( 'background' ) ) {
$backgroundMode = true;
- } elseif( $this->hasOption('quick') ) {
+ } elseif ( $this->hasOption( 'quick' ) ) {
$backgroundMode = false;
}
- if( $backgroundMode ) {
+ if ( $backgroundMode ) {
$this->output( "Using replication-friendly background mode...\n" );
$dbr = wfGetDB( DB_SLAVE );
$start = microtime( true );
$migrated = 0;
- for( $min = 0; $min <= $lastUser; $min += $chunkSize ) {
+ for ( $min = 0; $min <= $lastUser; $min += $chunkSize ) {
$max = $min + $chunkSize;
$result = $dbr->query(
"SELECT
GROUP BY user_id",
__METHOD__ );
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
$dbw->update( 'user',
array( 'user_editcount' => $row->user_editcount ),
array( 'user_id' => $row->user_id ),
$dbr->freeResult( $result );
$delta = microtime( true ) - $start;
- $rate = ($delta == 0.0) ? 0.0 : $migrated / $delta;
+ $rate = ( $delta == 0.0 ) ? 0.0 : $migrated / $delta;
$this->output( sprintf( "%s %d (%0.1f%%) done in %0.1f secs (%0.3f accounts/sec).\n",
wfWikiID(),
$migrated,
* @licence GNU General Public Licence 2.0 or later
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class InitStats extends Maintenance {
public function __construct() {
$image = $counter->files();
$this->output( "{$image}\n" );
- if( !$this->hasOption('noviews') ) {
+ if ( !$this->hasOption( 'noviews' ) ) {
$this->output( "Counting total page views..." );
$views = $counter->views();
$this->output( "{$views}\n" );
}
- if( $this->hasOption( 'active' ) ) {
+ if ( $this->hasOption( 'active' ) ) {
$this->output( "Counting active users..." );
$active = SiteStatsUpdate::cacheUpdate();
$this->output( "{$active}\n" );
$this->output( "\nUpdating site statistics..." );
- if( $this->hasOption( 'update' ) ) {
+ if ( $this->hasOption( 'update' ) ) {
$counter->update();
} else {
$counter->refresh();
# if PHP is globally configured to run through a gzip filter.
@ob_implicit_flush( true );
- if( !function_exists( 'version_compare' ) ) {
+ if ( !function_exists( 'version_compare' ) ) {
# version_compare was introduced in 4.1.0
echo "Your PHP version is much too old; 4.0.x will _not_ work. 5.1.0 or higher is required. ABORTING.\n";
die( 1 );
}
- if( version_compare( phpversion(), '5.1.0' ) < 0 ) {
- echo "PHP 5.1.0 or higher is required. If PHP 5 is available only when \n".
- "PHP files have a .php5 extension, please navigate to <a href=\"index.php5\">index.php5</a> \n".
+ if ( version_compare( phpversion(), '5.1.0' ) < 0 ) {
+ echo "PHP 5.1.0 or higher is required. If PHP 5 is available only when \n" .
+ "PHP files have a .php5 extension, please navigate to <a href=\"index.php5\">index.php5</a> \n" .
"to continue installation. ABORTING.\n";
die( 1 );
}
$test = new PhpXmlBugTester();
- if( !$test->ok ) {
+ if ( !$test->ok ) {
echo "Your system has a combination of PHP and libxml2 versions which is buggy\n" .
"and can cause hidden data corruption in MediaWiki and other web apps.\n" .
"Upgrade to PHP 5.2.9 or later and libxml2 2.7.3 or later!\n" .
$parser = xml_parser_create();
xml_set_character_data_handler( $parser, array( $this, 'chardata' ) );
- $parsedOk = xml_parse($parser, $xml, true);
- $this->ok = $parsedOk && ($this->parsedData == $charData);
+ $parsedOk = xml_parse( $parser, $xml, true );
+ $this->ok = $parsedOk && ( $this->parsedData == $charData );
}
- public function chardata($parser, $data) {
+ public function chardata( $parser, $data ) {
$this->parsedData .= $data;
}
}
if ( feof( STDIN ) ) {
$st = false;
} else {
- $st = fgets(STDIN, 1024);
+ $st = fgets( STDIN, 1024 );
}
}
- if ($st === false) return false;
+ if ( $st === false ) return false;
$resp = trim( $st );
return $resp;
}
function findExecutable( $name ) {
$paths = explode( PATH_SEPARATOR, getenv( "PATH" ) );
- foreach( $paths as $path ) {
+ foreach ( $paths as $path ) {
$full = $path . DIRECTORY_SEPARATOR . $name;
- if( file_exists( $full ) ) {
- if( wfIsWindows() || is_executable( $full ) ) {
+ if ( file_exists( $full ) ) {
+ if ( wfIsWindows() || is_executable( $full ) ) {
return $full;
}
}
function readlineEmulation( $prompt ) {
$bash = "bash";
- if( !wfIsWindows() && findExecutable( $bash ) ) {
+ if ( !wfIsWindows() && findExecutable( $bash ) ) {
$retval = false;
$encPrompt = wfEscapeShellArg( $prompt );
$command = "read -er -p $encPrompt && echo \"\$REPLY\"";
$encCommand = wfEscapeShellArg( $command );
$line = wfShellExec( "$bash -c $encCommand", $retval );
- if( $retval == 0 ) {
+ if ( $retval == 0 ) {
return $line;
- } elseif( $retval == 127 ) {
+ } elseif ( $retval == 127 ) {
// Couldn't execute bash even though we thought we saw it.
// Shell probably spit out an error message, sorry :(
// Fall through to fgets()...
return false;
}
print $prompt;
- return fgets(STDIN, 1024);
+ return fgets( STDIN, 1024 );
}
$error = $db->sourceFile( $fname );
if ( $error !== true ) {
print $error;
- exit(1);
+ exit( 1 );
}
}
$optionsWithArgs = array( 'target', 'repository', 'repos' );
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
-define('EXTINST_NOPATCH', 0);
-define('EXTINST_WRITEPATCH', 6);
-define('EXTINST_HOTPATCH', 10);
+define( 'EXTINST_NOPATCH', 0 );
+define( 'EXTINST_WRITEPATCH', 6 );
+define( 'EXTINST_HOTPATCH', 10 );
/**
* @ingroup Maintenance
function printListing( ) {
trigger_error( 'override InstallerRepository::printListing()', E_USER_ERROR );
- }
+ }
function getResource( $name ) {
trigger_error( 'override InstallerRepository::getResource()', E_USER_ERROR );
- }
+ }
static function makeRepository( $path, $type = NULL ) {
if ( !$type ) {
if ( !$proto ) {
$type = 'dir';
- } else if ( ( $proto == 'http' || $proto == 'https' ) && preg_match( '!([^\w]svn|svn[^\w])!i', $path) ) {
- $type = 'svn'; #HACK!
+ } else if ( ( $proto == 'http' || $proto == 'https' ) && preg_match( '!([^\w]svn|svn[^\w])!i', $path ) ) {
+ $type = 'svn'; # HACK!
} else {
$type = $proto;
}
}
foreach ( $ff as $f ) {
- $n = basename($f);
+ $n = basename( $f );
if ( !is_dir( $f ) ) {
$m = array();
print "\t$n\n";
}
- }
+ }
function getResource( $name ) {
$path = $this->path . '/' . $name;
if ( !file_exists( $path ) ) $path = $this->path . '/' . $name . '.zip';
return new LocalInstallerResource( $path );
- }
+ }
}
/**
}
$m = array();
- $ok = preg_match_all( '!<a\s[^>]*href\s*=\s*['."'".'"]([^/'."'".'"]+)\.tgz['."'".'"][^>]*>.*?</a>!si', $txt, $m, PREG_SET_ORDER );
+ $ok = preg_match_all( '!<a\s[^>]*href\s*=\s*[' . "'" . '"]([^/' . "'" . '"]+)\.tgz[' . "'" . '"][^>]*>.*?</a>!si', $txt, $m, PREG_SET_ORDER );
if ( !$ok ) {
ExtensionInstaller::error( "listing index from {$this->path} does not match!" );
print ( $txt );
print "\t$n\n";
}
}
- }
+ }
function getResource( $name ) {
$path = $this->path . '/' . $name . '.tgz';
return new WebInstallerResource( $path );
- }
+ }
}
/**
return false;
}
- $ll = preg_split('/(\s*[\r\n]\s*)+/', $txt);
+ $ll = preg_split( '/(\s*[\r\n]\s*)+/', $txt );
foreach ( $ll as $line ) {
$m = array();
- if ( !preg_match('!^(.*)/$!', $line, $m) ) continue;
+ if ( !preg_match( '!^(.*)/$!', $line, $m ) ) continue;
$n = $m[1];
print "\t$n\n";
}
- }
+ }
function getResource( $name ) {
$path = $this->path . '/' . $name;
return new SVNInstallerResource( $path );
- }
+ }
}
/**
function InstallerResource( $path, $isdir, $islocal ) {
$this->path = $path;
- $this->isdir= $isdir;
+ $this->isdir = $isdir;
$this->islocal = $islocal;
$m = array();
function fetch( $target ) {
trigger_error( 'override InstallerResource::fetch()', E_USER_ERROR );
- }
+ }
function extract( $file, $target ) {
- if ( $this->extensions == '.tgz' || $this->extensions == '.tar.gz' ) { #tgz file
+ if ( $this->extensions == '.tgz' || $this->extensions == '.tar.gz' ) { # tgz file
ExtensionInstaller::note( "extracting $file..." );
$code = null; // shell Exec return value.
wfShellExec( 'tar zxvf ' . escapeshellarg( $file ) . ' -C ' . escapeshellarg( $target ), $code );
return false;
}
}
- else if ( $this->extensions == '.zip' ) { #zip file
+ else if ( $this->extensions == '.zip' ) { # zip file
ExtensionInstaller::note( "extracting $file..." );
$code = null; // shell Exec return value.
wfShellExec( 'unzip ' . escapeshellarg( $file ) . ' -d ' . escapeshellarg( $target ) , $code );
return false;
}
}
- else {
+ else {
ExtensionInstaller::error( "unknown extension {$this->extensions}!" );
return false;
}
return true;
- }
+ }
/*static*/ function makeResource( $url ) {
$m = array();
}
$this->extract( $tmp, dirname( $target ) );
- unlink($tmp);
+ unlink( $tmp );
return true;
- }
+ }
}
/**
}
return true;
- }
+ }
}
/**
$this->incpath = "extensions/$name";
$this->tasks = array();
- #TODO: allow a subdir different from "extensions"
- #TODO: allow a config file different from "LocalSettings.php"
+ # TODO: allow a subdir different from "extensions"
+ # TODO: allow a config file different from "LocalSettings.php"
}
static function note( $msg ) {
}
$s = trim( $s );
- return $s;
+ return $s;
}
function confirm( $msg ) {
- while ( true ) {
- $s = $this->prompt( $msg . " [yes/no]: ");
- $s = strtolower( trim($s) );
+ while ( true ) {
+ $s = $this->prompt( $msg . " [yes/no]: " );
+ $s = strtolower( trim( $s ) );
if ( $s == 'yes' || $s == 'y' ) { return true; }
else if ( $s == 'no' || $s == 'n' ) { return false; }
if ( $ff === false || $ff === NULL ) return false;
foreach ( $ff as $f ) {
- $n= basename( $f );
- if ( $n{0} == '.' ) continue; #HACK: skip dot files
-
- if ( is_link( $f ) ) continue; #skip link
-
+ $n = basename( $f );
+ if ( $n { 0 } == '.' ) continue; # HACK: skip dot files
+
+ if ( is_link( $f ) ) continue; # skip link
+
if ( is_dir( $f ) ) {
ExtensionInstaller::setPermissions( $f, $dirbits, $filebits );
}
if ( file_exists( $this->dir ) && glob( $this->dir . "/*" ) ) {
if ( $this->confirm( "{$this->dir} exists and is not empty.\nDelete all files in that directory?" ) ) {
$this->deleteContents( $this->dir );
- }
+ }
else {
return false;
- }
+ }
}
$ok = $this->source->fetch( $this->dir );
if ( file_exists( $this->dir . '/INSTALL' ) ) $this->tasks[] = "read the INSTALL file in {$this->dir}";
if ( file_exists( $this->dir . '/RELEASE-NOTES' ) ) $this->tasks[] = "read the RELEASE-NOTES file in {$this->dir}";
- #TODO: configure this smartly...?
+ # TODO: configure this smartly...?
$this->setPermissions( $this->dir, 0755, 0644 );
$this->note( "fetched extension to {$this->dir}" );
}
function patchLocalSettings( $mode ) {
- #NOTE: if we get a better way to hook up extensions, that should be used instead.
+ # NOTE: if we get a better way to hook up extensions, that should be used instead.
$f = $this->dir . '/install.settings';
$t = $this->target . '/LocalSettings.php';
- #TODO: assert version ?!
- #TODO: allow custom installer scripts + sql patches
-
+ # TODO: assert version ?!
+ # TODO: allow custom installer scripts + sql patches
+
if ( !file_exists( $f ) ) {
self::warn( "No install.settings file provided!" );
$this->tasks[] = "Please read the instructions and edit LocalSettings.php manually to activate the extension.";
}
if ( $mode == EXTINST_HOTPATCH ) {
- #NOTE: keep php extension for backup file!
- $bak = $this->target . '/LocalSettings.install-' . $this->name . '-' . wfTimestamp(TS_MW) . '.bak.php';
+ # NOTE: keep php extension for backup file!
+ $bak = $this->target . '/LocalSettings.install-' . $this->name . '-' . wfTimestamp( TS_MW ) . '.bak.php';
$ok = copy( $t, $bak );
$this->warn( "removed old configuration block for extension {$this->name}!" );
}
- $newblock= "\n# BEGIN $marker\n$settings\n# END $marker\n";
+ $newblock = "\n# BEGIN $marker\n$settings\n# END $marker\n";
$localsettings = preg_replace( "/\?>\s*$/si", "$newblock?>", $localsettings );
if ( $mode != EXTINST_HOTPATCH ) {
- $t = $this->target . '/LocalSettings.install-' . $this->name . '-' . wfTimestamp(TS_MW) . '.php';
+ $t = $this->target . '/LocalSettings.install-' . $this->name . '-' . wfTimestamp( TS_MW ) . '.php';
}
$ok = file_put_contents( $t, $localsettings );
}
else {
self::note( "created patched settings file $t" );
- $this->tasks[] = "Replace your current LocalSettings.php with ".basename($t);
+ $this->tasks[] = "Replace your current LocalSettings.php with " . basename( $t );
}
return true;
if ( !$repos ) $repos = @$options['repos'];
if ( !$repos ) $repos = @$wgExtensionInstallerRepository;
-if ( !$repos && file_exists("$tgt/.svn") && is_dir("$tgt/.svn") ) {
+if ( !$repos && file_exists( "$tgt/.svn" ) && is_dir( "$tgt/.svn" ) ) {
$svn = file_get_contents( "$tgt/.svn/entries" );
$m = array();
if ( !$repos ) $repos = 'http://svn.wikimedia.org/svnroot/mediawiki/trunk/extensions';
-if( !isset( $args[0] ) && !@$options['list'] ) {
+if ( !isset( $args[0] ) && !@$options['list'] ) {
die( "USAGE: installExtension.php [options] <name> [source]\n" .
- "OPTIONS: \n" .
+ "OPTIONS: \n" .
" --list list available extensions. <name> is ignored / may be omitted.\n" .
" --repository <n> repository to fetch extensions from. May be a local directoy,\n" .
" an SVN repository or a HTTP directory\n" .
" --target <dir> mediawiki installation directory to use\n" .
" --nopatch don't create a patched LocalSettings.php\n" .
" --hotpatch patched LocalSettings.php directly (creates a backup)\n" .
- "SOURCE: specifies the package source directly. If given, the repository is ignored.\n" .
+ "SOURCE: specifies the package source directly. If given, the repository is ignored.\n" .
" The source my be a local file (tgz or zip) or directory, the URL of a\n" .
- " remote file (tgz or zip), or a SVN path.\n"
+ " remote file (tgz or zip), or a SVN path.\n"
);
}
if ( isset( $options['list'] ) ) {
$repository->printListing();
- exit(0);
+ exit( 0 );
}
$name = $args[0];
$src = isset( $args[1] ) ? $args[1] : $repository->getResource( $name );
-#TODO: detect $source mismatching $name !!
+# TODO: detect $source mismatching $name !!
$mode = EXTINST_WRITEPATCH;
if ( isset( $options['nopatch'] ) || @$wgExtensionInstallerNoPatch ) { $mode = EXTINST_NOPATCH; }
else if ( isset( $options['hotpatch'] ) || @$wgExtensionInstallerHotPatch ) { $mode = EXTINST_HOTPATCH; }
if ( !file_exists( "$tgt/LocalSettings.php" ) ) {
- die("can't find $tgt/LocalSettings.php\n");
+ die( "can't find $tgt/LocalSettings.php\n" );
}
if ( $mode == EXTINST_HOTPATCH && !is_writable( "$tgt/LocalSettings.php" ) ) {
- die("can't write to $tgt/LocalSettings.php\n");
+ die( "can't write to $tgt/LocalSettings.php\n" );
}
if ( !file_exists( "$tgt/extensions" ) ) {
- die("can't find $tgt/extensions\n");
+ die( "can't find $tgt/extensions\n" );
}
if ( !is_writable( "$tgt/extensions" ) ) {
- die("can't write to $tgt/extensions\n");
+ die( "can't write to $tgt/extensions\n" );
}
$installer = new ExtensionInstaller( $name, $src, $tgt );
print "\tEXPECT THE UNEXPECTED!\n";
print "\n";
-if ( !$installer->confirm("continue") ) die("aborted\n");
+if ( !$installer->confirm( "continue" ) ) die( "aborted\n" );
$ok = $installer->fetchExtension();
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class DatabaseLag extends Maintenance {
public function __construct() {
if ( $this->hasOption( 'r' ) ) {
$lb = wfGetLB();
echo 'time ';
- for( $i = 1; $i < $lb->getServerCount(); $i++ ) {
+ for ( $i = 1; $i < $lb->getServerCount(); $i++ ) {
$hostname = $lb->getServerName( $i );
printf( "%-12s ", $hostname );
}
echo "\n";
- while( 1 ) {
+ while ( 1 ) {
$lb->clearLagTimeCache();
$lags = $lb->getLagTimes();
unset( $lags[0] );
echo gmdate( 'H:i:s' ) . ' ';
- foreach( $lags as $i => $lag ) {
+ foreach ( $lags as $i => $lag ) {
printf( "%-12s " , $lag === false ? 'false' : $lag );
}
echo "\n";
} else {
$lb = wfGetLB();
$lags = $lb->getLagTimes();
- foreach( $lags as $i => $lag ) {
+ foreach ( $lags as $i => $lag ) {
$name = $lb->getServerName( $i );
$this->output( sprintf( "%-20s %s\n" , $name, $lag === false ? 'false' : $lag ) );
}
<?php
-if (!defined('MEDIAWIKI')) die();
+if ( !defined( 'MEDIAWIKI' ) ) die();
/**
* Statistic output classes.
*
echo "'''Statistics are based on:''' <code>" . $version . "</code>\n\n";
echo "'''Note:''' These statistics can be generated by running <code>php maintenance/language/transstat.php</code>.\n\n";
echo "For additional information on specific languages (the message names, the actual problems, etc.), run <code>php maintenance/language/checkLanguage.php --lang=foo</code>.\n\n";
- echo '{| class="sortable wikitable" border="2" cellpadding="4" cellspacing="0" style="background-color: #F9F9F9; border: 1px #AAAAAA solid; border-collapse: collapse; clear:both;" width="100%"'."\n";
+ echo '{| class="sortable wikitable" border="2" cellpadding="4" cellspacing="0" style="background-color: #F9F9F9; border: 1px #AAAAAA solid; border-collapse: collapse; clear:both;" width="100%"' . "\n";
}
function footer() {
echo "|}\n";
echo '';
}
function element( $in, $heading = false ) {
- echo ($heading ? '!' : '|') . "$in\n";
+ echo ( $heading ? '!' : '|' ) . "$in\n";
}
function formatPercent( $subset, $total, $revert = false, $accuracy = 2 ) {
- $v = @round(255 * $subset / $total);
+ $v = @round( 255 * $subset / $total );
if ( $revert ) {
$v = 255 - $v;
}
$green = sprintf( '%02X', 2 * $v );
} else {
# Yellow to Green
- $red = sprintf('%02X', 2 * ( 255 - $v ) );
+ $red = sprintf( '%02X', 2 * ( 255 - $v ) );
$green = 'FF';
}
$blue = '00';
$color = $red . $green . $blue;
$percent = statsOutput::formatPercent( $subset, $total, $revert, $accuracy );
- return 'bgcolor="#'. $color .'"|'. $percent;
+ return 'bgcolor="#' . $color . '"|' . $percent;
}
}
/** Output text. To be used on a terminal for example. */
class textStatsOutput extends statsOutput {
function element( $in, $heading = false ) {
- echo $in."\t";
+ echo $in . "\t";
}
function blockend() {
echo "\n";
* @ingroup MaintenanceLanguage
*/
-require_once( dirname(__FILE__) . '/../Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
class AllTrans extends Maintenance {
public function __construct() {
public function execute() {
$wgEnglishMessages = array_keys( Language::getMessagesFor( 'en' ) );
- foreach( $wgEnglishMessages as $key ) {
+ foreach ( $wgEnglishMessages as $key ) {
$this->output( "$key\n" );
}
}
* @ingroup MaintenanceLanguage
*/
-require_once( dirname(__FILE__).'/../commandLine.inc' );
-$messagesDir = dirname(__FILE__).'/../../languages/messages/';
+require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
+$messagesDir = dirname( __FILE__ ) . '/../../languages/messages/';
$runTest = false;
$run = false;
$runMode = 'text';
// Check parameters
-if ( isset( $options['lang'] ) && isset( $options['clang'] )) {
- if (!isset( $options['mode'] )) {
+if ( isset( $options['lang'] ) && isset( $options['clang'] ) ) {
+ if ( !isset( $options['mode'] ) ) {
$runMode = 'text';
} else {
- if (!strcmp($options['mode'],'wiki')) {
+ if ( !strcmp( $options['mode'], 'wiki' ) ) {
$runMode = 'wiki';
- } else if (!strcmp($options['mode'],'php')) {
+ } else if ( !strcmp( $options['mode'], 'php' ) ) {
$runMode = 'php';
- } else if (!strcmp($options['mode'],'raw')) {
+ } else if ( !strcmp( $options['mode'], 'raw' ) ) {
$runMode = 'raw';
} else {
}
if ( $runTest ) {
$langCode = $options['lang'];
$langCodeC = $options['clang'];
- $langCodeF = ucfirst(strtolower(preg_replace('/-/','_',$langCode)));
- $langCodeFC = ucfirst(strtolower(preg_replace('/-/','_',$langCodeC)));
- $messagesFile = $messagesDir.'Messages'.$langCodeF.'.php';
- $messagesFileC = $messagesDir.'Messages'.$langCodeFC.'.php';
- if (file_exists($messagesFile) && file_exists($messagesFileC)) {
+ $langCodeF = ucfirst( strtolower( preg_replace( '/-/', '_', $langCode ) ) );
+ $langCodeFC = ucfirst( strtolower( preg_replace( '/-/', '_', $langCodeC ) ) );
+ $messagesFile = $messagesDir . 'Messages' . $langCodeF . '.php';
+ $messagesFileC = $messagesDir . 'Messages' . $langCodeFC . '.php';
+ if ( file_exists( $messagesFile ) && file_exists( $messagesFileC ) ) {
$run = true;
}
else {
// Run to check the dupes
if ( $run ) {
- if (!strcmp($runMode,'wiki')) {
+ if ( !strcmp( $runMode, 'wiki' ) ) {
$runMode = 'wiki';
- } else if (!strcmp($runMode,'raw')) {
+ } else if ( !strcmp( $runMode, 'raw' ) ) {
$runMode = 'raw';
}
include( $messagesFile );
- $messageExist = isset($messages);
- if ($messageExist)
+ $messageExist = isset( $messages );
+ if ( $messageExist )
$wgMessages[$langCode] = $messages;
include( $messagesFileC );
- $messageCExist = isset($messages);
- if ($messageCExist)
+ $messageCExist = isset( $messages );
+ if ( $messageCExist )
$wgMessages[$langCodeC] = $messages;
$count = 0;
- if (($messageExist) && ($messageCExist)) {
+ if ( ( $messageExist ) && ( $messageCExist ) ) {
- if (!strcmp($runMode,'php')) {
- print("<?php\n");
- print('$dupeMessages = array('."\n");
+ if ( !strcmp( $runMode, 'php' ) ) {
+ print( "<?php\n" );
+ print( '$dupeMessages = array(' . "\n" );
}
- foreach ($wgMessages[$langCodeC] as $key => $value) {
- foreach ($wgMessages[$langCode] as $ckey => $cvalue) {
- if (!strcmp($key,$ckey)) {
- if ((!strcmp($key,$ckey)) && (!strcmp($value,$cvalue))) {
- if (!strcmp($runMode,'raw')) {
- print("$key\n");
- } else if (!strcmp($runMode,'php')) {
- print("'$key' => '',\n");
- } else if (!strcmp($runMode,'wiki')) {
- $uKey = ucfirst($key);
- print("* MediaWiki:$uKey/$langCode\n");
+ foreach ( $wgMessages[$langCodeC] as $key => $value ) {
+ foreach ( $wgMessages[$langCode] as $ckey => $cvalue ) {
+ if ( !strcmp( $key, $ckey ) ) {
+ if ( ( !strcmp( $key, $ckey ) ) && ( !strcmp( $value, $cvalue ) ) ) {
+ if ( !strcmp( $runMode, 'raw' ) ) {
+ print( "$key\n" );
+ } else if ( !strcmp( $runMode, 'php' ) ) {
+ print( "'$key' => '',\n" );
+ } else if ( !strcmp( $runMode, 'wiki' ) ) {
+ $uKey = ucfirst( $key );
+ print( "* MediaWiki:$uKey/$langCode\n" );
} else {
- print("* $key\n");
+ print( "* $key\n" );
}
$count++;
}
}
}
}
- if (!strcmp($runMode,'php')) {
- print(");\n");
+ if ( !strcmp( $runMode, 'php' ) ) {
+ print( ");\n" );
}
- if (!strcmp($runMode,'text')) {
- if ($count == 1) {
+ if ( !strcmp( $runMode, 'text' ) ) {
+ if ( $count == 1 ) {
echo "\nThere are $count duplicated message in $langCode, against to $langCodeC.\n";
} else {
echo "\nThere are $count duplicated messages in $langCode, against to $langCodeC.\n";
}
}
} else {
- if (!$messageExist)
+ if ( !$messageExist )
echo "There are no messages defined in $langCode.\n";
- if (!$messageCExist)
+ if ( !$messageCExist )
echo "There are no messages defined in $langCodeC.\n";
- }
+ }
}
* @ingroup MaintenanceLanguage
*/
-require_once( dirname(__FILE__).'/../commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
require_once( 'languages.inc' );
require_once( 'checkLanguage.inc' );
-if( !class_exists( 'MessageGroups' ) || !class_exists( 'PremadeMediawikiExtensionGroups' ) ) {
+if ( !class_exists( 'MessageGroups' ) || !class_exists( 'PremadeMediawikiExtensionGroups' ) ) {
echo <<<TEXT
Please add the Translate extension to LocalSettings.php, and enable the extension groups:
require_once( 'extensions/Translate/Translate.php' );
If you still get this message, update Translate to its latest version.
TEXT;
- exit(-1);
+ exit( -1 );
}
$cli = new CheckExtensionsCLI( $options, $argv[0] );
* @ingroup MaintenanceLanguage
*/
-require_once( dirname(__FILE__).'/../commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
require_once( 'checkLanguage.inc' );
require_once( 'languages.inc' );
try {
$cli->execute();
-} catch( MWException $e ) {
+} catch ( MWException $e ) {
print 'Error: ' . $e->getMessage() . "\n";
}
* @ingroup MaintenanceLanguage
*/
-require_once( dirname(__FILE__) . '/../Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
class CountMessages extends Maintenance {
public function __construct() {
$nonZero = 0;
foreach ( glob( "$dir/*.php" ) as $file ) {
$baseName = basename( $file );
- if( !preg_match( '/Messages([A-Z][a-z_]+)\.php$/', $baseName, $m ) ) {
+ if ( !preg_match( '/Messages([A-Z][a-z_]+)\.php$/', $baseName, $m ) ) {
continue;
}
$code = str_replace( '_', '-', strtolower( $m[1] ) );
$numMessages = $this->getNumMessages( $file );
- //print "$code: $numMessages\n";
+ // print "$code: $numMessages\n";
$total += $numMessages;
if ( $numMessages > 0 ) {
$nonZero ++;
* @ingroup MaintenanceLanguage
*/
-require_once( dirname(__FILE__) . '/../Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
class DateFormats extends Maintenance {
}
$this->output( $lang->time( $this->ts, false, $pref ) );
}
- $this->output( "\n$code both: " );
+ $this->output( "\n$code both: " );
foreach ( $prefs as $index => $pref ) {
if ( $index > 0 ) {
$this->output( ' | ' );
*/
/** This script run from the commandline */
-require_once( dirname(__FILE__).'/../parserTests.inc' );
-require_once( dirname(__FILE__).'/../commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/../parserTests.inc' );
+require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
-if( isset($options['help']) ) { usage(); wfDie(); }
+if ( isset( $options['help'] ) ) { usage(); wfDie(); }
-$wgLanguageCode = ucfirstlcrest($wgLanguageCode);
+$wgLanguageCode = ucfirstlcrest( $wgLanguageCode );
/** Language messages we will use as reference. By default 'en' */
$referenceMessages = $wgAllMessagesEn;
$referenceLanguage = 'En';
-$referenceFilename = 'Language'.$referenceLanguage.'.php';
+$referenceFilename = 'Language' . $referenceLanguage . '.php';
/** Language messages we will test. */
$testMessages = array();
$testLanguage = '';
# FUNCTIONS
/** @todo more informations !! */
function usage() {
-echo 'php DiffLanguage.php [lang [file]] [--color=(yes|no|light)]'."\n";
+echo 'php DiffLanguage.php [lang [file]] [--color=(yes|no|light)]' . "\n";
}
/** Return a given string with first letter upper case, the rest lowercase */
-function ucfirstlcrest($string) {
- return strtoupper(substr($string,0,1)).strtolower(substr($string,1));
+function ucfirstlcrest( $string ) {
+ return strtoupper( substr( $string, 0, 1 ) ) . strtolower( substr( $string, 1 ) );
}
/**
* @param $languageCode String: formated language code
* @return array The MediaWiki default $wgAllMessages array requested
*/
-function getMediawikiMessages($languageCode = 'En') {
+function getMediawikiMessages( $languageCode = 'En' ) {
$foo = "wgAllMessages$languageCode";
global $$foo;
global $wgSkinNamesEn; // potentially unused global declaration?
// it might already be loaded in LocalSettings.php
- if(!isset($$foo)) {
+ if ( !isset( $$foo ) ) {
global $IP;
- $langFile = $IP.'/languages/classes/Language'.$languageCode.'.php';
- if (file_exists( $langFile ) ) {
+ $langFile = $IP . '/languages/classes/Language' . $languageCode . '.php';
+ if ( file_exists( $langFile ) ) {
print "Including $langFile\n";
- include($langFile);
- } else wfDie("ERROR: The file $langFile does not exist !\n");
+ include( $langFile );
+ } else wfDie( "ERROR: The file $langFile does not exist !\n" );
}
return $$foo;
}
* @param $languageCode String: language of the external array
* @return array A $wgAllMessages array from an external file.
*/
-function getExternalMessages($filename, $languageCode) {
+function getExternalMessages( $filename, $languageCode ) {
print "Including external file $filename.\n";
- include($filename);
+ include( $filename );
$foo = "wgAllMessages$languageCode";
return $$foo;
}
# MAIN ENTRY
-if ( isset($args[0]) ) {
- $lang = ucfirstlcrest($args[0],1);
+if ( isset( $args[0] ) ) {
+ $lang = ucfirstlcrest( $args[0], 1 );
// eventually against another language file we will use as reference instead
// of the default english language.
- if( isset($args[1])) {
+ if ( isset( $args[1] ) ) {
// we assume the external file contain an array of messages for the
// lang we are testing
$referenceMessages = getExternalMessages( $args[1], $lang );
}
// Load datas from MediaWiki
- $testMessages = getMediawikiMessages($lang);
+ $testMessages = getMediawikiMessages( $lang );
$testLanguage = $lang;
} else {
usage();
$i = 0;
$msg = "MW Language{$testLanguage}.php against ";
-if($externalRef) { $msg .= 'external file '; }
+if ( $externalRef ) { $msg .= 'external file '; }
else { $msg .= 'internal file '; }
-$msg .= $referenceFilename.' ('.$referenceLanguage."):\n----\n";
+$msg .= $referenceFilename . ' (' . $referenceLanguage . "):\n----\n";
echo $msg;
// process messages
-foreach($referenceMessages as $index => $ref)
+foreach ( $referenceMessages as $index => $ref )
{
// message is not localized
- if(!(isset($testMessages[$index]))) {
+ if ( !( isset( $testMessages[$index] ) ) ) {
$i++;
print "'$index' => \"$ref\",\n";
// Messages in the same language differs
- } elseif( ($lang == $referenceLanguage) AND ($testMessages[$index] != $ref)) {
+ } elseif ( ( $lang == $referenceLanguage ) AND ( $testMessages[$index] != $ref ) ) {
print "\n$index differs:\n";
- print $myParserTest->quickDiff($testMessages[$index],$ref,'tested','reference');
+ print $myParserTest->quickDiff( $testMessages[$index], $ref, 'tested', 'reference' );
}
}
-echo "\n----\n".$msg;
-echo "$referenceLanguage language is complete at ".number_format((100 - $i/count($wgAllMessagesEn) * 100),2)."%\n";
-echo "$i unlocalised messages of the ".count($wgAllMessagesEn)." messages available.\n";
+echo "\n----\n" . $msg;
+echo "$referenceLanguage language is complete at " . number_format( ( 100 - $i / count( $wgAllMessagesEn ) * 100 ), 2 ) . "%\n";
+echo "$i unlocalised messages of the " . count( $wgAllMessagesEn ) . " messages available.\n";
* @ingroup MaintenanceLanguage
*/
-require_once( dirname(__FILE__).'/../Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
class Digit2Html extends Maintenance {
# A list of unicode numerals is available at:
# http://www.fileformat.info/info/unicode/category/Nd/list.htm
- private $mLangs = array(
- 'Ar', 'As', 'Bh', 'Bo', 'Dz',
- 'Fa', 'Gu', 'Hi', 'Km', 'Kn',
- 'Ks', 'Lo', 'Ml', 'Mr', 'Ne',
- 'New', 'Or', 'Pa', 'Pi', 'Sa'
+ private $mLangs = array(
+ 'Ar', 'As', 'Bh', 'Bo', 'Dz',
+ 'Fa', 'Gu', 'Hi', 'Km', 'Kn',
+ 'Ks', 'Lo', 'Ml', 'Mr', 'Ne',
+ 'New', 'Or', 'Pa', 'Pi', 'Sa'
);
public function __construct() {
}
public function execute() {
- foreach( $this->mLangs as $code ) {
+ foreach ( $this->mLangs as $code ) {
$filename = Language::getMessagesFileName( $code );
$this->output( "Loading language [$code] ... " );
unset( $digitTransformTable );
require_once( $filename );
- if( !isset( $digitTransformTable ) ) {
+ if ( !isset( $digitTransformTable ) ) {
$this->error( "\$digitTransformTable not found for lang: $code" );
continue;
}
$this->output( "OK\n\$digitTransformTable = array(\n" );
- foreach( $digitTransformTable as $latin => $translation ) {
+ foreach ( $digitTransformTable as $latin => $translation ) {
$htmlent = utf8ToHexSequence( $translation );
$this->output( "'$latin' => '$translation', # &#x$htmlent;\n" );
}
* @todo Make this more useful, right now just dumps $wgContentLang
*/
-require_once( dirname(__FILE__) . '/../Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
class DumpMessages extends Maintenance {
public function __construct() {
define( 'MEDIAWIKI', 1 );
define( 'NOT_REALLY_MEDIAWIKI', 1 );
-class Language {}
+class Language { }
foreach ( glob( 'Language*.php' ) as $file ) {
if ( $file != 'Language.php' ) {
require_once( $file );
}
}
-$removedFunctions = array( 'date', 'time', 'timeanddate', 'formatMonth', 'formatDay',
- 'getMonthName', 'getMonthNameGen', 'getMonthAbbreviation', 'getWeekdayName',
+$removedFunctions = array( 'date', 'time', 'timeanddate', 'formatMonth', 'formatDay',
+ 'getMonthName', 'getMonthNameGen', 'getMonthAbbreviation', 'getWeekdayName',
'userAdjust', 'dateFormat', 'timeSeparator', 'timeDateSeparator', 'timeBeforeDate',
'monthByLatinNumber', 'getSpecialMonthName',
// No decomposition
continue;
}
- if ( !preg_match( '/^ *(<\w*>) +([0-9A-F ]*)$/',
- $data['Decomposition_Type_Mapping'], $m ) )
+ if ( !preg_match( '/^ *(<\w*>) +([0-9A-F ]*)$/',
+ $data['Decomposition_Type_Mapping'], $m ) )
{
$this->error( "Can't parse Decomposition_Type/Mapping on line $lineNum" );
$this->error( $line );
*/
/** This is a command line script */
-require_once(dirname(__FILE__) . '/../Maintenance.php' );
-require_once(dirname(__FILE__) . '/languages.inc' );
+require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/languages.inc' );
-define('ALL_LANGUAGES', true);
-define('XGETTEXT_BIN', 'xgettext');
-define('MSGMERGE_BIN', 'msgmerge');
+define( 'ALL_LANGUAGES', true );
+define( 'XGETTEXT_BIN', 'xgettext' );
+define( 'MSGMERGE_BIN', 'msgmerge' );
// used to generate the .pot
-define('XGETTEXT_OPTIONS', '-n --keyword=wfMsg --keyword=wfMsgForContent --keyword=wfMsgHtml --keyword=wfMsgWikiHtml ');
-define('MSGMERGE_OPTIONS', ' -v ');
+define( 'XGETTEXT_OPTIONS', '-n --keyword=wfMsg --keyword=wfMsgForContent --keyword=wfMsgHtml --keyword=wfMsgWikiHtml ' );
+define( 'MSGMERGE_OPTIONS', ' -v ' );
-define('LOCALE_OUTPUT_DIR', $IP.'/locale');
+define( 'LOCALE_OUTPUT_DIR', $IP . '/locale' );
class Lang2Po extends Maintenance {
public function __construct() {
$langTool = new languages();
- if( $this->getOption( 'lang', ALL_LANGUAGES ) === ALL_LANGUAGES ) {
+ if ( $this->getOption( 'lang', ALL_LANGUAGES ) === ALL_LANGUAGES ) {
$codes = $langTool->getLanguages();
} else {
$codes = array( $this->getOption( 'lang' ) );
}
// Do all languages
- foreach ( $codes as $langcode) {
+ foreach ( $codes as $langcode ) {
$this->output( "Loading messages for $langcode:\n" );
- if( !$this->generatePo($langcode, $langTool->getMessages($langcode) ) ) {
+ if ( !$this->generatePo( $langcode, $langTool->getMessages( $langcode ) ) ) {
$this->error( "ERROR: Failed to write file." );
} else {
$this->output( "Applying template:" );
- $this->applyPot($langcode);
+ $this->applyPot( $langcode );
}
}
}
* @param array &$messages Array containing the various messages.
* @return string Filename where stuff got saved or false.
*/
- private function generatePo($langcode, $messages) {
+ private function generatePo( $langcode, $messages ) {
$data = $this->poHeader();
// Generate .po entries
- foreach( $messages['all'] as $identifier => $content ) {
+ foreach ( $messages['all'] as $identifier => $content ) {
$data .= "msgid \"$identifier\"\n";
// Escape backslashes
- $tmp = str_replace('\\', '\\\\', $content);
+ $tmp = str_replace( '\\', '\\\\', $content );
// Escape doublelquotes
- $tmp = preg_replace( "/(?<!\\\\)\"/", '\"', $tmp);
+ $tmp = preg_replace( "/(?<!\\\\)\"/", '\"', $tmp );
// Rewrite multilines to gettext format
- $tmp = str_replace("\n", "\"\n\"", $tmp);
+ $tmp = str_replace( "\n", "\"\n\"", $tmp );
- $data .= 'msgstr "'. $tmp . "\"\n\n";
+ $data .= 'msgstr "' . $tmp . "\"\n\n";
}
// Write the content to a file in locale/XX/messages.po
- $dir = LOCALE_OUTPUT_DIR.'/'.$langcode;
- if( !is_dir($dir) ) { mkdir( $dir, 0770 ); }
- $filename = $dir.'/fromlanguagefile.po';
+ $dir = LOCALE_OUTPUT_DIR . '/' . $langcode;
+ if ( !is_dir( $dir ) ) { mkdir( $dir, 0770 ); }
+ $filename = $dir . '/fromlanguagefile.po';
$file = fopen( $filename , 'wb' );
- if( fwrite( $file, $data ) ) {
+ if ( fwrite( $file, $data ) ) {
fclose( $file );
return $filename;
} else {
private function generatePot() {
global $IP;
$curdir = getcwd();
- chdir($IP);
+ chdir( $IP );
exec( XGETTEXT_BIN
- .' '.XGETTEXT_OPTIONS
- .' -o '.LOCALE_OUTPUT_DIR.'/wfMsg.pot'
- .' includes/*php'
+ . ' ' . XGETTEXT_OPTIONS
+ . ' -o ' . LOCALE_OUTPUT_DIR . '/wfMsg.pot'
+ . ' includes/*php'
);
- chdir($curdir);
+ chdir( $curdir );
}
- private function applyPot($langcode) {
- $langdir = LOCALE_OUTPUT_DIR.'/'.$langcode;
+ private function applyPot( $langcode ) {
+ $langdir = LOCALE_OUTPUT_DIR . '/' . $langcode;
- $from = $langdir.'/fromlanguagefile.po';
- $pot = LOCALE_OUTPUT_DIR.'/wfMsg.pot';
- $dest = $langdir.'/messages.po';
+ $from = $langdir . '/fromlanguagefile.po';
+ $pot = LOCALE_OUTPUT_DIR . '/wfMsg.pot';
+ $dest = $langdir . '/messages.po';
// Merge template and generate file to get final .po
- exec(MSGMERGE_BIN.MSGMERGE_OPTIONS." $from $pot -o $dest ");
+ exec( MSGMERGE_BIN . MSGMERGE_OPTIONS . " $from $pot -o $dest " );
// delete no more needed file
// unlink($from);
}
*/
/** This is a command line script */
-require_once( dirname(__FILE__) . '/../Maintenance.php' );
-require_once( dirname(__FILE__) . '/languages.inc' );
+require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/languages.inc' );
class LangMemUsage extends Maintenance {
foreach ( $langtool->getLanguages() as $langcode ) {
Language::factory( $langcode );
$memstep = memory_get_usage();
- $this->output( sprintf( "%12s: %d\n", $langcode, ($memstep- $memlast) ) );
+ $this->output( sprintf( "%12s: %d\n", $langcode, ( $memstep - $memlast ) ) );
$memlast = $memstep;
}
$memend = memory_get_usage();
- $this->output( ' Total Usage: '.($memend - $memstart)."\n" );
+ $this->output( ' Total Usage: ' . ( $memend - $memstart ) . "\n" );
}
}
* @defgroup MaintenanceLanguage MaintenanceLanguage
*/
-require_once( dirname(__FILE__).'/../commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
require_once( 'languages.inc' );
require_once( 'writeMessagesArray.inc' );
global $wgLanguages;
$messages = $wgLanguages->getMessages( $code );
$messages = $messages['all'];
- if ($removeDupes) {
+ if ( $removeDupes ) {
$messages = removeDupes( $messages, $dupeMsgSource );
}
MessageWriter::writeMessagesToFile( $messages, $code, $write, $listUnknown, $removeUnknown );
* @return $newMsgArray The output message array, with duplicates removed.
*/
function removeDupes( $oldMsgArray, $dupeMsgSource ) {
- if (file_exists($dupeMsgSource)) {
- include($dupeMsgSource);
- if (!isset($dupeMessages)) {
- echo("There are no duplicated messages in the source file provided.");
- exit(1);
+ if ( file_exists( $dupeMsgSource ) ) {
+ include( $dupeMsgSource );
+ if ( !isset( $dupeMessages ) ) {
+ echo( "There are no duplicated messages in the source file provided." );
+ exit( 1 );
}
} else {
- echo ("The specified file $dupeMsgSource cannot be found.");
- exit(1);
+ echo ( "The specified file $dupeMsgSource cannot be found." );
+ exit( 1 );
}
$newMsgArray = $oldMsgArray;
- foreach ($oldMsgArray as $key => $value) {
+ foreach ( $oldMsgArray as $key => $value ) {
if ( array_key_exists( $key, $dupeMessages ) ) {
- unset($newMsgArray[$key]);
+ unset( $newMsgArray[$key] );
}
}
return $newMsgArray;
* remove-duplicates: Remove duplicated messages based on a PHP source file.
TEXT;
- exit(1);
+ exit( 1 );
}
# Get the language code
*/
$optionsWithArgs = array( 'output' );
-require_once( dirname(__FILE__).'/../commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
require_once( 'languages.inc' );
-require_once( dirname(__FILE__).'/StatOutputs.php' );
+require_once( dirname( __FILE__ ) . '/StatOutputs.php' );
if ( isset( $options['help'] ) ) {
Example: php maintenance/transstat.php --output=text
TEXT;
- exit(1);
+ exit( 1 );
}
$keys = array_keys( $vars );
$diff = array_diff( $keys, Language::$mLocalisationKeys );
if ( $diff ) {
- print "\nWarning: unrecognised variable(s): " . implode( ', ', $diff ) ."\n";
+ print "\nWarning: unrecognised variable(s): " . implode( ', ', $diff ) . "\n";
} else {
print " ok\n";
}
*/
/** */
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
-$mcc = new MWMemcached( array('persistant' => true/*, 'debug' => true*/) );
+$mcc = new MWMemcached( array( 'persistant' => true/*, 'debug' => true*/ ) );
$mcc->set_servers( $wgMemCachedServers );
-#$mcc->set_debug( true );
+# $mcc->set_debug( true );
-function mccShowHelp($command) {
- $commandList = array(
+function mccShowHelp( $command ) {
+ $commandList = array(
'get' => 'grabs something',
'getsock' => 'lists sockets',
'set' => 'changes something',
'quit' => 'exit mcc',
'help' => 'help about a command',
);
- if( !$command ) {
+ if ( !$command ) {
$command = 'fullhelp';
}
- if( $command === 'fullhelp' ) {
- foreach( $commandList as $cmd => $desc ) {
+ if ( $command === 'fullhelp' ) {
+ foreach ( $commandList as $cmd => $desc ) {
print "$cmd: $desc\n";
}
- } elseif( isset( $commandList[$command] ) ) {
+ } elseif ( isset( $commandList[$command] ) ) {
print "$command: $commandList[$command]\n";
} else {
print "$command: command does not exist or no help for it\n";
$quit = false;
$line = readconsole( '> ' );
- if ($line === false) exit;
+ if ( $line === false ) exit;
$args = explode( ' ', $line );
$command = array_shift( $args );
switch ( $command ) {
case 'help':
// show an help message
- mccShowHelp(array_shift($args));
+ mccShowHelp( array_shift( $args ) );
break;
case 'get':
$res = $res[$args[1]];
}
if ( $res === false ) {
- #print 'Error: ' . $mcc->error_string() . "\n";
+ # print 'Error: ' . $mcc->error_string() . "\n";
print "MemCached error\n";
} elseif ( is_string( $res ) ) {
print "$res\n";
$value = implode( ' ', $args );
}
if ( !$mcc->set( $key, $value, 0 ) ) {
- #print 'Error: ' . $mcc->error_string() . "\n";
+ # print 'Error: ' . $mcc->error_string() . "\n";
print "MemCached error\n";
}
break;
case 'delete':
$key = implode( ' ', $args );
if ( !$mcc->delete( $key ) ) {
- #print 'Error: ' . $mcc->error_string() . "\n";
+ # print 'Error: ' . $mcc->error_string() . "\n";
print "MemCached error\n";
}
break;
case 'history':
if ( function_exists( 'readline_list_history' ) ) {
- foreach( readline_list_history() as $num => $line) {
+ foreach ( readline_list_history() as $num => $line ) {
print "$num: $line\n";
}
} else {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class mcTest extends Maintenance {
public function __construct() {
global $wgMemCachedServers;
$iterations = $this->getOption( 'i', 100 );
- if( $this->hasArg() )
+ if ( $this->hasArg() )
$wgMemCachedServers = array( $this->getArg() );
foreach ( $wgMemCachedServers as $server ) {
$this->output( $server . " ", $server );
- $mcc = new MemCachedClientforWiki( array('persistant' => true) );
+ $mcc = new MemCachedClientforWiki( array( 'persistant' => true ) );
$mcc->set_servers( array( $server ) );
$set = 0;
$incr = 0;
$get = 0;
$time_start = $this->microtime_float();
- for ( $i=1; $i<=$iterations; $i++ ) {
+ for ( $i = 1; $i <= $iterations; $i++ ) {
if ( !is_null( $mcc->set( "test$i", $i ) ) ) {
$set++;
}
}
- for ( $i=1; $i<=$iterations; $i++ ) {
+ for ( $i = 1; $i <= $iterations; $i++ ) {
if ( !is_null( $mcc->incr( "test$i", $i ) ) ) {
$incr++;
}
}
- for ( $i=1; $i<=$iterations; $i++ ) {
+ for ( $i = 1; $i <= $iterations; $i++ ) {
$value = $mcc->get( "test$i" );
- if ( $value == $i*2 ) {
+ if ( $value == $i * 2 ) {
$get++;
}
}
* @return float
*/
private function microtime_float() {
- list($usec, $sec) = explode(" ", microtime());
- return ((float)$usec + (float)$sec);
+ list( $usec, $sec ) = explode( " ", microtime() );
+ return ( (float)$usec + (float)$sec );
}
}
# Start from scratch
define( 'MW_NO_EXTENSION_MESSAGES', 1 );
-require_once( dirname( __FILE__ ).'/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
$maintClass = 'MergeMessageFileList';
$mmfl = false;
class MergeMessageFileList extends Maintenance {
function __construct() {
$this->addOption( 'list-file', 'A file containing a list of extension setup files, one per line.', false, true );
$this->addOption( 'output', 'Send output to this file (omit for stdout)', false, true );
- $this->mDescription = 'Merge $wgExtensionMessagesFiles from various extensions to produce a ' .
+ $this->mDescription = 'Merge $wgExtensionMessagesFiles from various extensions to produce a ' .
'single array containing all message files.';
}
include_once( $fileName );
}
fwrite( STDERR, "\n" );
-$s =
- "<" . "?php\n" .
+$s =
+ "<" . "?php\n" .
"## This file is generated by mergeMessageFileList.php. Do not edit it directly.\n\n" .
"if ( defined( 'MW_NO_EXTENSION_MESSAGES' ) ) return;\n\n" .
'$wgExtensionMessagesFiles = ' . var_export( $wgExtensionMessagesFiles, true ) . ";\n\n" .
$dirs = array(
$IP,
- dirname( dirname( __FILE__ ) ),
+ dirname( dirname( __FILE__ ) ),
realpath( $IP )
);
foreach ( $dirs as $dir ) {
- $s = preg_replace(
+ $s = preg_replace(
"/'" . preg_quote( $dir, '/' ) . "([^']*)'/",
- '"$IP\1"',
+ '"$IP\1"',
$s );
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class MigrateUserGroup extends Maintenance {
public function __construct() {
$newGroup = $this->getArg( 1 );
$dbw = wfGetDB( DB_MASTER );
$start = $dbw->selectField( 'user_groups', 'MIN(ug_user)',
- array('ug_group' => $oldGroup), __FUNCTION__ );
+ array( 'ug_group' => $oldGroup ), __FUNCTION__ );
$end = $dbw->selectField( 'user_groups', 'MAX(ug_user)',
- array('ug_group' => $oldGroup), __FUNCTION__ );
- if( $start === null ) {
+ array( 'ug_group' => $oldGroup ), __FUNCTION__ );
+ if ( $start === null ) {
$this->error( "Nothing to do - no users in the '$oldGroup' group", true );
}
# Do remaining chunk
$blockStart = $start;
$blockEnd = $start + $this->mBatchSize - 1;
// Migrate users over in batches...
- while( $blockEnd <= $end ) {
+ while ( $blockEnd <= $end ) {
$this->output( "Doing users $blockStart to $blockEnd\n" );
$dbw->begin();
$dbw->update( 'user_groups',
- array('ug_group' => $newGroup),
- array('ug_group' => $oldGroup,
+ array( 'ug_group' => $newGroup ),
+ array( 'ug_group' => $oldGroup,
"ug_user BETWEEN $blockStart AND $blockEnd" )
);
$count += $dbw->affectedRows();
public function __construct() {
parent::__construct();
- $this->addOption( 'outfile',
- 'File for output. Only a single file may be specified for input.',
+ $this->addOption( 'outfile',
+ 'File for output. Only a single file may be specified for input.',
false, true );
$this->addOption( 'outdir',
- "Directory for output. If this is not specified, and neither is --outfile, then the\n" .
+ "Directory for output. If this is not specified, and neither is --outfile, then the\n" .
"output files will be sent to the same directories as the input files.",
false, true );
$this->mDescription = "Minify a file or set of files.\n\n" .
- "If --outfile is not specified, then the output file names will have a .min extension\n" .
+ "If --outfile is not specified, then the output file names will have a .min extension\n" .
"added, e.g. jquery.js -> jquery.min.js.";
}
* e.g. immobile_namespace for namespaces which can't be moved
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class MoveBatch extends Maintenance {
public function __construct() {
$user = $this->getOption( 'u', 'Move page script' );
$reason = $this->getOption( 'r', '' );
$interval = $this->getOption( 'i', 0 );
- if( $this->hasArg() ) {
+ if ( $this->hasArg() ) {
$file = fopen( $this->getArg(), 'r' );
} else {
$file = $this->getStdin();
}
# Setup
- if( !$file ) {
+ if ( !$file ) {
$this->error( "Unable to read file, exiting", true );
}
$wgUser = User::newFromName( $user );
$this->output( $source->getPrefixedText() . ' --> ' . $dest->getPrefixedText() );
$dbw->begin();
$err = $source->moveTo( $dest, false, $reason );
- if( $err !== true ) {
+ if ( $err !== true ) {
$msg = array_shift( $err[0] );
$this->output( "\nFAILED: " . wfMsg( $msg, $err[0] ) );
}
# Variables / Configuration
#
-if( php_sapi_name() != 'cli' ) {
+if ( php_sapi_name() != 'cli' ) {
echo 'Run me from the command line.';
die( -1 );
}
$svnstat = $mwPath . 'bin/svnstat';
/** where Phpdoc should output documentation */
-#$doxyOutput = '/var/www/mwdoc/';
+# $doxyOutput = '/var/www/mwdoc/';
$doxyOutput = $mwPath . 'docs' . DIRECTORY_SEPARATOR ;
/** MediaWiki subpaths */
-$mwPathI = $mwPath.'includes/';
-$mwPathL = $mwPath.'languages/';
-$mwPathM = $mwPath.'maintenance/';
-$mwPathS = $mwPath.'skins/';
+$mwPathI = $mwPath . 'includes/';
+$mwPathL = $mwPath . 'languages/';
+$mwPathM = $mwPath . 'maintenance/';
+$mwPathS = $mwPath . 'skins/';
/** Variable to get user input */
$input = '';
* Read a line from the shell
* @param $prompt String
*/
-function readaline( $prompt = '' ){
+function readaline( $prompt = '' ) {
print $prompt;
$fp = fopen( "php://stdin", "r" );
$resp = trim( fgets( $fp, 1024 ) );
// http://svnbook.red-bean.com/nightly/en/svn.developer.insidewc.html
$entries = $dir . '/.svn/entries';
- if( !file_exists( $entries ) ) {
+ if ( !file_exists( $entries ) ) {
return false;
}
$content = file( $entries );
// check if file is xml (subversion release <= 1.3) or not (subversion release = 1.4)
- if( preg_match( '/^<\?xml/', $content[0] ) ) {
+ if ( preg_match( '/^<\?xml/', $content[0] ) ) {
// subversion is release <= 1.3
- if( !function_exists( 'simplexml_load_file' ) ) {
+ if ( !function_exists( 'simplexml_load_file' ) ) {
// We could fall back to expat... YUCK
return false;
}
$xml = simplexml_load_file( $entries );
- if( $xml ) {
- foreach( $xml->entry as $entry ) {
- if( $xml->entry[0]['name'] == '' ) {
+ if ( $xml ) {
+ foreach ( $xml->entry as $entry ) {
+ if ( $xml->entry[0]['name'] == '' ) {
// The directory entry should always have a revision marker.
- if( $entry['revision'] ) {
+ if ( $entry['revision'] ) {
return intval( $entry['revision'] );
}
}
* @param $exclude String: Additionals path regex to exlcude
* (LocalSettings.php, AdminSettings.php and .svn directories are always excluded)
*/
-function generateConfigFile( $doxygenTemplate, $outputDirectory, $stripFromPath, $currentVersion, $svnstat, $input, $exclude ){
+function generateConfigFile( $doxygenTemplate, $outputDirectory, $stripFromPath, $currentVersion, $svnstat, $input, $exclude ) {
global $tmpPath;
$template = file_get_contents( $doxygenTemplate );
'{{EXCLUDE}}' => $exclude,
);
$tmpCfg = str_replace( array_keys( $replacements ), array_values( $replacements ), $template );
- $tmpFileName = $tmpPath . 'mwdocgen'. rand() .'.tmp';
- file_put_contents( $tmpFileName , $tmpCfg ) or die("Could not write doxygen configuration to file $tmpFileName\n");
+ $tmpFileName = $tmpPath . 'mwdocgen' . rand() . '.tmp';
+ file_put_contents( $tmpFileName , $tmpCfg ) or die( "Could not write doxygen configuration to file $tmpFileName\n" );
return $tmpFileName;
}
unset( $file );
-if( is_array( $argv ) && isset( $argv[1] ) ) {
+if ( is_array( $argv ) && isset( $argv[1] ) ) {
switch( $argv[1] ) {
case '--all': $input = 0; break;
case '--includes': $input = 1; break;
case '--skins': $input = 4; break;
case '--file':
$input = 5;
- if( isset( $argv[2] ) ) {
+ if ( isset( $argv[2] ) ) {
$file = $argv[2];
}
break;
// TODO : generate a list of paths ))
-if( $input === '' ) {
+if ( $input === '' ) {
echo <<<OPTIONS
Several documentation possibilities:
0 : whole documentation (1 + 2 + 3 + 4)
5 : only a given file
6 : all but the extensions directory
OPTIONS;
- while ( !is_numeric($input) )
+ while ( !is_numeric( $input ) )
{
$input = readaline( "\nEnter your choice [0]:" );
- if($input == '') {
+ if ( $input == '' ) {
$input = 0;
}
}
}
-switch ($input) {
+switch ( $input ) {
case 0: $input = $mwPath; break;
case 1: $input = $mwPathI; break;
case 2: $input = $mwPathL; break;
case 3: $input = $mwPathM; break;
case 4: $input = $mwPathS; break;
case 5:
- if( !isset( $file ) ) {
+ if ( !isset( $file ) ) {
$file = readaline( "Enter file name $mwPath" );
}
- $input = $mwPath.$file;
+ $input = $mwPath . $file;
case 6:
$input = $mwPath;
$exclude = 'extensions';
}
$versionNumber = getSvnRevision( $input );
-if( $versionNumber === false ){ #Not using subversion ?
+if ( $versionNumber === false ) { # Not using subversion ?
$svnstat = ''; # Not really useful if subversion not available
$version = 'trunk'; # FIXME
} else {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class NamespaceConflictChecker extends Maintenance {
public function __construct() {
$prefix = $this->getOption( 'prefix', '' );
$key = intval( $this->getOption( 'key', 0 ) );
- if( $prefix ) {
+ if ( $prefix ) {
$retval = $this->checkPrefix( $key, $prefix, $fix, $suffix );
} else {
$retval = $this->checkAll( $fix, $suffix );
}
- if( $retval ) {
+ if ( $retval ) {
$this->output( "\nLooks good!\n" );
} else {
$this->output( "\nOh noeees\n" );
// List interwikis first, so they'll be overridden
// by any conflicting local namespaces.
- foreach( $this->getInterwikiList() as $prefix ) {
+ foreach ( $this->getInterwikiList() as $prefix ) {
$name = $wgContLang->ucfirst( $prefix );
$spaces[$name] = 0;
}
// Now pull in all canonical and alias namespaces...
- foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
+ foreach ( $wgCanonicalNamespaceNames as $ns => $name ) {
// This includes $wgExtraNamespaces
- if( $name !== '' ) {
+ if ( $name !== '' ) {
$spaces[$name] = $ns;
}
}
- foreach( $wgContLang->getNamespaces() as $ns => $name ) {
- if( $name !== '' ) {
+ foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
+ if ( $name !== '' ) {
$spaces[$name] = $ns;
}
}
- foreach( $wgNamespaceAliases as $name => $ns ) {
+ foreach ( $wgNamespaceAliases as $name => $ns ) {
$spaces[$name] = $ns;
}
- foreach( $wgContLang->getNamespaceAliases() as $name => $ns ) {
+ foreach ( $wgContLang->getNamespaceAliases() as $name => $ns ) {
$spaces[$name] = $ns;
}
// We'll need to check for lowercase keys as well,
// since we're doing case-sensitive searches in the db.
- foreach( $spaces as $name => $ns ) {
+ foreach ( $spaces as $name => $ns ) {
$moreNames = array();
$moreNames[] = $wgContLang->uc( $name );
$moreNames[] = $wgContLang->ucfirst( $wgContLang->lc( $name ) );
$moreNames[] = $wgContLang->ucwords( $wgContLang->lc( $name ) );
$moreNames[] = $wgContLang->ucwordbreaks( $name );
$moreNames[] = $wgContLang->ucwordbreaks( $wgContLang->lc( $name ) );
- if( !$wgCapitalLinks ) {
- foreach( $moreNames as $altName ) {
+ if ( !$wgCapitalLinks ) {
+ foreach ( $moreNames as $altName ) {
$moreNames[] = $wgContLang->lcfirst( $altName );
}
$moreNames[] = $wgContLang->lcfirst( $name );
}
- foreach( array_unique( $moreNames ) as $altName ) {
- if( $altName !== $name ) {
+ foreach ( array_unique( $moreNames ) as $altName ) {
+ if ( $altName !== $name ) {
$spaces[$altName] = $ns;
}
}
asort( $spaces );
$ok = true;
- foreach( $spaces as $name => $ns ) {
+ foreach ( $spaces as $name => $ns ) {
$ok = $this->checkNamespace( $ns, $name, $fix, $suffix ) && $ok;
}
return $ok;
private function getInterwikiList() {
$result = $this->db->select( 'interwiki', array( 'iw_prefix' ) );
$prefixes = array();
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
$prefixes[] = $row->iw_prefix;
}
$this->db->freeResult( $result );
private function checkNamespace( $ns, $name, $fix, $suffix = '' ) {
$conflicts = $this->getConflicts( $ns, $name );
$count = count( $conflicts );
- if( $count == 0 ) {
+ if ( $count == 0 ) {
return true;
}
$ok = true;
- foreach( $conflicts as $row ) {
+ foreach ( $conflicts as $row ) {
$resolvable = $this->reportConflict( $row, $suffix );
$ok = $ok && $resolvable;
- if( $fix && ( $resolvable || $suffix != '' ) ) {
+ if ( $fix && ( $resolvable || $suffix != '' ) ) {
$ok = $this->resolveConflict( $row, $resolvable, $suffix ) && $ok;
}
}
$encNamespace = $this->db->addQuotes( $ns );
$titleSql = "TRIM(LEADING '$prefix:' FROM {$page}_title)";
- if( $ns == 0 ) {
+ if ( $ns == 0 ) {
// An interwiki; try an alternate encoding with '-' for ':'
$titleSql = $this->db->buildConcat( array( "'$prefix-'", $titleSql ) );
}
$result = $this->db->query( $sql, __METHOD__ );
$set = array();
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
$set[] = $row;
}
$this->db->freeResult( $result );
*/
private function reportConflict( $row, $suffix ) {
$newTitle = Title::makeTitleSafe( $row->namespace, $row->title );
- if( is_null($newTitle) || !$newTitle->canExist() ) {
+ if ( is_null( $newTitle ) || !$newTitle->canExist() ) {
// Title is also an illegal title...
// For the moment we'll let these slide to cleanupTitles or whoever.
$this->output( sprintf( "... %d (%d,\"%s\")\n",
$newTitle->getPrefixedText() ) );
$id = $newTitle->getArticleId();
- if( $id ) {
+ if ( $id ) {
$this->output( "... *** cannot resolve automatically; page exists with ID $id ***\n" );
return false;
} else {
* @param $suffix String Suffix to append to the fixed page
*/
private function resolveConflict( $row, $resolvable, $suffix ) {
- if( !$resolvable ) {
+ if ( !$resolvable ) {
$this->output( "... *** old title {$row->title}\n" );
- while( true ) {
+ while ( true ) {
$row->title .= $suffix;
$this->output( "... *** new title {$row->title}\n" );
$title = Title::makeTitleSafe( $row->namespace, $row->title );
}
if ( $id = $title->getArticleId() ) {
$this->output( "... *** page exists with ID $id ***\n" );
- } else {
+ } else {
break;
}
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class nextJobDB extends Maintenance {
public function __construct() {
$pendingDBs = $wgMemc->get( $mckey );
# If we didn't get it from the cache
- if( !$pendingDBs ) {
+ if ( !$pendingDBs ) {
$pendingDBs = $this->getPendingDbs( $type );
$wgMemc->get( $mckey, $pendingDBs, 300 );
}
# If we've got a pending job in a db, display it.
if ( $pendingDBs ) {
- $this->output( $pendingDBs[mt_rand(0, count( $pendingDBs ) - 1)] );
+ $this->output( $pendingDBs[mt_rand( 0, count( $pendingDBs ) - 1 )] );
}
}
$dbsByMaster = array();
foreach ( $wgLocalDatabases as $db ) {
$lb = wfGetLB( $db );
- $dbsByMaster[$lb->getServerName(0)][] = $db;
+ $dbsByMaster[$lb->getServerName( 0 )][] = $db;
}
foreach ( $dbsByMaster as $master => $dbs ) {
* based on nukePage by Rob Church
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class NukeNS extends Maintenance {
public function __construct() {
$n_deleted = 0;
- foreach( $res as $row ) {
- //echo "$ns_name:".$row->page_title, "\n";
+ foreach ( $res as $row ) {
+ // echo "$ns_name:".$row->page_title, "\n";
$title = Title::makeTitle( $ns, $row->page_title );
$id = $title->getArticleID();
$res2 = $dbw->query( "SELECT rev_id FROM $tbl_rev WHERE rev_page = $id" );
$revs = array();
- foreach( $res2 as $row2 ) {
+ foreach ( $res2 as $row2 ) {
$revs[] = $row2->rev_id;
}
$count = count( $revs );
- //skip anything that looks modified (i.e. multiple revs)
+ // skip anything that looks modified (i.e. multiple revs)
if ( $count == 1 ) {
- #echo $title->getPrefixedText(), "\t", $count, "\n";
+ # echo $title->getPrefixedText(), "\t", $count, "\n";
$this->output( "delete: " . $title->getPrefixedText() . "\n" );
- //as much as I hate to cut & paste this, it's a little different, and
- //I already have the id & revs
- if( $delete ) {
+ // as much as I hate to cut & paste this, it's a little different, and
+ // I already have the id & revs
+ if ( $delete ) {
$dbw->query( "DELETE FROM $tbl_pag WHERE page_id = $id" );
$dbw->commit();
// Delete revisions as appropriate
$dbw->commit();
if ( $n_deleted > 0 ) {
- #update statistics - better to decrement existing count, or just count
- #the page table?
+ # update statistics - better to decrement existing count, or just count
+ # the page table?
$pages = $dbw->selectField( 'site_stats', 'ss_total_pages' );
$pages -= $n_deleted;
$dbw->update(
- 'site_stats',
- array( 'ss_total_pages' => $pages ),
+ 'site_stats',
+ array( 'ss_total_pages' => $pages ),
array( 'ss_row_id' => 1 ),
__METHOD__
);
* @author Rob Church <robchur@gmail.com>
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class NukePage extends Maintenance {
public function __construct() {
# Get page ID
$this->output( "Searching for \"$name\"..." );
$title = Title::newFromText( $name );
- if( $title ) {
+ if ( $title ) {
$id = $title->getArticleID();
$real = $title->getPrefixedText();
$isGoodArticle = $title->isContentPage();
# Get corresponding revisions
$this->output( "Searching for revisions..." );
$res = $dbw->query( "SELECT rev_id FROM $tbl_rev WHERE rev_page = $id" );
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$revs[] = $row->rev_id;
}
$count = count( $revs );
$this->output( "found $count.\n" );
# Delete the page record and associated recent changes entries
- if( $delete ) {
+ if ( $delete ) {
$this->output( "Deleting page record..." );
$dbw->query( "DELETE FROM $tbl_pag WHERE page_id = $id" );
$this->output( "done.\n" );
$dbw->commit();
# Delete revisions as appropriate
- if( $delete && $count ) {
+ if ( $delete && $count ) {
$this->output( "Deleting revisions..." );
$this->deleteRevisions( $revs );
$this->output( "done.\n" );
$set = implode( ', ', $ids );
$dbw->query( "DELETE FROM $tbl_rev WHERE rev_id IN ( $set )" );
- $dbw->commit();
+ $dbw->commit();
}
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class Orphans extends Maintenance {
public function __construct() {
*/
private function lockTables( &$db, $extraTable = null ) {
$tbls = array( 'page', 'revision', 'redirect' );
- if( $extraTable )
+ if ( $extraTable )
$tbls[] = $extraTable;
$db->lockTables( array(), $tbls, __METHOD__, false );
}
$page = $dbw->tableName( 'page' );
$revision = $dbw->tableName( 'revision' );
- if( $fix ) {
+ if ( $fix ) {
$this->lockTables( $dbw );
}
SELECT *
FROM $revision LEFT OUTER JOIN $page ON rev_page=page_id
WHERE page_id IS NULL
- ");
+ " );
$orphans = $dbw->numRows( $result );
- if( $orphans > 0 ) {
+ if ( $orphans > 0 ) {
global $wgContLang;
$this->output( "$orphans orphan revisions...\n" );
$this->output( sprintf( "%10s %10s %14s %20s %s\n", 'rev_id', 'rev_page', 'rev_timestamp', 'rev_user_text', 'rev_comment' ) );
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
$comment = ( $row->rev_comment == '' )
? ''
: '(' . $wgContLang->truncate( $row->rev_comment, 40 ) . ')';
$row->rev_timestamp,
$wgContLang->truncate( $row->rev_user_text, 17 ),
$comment ) );
- if( $fix ) {
+ if ( $fix ) {
$dbw->delete( 'revision', array( 'rev_id' => $row->rev_id ) );
}
}
- if( !$fix ) {
+ if ( !$fix ) {
$this->output( "Run again with --fix to remove these entries automatically.\n" );
}
} else {
$this->output( "No orphans! Yay!\n" );
}
- if( $fix ) {
+ if ( $fix ) {
$dbw->unlockTables();
}
}
$page = $dbw->tableName( 'page' );
$revision = $dbw->tableName( 'revision' );
- if( $fix ) {
+ if ( $fix ) {
$this->lockTables( $dbw );
}
SELECT *
FROM $page LEFT OUTER JOIN $revision ON page_latest=rev_id
WHERE rev_id IS NULL
- ");
+ " );
$widows = $dbw->numRows( $result );
- if( $widows > 0 ) {
+ if ( $widows > 0 ) {
global $wgContLang;
$this->output( "$widows childless pages...\n" );
$this->output( sprintf( "%10s %11s %2s %s\n", 'page_id', 'page_latest', 'ns', 'page_title' ) );
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
printf( "%10d %11d %2d %s\n",
$row->page_id,
$row->page_latest,
$row->page_namespace,
$row->page_title );
- if( $fix ) {
+ if ( $fix ) {
$dbw->delete( 'page', array( 'page_id' => $row->page_id ) );
}
}
- if( !$fix ) {
+ if ( !$fix ) {
$this->output( "Run again with --fix to remove these entries automatically.\n" );
}
} else {
$this->output( "No childless pages! Yay!\n" );
}
- if( $fix ) {
+ if ( $fix ) {
$dbw->unlockTables();
}
}
$revision = $dbw->tableName( 'revision' );
$text = $dbw->tableName( 'text' );
- if( $fix ) {
+ if ( $fix ) {
$dbw->lockTables( $dbw, 'text' );
}
$result = $dbw->query( "
SELECT *
FROM $page LEFT OUTER JOIN $revision ON page_latest=rev_id
- ");
+ " );
$found = 0;
- foreach( $result as $row ) {
+ foreach ( $result as $row ) {
$result2 = $dbw->query( "
SELECT MAX(rev_timestamp) as max_timestamp
FROM $revision
" );
$row2 = $dbw->fetchObject( $result2 );
$dbw->freeResult( $result2 );
- if( $row2 ) {
- if( $row->rev_timestamp != $row2->max_timestamp ) {
- if( $found == 0 ) {
+ if ( $row2 ) {
+ if ( $row->rev_timestamp != $row2->max_timestamp ) {
+ if ( $found == 0 ) {
$this->output( sprintf( "%10s %10s %14s %14s\n",
'page_id', 'rev_id', 'timestamp', 'max timestamp' ) );
}
$row->page_latest,
$row->rev_timestamp,
$row2->max_timestamp ) );
- if( $fix ) {
+ if ( $fix ) {
# ...
$maxId = $dbw->selectField(
'revision',
}
}
- if( $found ) {
+ if ( $found ) {
$this->output( "Found $found pages with incorrect latest revision.\n" );
} else {
$this->output( "No pages with incorrect latest revision. Yay!\n" );
}
- if( !$fix && $found > 0 ) {
+ if ( !$fix && $found > 0 ) {
$this->output( "Run again with --fix to remove these entries automatically.\n" );
}
- if( $fix ) {
+ if ( $fix ) {
$dbw->unlockTables();
}
}
print "/*!40100 set old_passwords=1 */;\n";
print "/*!40100 set global old_passwords=1 */;\n";
-foreach( $hosts as $host ) {
+foreach ( $hosts as $host ) {
print "--\n-- $host\n--\n";
print "\n-- wikiuser\n\n";
print "GRANT REPLICATION CLIENT,PROCESS ON *.* TO 'wikiuser'@'$host' IDENTIFIED BY '$wikiuser_pass';\n";
print "GRANT ALL PRIVILEGES ON `boardvote%`.* TO 'wikiuser'@'$host' IDENTIFIED BY '$wikiuser_pass';\n";
- foreach( $databases as $db ) {
+ foreach ( $databases as $db ) {
print "GRANT SELECT, INSERT, UPDATE, DELETE ON `$db`.* TO 'wikiuser'@'$host' IDENTIFIED BY '$wikiuser_pass';\n";
}
$optionsWithArgs = array( 'regex', 'seed', 'setversion' );
if ( !defined( "NO_COMMAND_LINE" ) ) {
- require_once( dirname(__FILE__) . '/commandLine.inc' );
+ require_once( dirname( __FILE__ ) . '/commandLine.inc' );
}
require_once( "$IP/maintenance/parserTestsParserHook.php" );
require_once( "$IP/maintenance/parserTestsStaticParserHook.php" );
global $options;
# Only colorize output if stdout is a terminal.
- $this->color = !wfIsWindows() && posix_isatty(1);
+ $this->color = !wfIsWindows() && posix_isatty( 1 );
- if( isset( $options['color'] ) ) {
+ if ( isset( $options['color'] ) ) {
switch( $options['color'] ) {
case 'no':
$this->color = false;
$this->showOutput = isset( $options['show-output'] );
- if (isset($options['regex'])) {
+ if ( isset( $options['regex'] ) ) {
if ( isset( $options['record'] ) ) {
echo "Warning: --record cannot be used with --regex, disabling --record\n";
unset( $options['record'] );
$this->regex = '';
}
- if( isset( $options['record'] ) ) {
+ if ( isset( $options['record'] ) ) {
$this->recorder = new DbTestRecorder( $this );
- } elseif( isset( $options['compare'] ) ) {
+ } elseif ( isset( $options['compare'] ) ) {
$this->recorder = new DbTestPreviewer( $this );
- } elseif( isset( $options['upload'] ) ) {
+ } elseif ( isset( $options['upload'] ) ) {
$this->recorder = new RemoteTestRecorder( $this );
- } elseif( class_exists( 'PHPUnitTestRecorder' ) ) {
+ } elseif ( class_exists( 'PHPUnitTestRecorder' ) ) {
$this->recorder = new PHPUnitTestRecorder( $this );
} else {
$this->recorder = new TestRecorder( $this );
/**
* Remove last character if it is a newline
*/
- public function chomp($s) {
- if (substr($s, -1) === "\n") {
- return substr($s, 0, -1);
+ public function chomp( $s ) {
+ if ( substr( $s, -1 ) === "\n" ) {
+ return substr( $s, 0, -1 );
}
else {
return $s;
*/
function getFuzzInput( $filenames ) {
$dict = '';
- foreach( $filenames as $filename ) {
+ foreach ( $filenames as $filename ) {
$contents = file_get_contents( $filename );
preg_match_all( '/!!\s*input\n(.*?)\n!!\s*result/s', $contents, $matches );
foreach ( $matches[1] as $match ) {
function getMemoryBreakdown() {
$memStats = array();
foreach ( $GLOBALS as $name => $value ) {
- $memStats['$'.$name] = strlen( serialize( $value ) );
+ $memStats['$' . $name] = strlen( serialize( $value ) );
}
$classes = get_declared_classes();
foreach ( $classes as $class ) {
$this->recorder->start();
$this->setupDatabase();
$ok = true;
- foreach( $filenames as $filename ) {
+ foreach ( $filenames as $filename ) {
$tests = new TestFileIterator( $filename, $this );
$ok = $this->runTests( $tests ) && $ok;
}
return $ok;
}
- function runTests($tests) {
+ function runTests( $tests ) {
$ok = true;
- foreach($tests as $i => $t) {
+ foreach ( $tests as $i => $t ) {
$result =
- $this->runTest($t['test'], $t['input'], $t['result'], $t['options'], $t['config']);
+ $this->runTest( $t['test'], $t['input'], $t['result'], $t['options'], $t['config'] );
$ok = $ok && $result;
$this->recorder->record( $t['test'], $result );
}
/**
* Get a Parser object
*/
- function getParser($preprocessor = null) {
+ function getParser( $preprocessor = null ) {
global $wgParserConf;
$class = $wgParserConf['class'];
- $parser = new $class( array( 'preprocessorClass'=>$preprocessor ) + $wgParserConf );
- foreach( $this->hooks as $tag => $callback ) {
+ $parser = new $class( array( 'preprocessorClass' => $preprocessor ) + $wgParserConf );
+ foreach ( $this->hooks as $tag => $callback ) {
$parser->setHook( $tag, $callback );
}
- foreach( $this->functionHooks as $tag => $bits ) {
+ foreach ( $this->functionHooks as $tag => $bits ) {
list( $callback, $flags ) = $bits;
$parser->setFunctionHook( $tag, $callback, $flags );
}
* @return Boolean
*/
public function runTest( $desc, $input, $result, $opts, $config ) {
- if( $this->showProgress ) {
+ if ( $this->showProgress ) {
$this->showTesting( $desc );
}
$opts = $this->parseOptions( $opts );
- $this->setupGlobals($opts, $config);
+ $this->setupGlobals( $opts, $config );
$user = new User();
$options = ParserOptions::newFromUser( $user );
$m = array();
- if (isset( $opts['title'] ) ) {
+ if ( isset( $opts['title'] ) ) {
$titleText = $opts['title'];
}
else {
$title = Title::newFromText( $titleText );
$matches = array();
- if( isset( $opts['pst'] ) ) {
+ if ( isset( $opts['pst'] ) ) {
$out = $parser->preSaveTransform( $input, $title, $user, $options );
- } elseif( isset( $opts['msg'] ) ) {
+ } elseif ( isset( $opts['msg'] ) ) {
$out = $parser->transformMsg( $input, $options );
- } elseif( isset( $opts['section'] ) ) {
+ } elseif ( isset( $opts['section'] ) ) {
$section = $opts['section'];
$out = $parser->getSection( $input, $section );
- } elseif( isset( $opts['replace'] ) ) {
+ } elseif ( isset( $opts['replace'] ) ) {
$section = $opts['replace'][0];
$replace = $opts['replace'][1];
$out = $parser->replaceSection( $input, $section, $replace );
- } elseif( isset( $opts['comment'] ) ) {
+ } elseif ( isset( $opts['comment'] ) ) {
$linker = $user->getSkin();
$out = $linker->formatComment( $input, $title, $local );
- } elseif( isset( $opts['preload'] ) ) {
+ } elseif ( isset( $opts['preload'] ) ) {
$out = $parser->getpreloadText( $input, $title, $options );
} else {
$output = $parser->parse( $input, $title, $options, true, true, 1337 );
$out = $output->getText();
if ( isset( $opts['showtitle'] ) ) {
- if($output->getTitleText()) $title = $output->getTitleText();
+ if ( $output->getTitleText() ) $title = $output->getTitleText();
$out = "$title\n$out";
}
- if (isset( $opts['ill'] ) ) {
+ if ( isset( $opts['ill'] ) ) {
$out = $this->tidy( implode( ' ', $output->getLanguageLinks() ) );
- } elseif( isset( $opts['cat'] ) ) {
+ } elseif ( isset( $opts['cat'] ) ) {
global $wgOut;
- $wgOut->addCategoryLinks($output->getCategories());
+ $wgOut->addCategoryLinks( $output->getCategories() );
$cats = $wgOut->getCategoryLinks();
if ( isset( $cats['normal'] ) ) {
$out = $this->tidy( implode( ' ', $cats['normal'] ) );
}
}
- $result = $this->tidy($result);
+ $result = $this->tidy( $result );
}
$this->teardownGlobals();
- if( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
+ if ( $result === $out && ( $noxml === true || $this->wellFormed( $out ) ) ) {
return $this->showSuccess( $desc );
} else {
return $this->showFailure( $desc, $result, $out );
*/
private static function getOptionValue( $key, $opts, $default ) {
$key = strtolower( $key );
- if( isset( $opts[$key] ) ) {
+ if ( isset( $opts[$key] ) ) {
return $opts[$key];
} else {
return $default;
)?
/x';
- if( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
- foreach( $matches as $bits ) {
+ if ( preg_match_all( $regex, $instring, $matches, PREG_SET_ORDER ) ) {
+ foreach ( $matches as $bits ) {
$match = array_shift( $bits );
$key = strtolower( array_shift( $bits ) );
- if( count( $bits ) == 0 ) {
+ if ( count( $bits ) == 0 ) {
$opts[$key] = true;
- } elseif( count( $bits ) == 1 ) {
+ } elseif ( count( $bits ) == 1 ) {
$opts[$key] = $this->cleanupOption( array_shift( $bits ) );
} else {
// Array!
}
private function cleanupOption( $opt ) {
- if( substr( $opt, 0, 1 ) == '"' ) {
+ if ( substr( $opt, 0, 1 ) == '"' ) {
return substr( $opt, 1, -1 );
}
- if( substr( $opt, 0, 2 ) == '[[' ) {
+ if ( substr( $opt, 0, 2 ) == '[[' ) {
return substr( $opt, 2, -2 );
}
return $opt;
* Set up the global variables for a consistent environment for each test.
* Ideally this should replace the global configuration entirely.
*/
- private function setupGlobals($opts = '', $config = '') {
+ private function setupGlobals( $opts = '', $config = '' ) {
global $wgDBtype;
- if( !isset( $this->uploadDir ) ) {
+ if ( !isset( $this->uploadDir ) ) {
$this->uploadDir = $this->setupUploadDir();
}
'wgAllowMicrodataAttributes' => true,
);
- if ($config) {
+ if ( $config ) {
$configLines = explode( "\n", $config );
- foreach( $configLines as $line ) {
+ foreach ( $configLines as $line ) {
list( $var, $value ) = explode( '=', $line, 2 );
- $settings[$var] = eval("return $value;" );
+ $settings[$var] = eval( "return $value;" );
}
}
$this->savedGlobals = array();
- foreach( $settings as $var => $val ) {
- if( array_key_exists( $var, $GLOBALS ) ) {
+ foreach ( $settings as $var => $val ) {
+ if ( array_key_exists( $var, $GLOBALS ) ) {
$this->savedGlobals[$var] = $GLOBALS[$var];
}
$GLOBALS[$var] = $val;
*/
private function listTables() {
global $wgDBtype;
- $tables = array('user', 'page', 'page_restrictions',
+ $tables = array( 'user', 'page', 'page_restrictions',
'protected_titles', 'revision', 'text', 'pagelinks', 'imagelinks',
'categorylinks', 'templatelinks', 'externallinks', 'langlinks', 'iwlinks',
'site_stats', 'hitcounter', 'ipblocks', 'image', 'oldimage',
'archive', 'user_groups', 'page_props', 'category'
);
- if ($wgDBtype === 'mysql')
+ if ( $wgDBtype === 'mysql' )
array_push( $tables, 'searchindex' );
// Allow extensions to add to the list of tables to duplicate;
if ( $this->databaseSetupDone ) {
return;
}
- if ( $wgDBprefix === 'parsertest_' || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_')) {
+ if ( $wgDBprefix === 'parsertest_' || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) ) {
throw new MWException( 'setupDatabase should be called before setupGlobals' );
}
$this->databaseSetupDone = true;
# Create new table
$db->duplicateTableStructure( $oldTableName, $newTableName, $temporary );
}
- if ($wgDBtype == 'oracle')
- $db->query('BEGIN FILL_WIKI_INFO; END;');
+ if ( $wgDBtype == 'oracle' )
+ $db->query( 'BEGIN FILL_WIKI_INFO; END;' );
$this->changePrefix( $wgDBtype != 'oracle' ? 'parsertest_' : 'pt_' );
) );
- if ($wgDBtype == 'oracle') {
+ if ( $wgDBtype == 'oracle' ) {
# Insert 0 and 1 user_ids to prevent FK violations
- #Anonymous user
+ # Anonymous user
$db->insert( 'user', array(
'user_id' => 0,
- 'user_name' => 'Anonymous') );
+ 'user_name' => 'Anonymous' ) );
# Hack-on-Hack: Insert a test user to be able to insert an image
$db->insert( 'user', array(
'user_id' => 1,
- 'user_name' => 'Tester') );
+ 'user_name' => 'Tester' ) );
}
# Hack: Insert an image to work with
private function teardownGlobals() {
RepoGroup::destroySingleton();
LinkCache::singleton()->clear();
- foreach( $this->savedGlobals as $var => $val ) {
+ foreach ( $this->savedGlobals as $var => $val ) {
$GLOBALS[$var] = $val;
}
- if( isset( $this->uploadDir ) ) {
+ if ( isset( $this->uploadDir ) ) {
$this->teardownUploadDir( $this->uploadDir );
unset( $this->uploadDir );
}
* @param $files Array: full paths to files to delete.
*/
private static function deleteFiles( $files ) {
- foreach( $files as $file ) {
- if( file_exists( $file ) ) {
+ foreach ( $files as $file ) {
+ if ( file_exists( $file ) ) {
unlink( $file );
}
}
* @param $dirs Array: full paths to directories to delete.
*/
private static function deleteDirs( $dirs ) {
- foreach( $dirs as $dir ) {
- if( is_dir( $dir ) ) {
+ foreach ( $dirs as $dir ) {
+ if ( is_dir( $dir ) ) {
rmdir( $dir );
}
}
* @return Boolean
*/
protected function showSuccess( $desc ) {
- if( $this->showProgress ) {
+ if ( $this->showProgress ) {
print $this->term->color( '1;32' ) . 'PASSED' . $this->term->reset() . "\n";
}
return true;
* @return Boolean
*/
protected function showFailure( $desc, $result, $html ) {
- if( $this->showFailure ) {
- if( !$this->showProgress ) {
+ if ( $this->showFailure ) {
+ if ( !$this->showProgress ) {
# In quiet mode we didn't show the 'Testing' message before the
# test, in case it succeeded. Show it now:
$this->showTesting( $desc );
if ( $this->showOutput ) {
print "--- Expected ---\n$result\n--- Actual ---\n$html\n";
}
- if( $this->showDiffs ) {
+ if ( $this->showDiffs ) {
print $this->quickDiff( $result, $html );
- if( !$this->wellFormed( $html ) ) {
+ if ( !$this->wellFormed( $html ) ) {
print "XML error: $this->mXmlError\n";
}
}
* @param $outFileTail String: tailing for the output file name
* @return String
*/
- protected function quickDiff( $input, $output, $inFileTail='expected', $outFileTail='actual' ) {
+ protected function quickDiff( $input, $output, $inFileTail = 'expected', $outFileTail = 'actual' ) {
$prefix = wfTempDir() . "/mwParser-" . mt_rand();
$infile = "$prefix-$inFileTail";
*
* @param $path String
*/
- public function showRunFile( $path ){
+ public function showRunFile( $path ) {
print $this->term->color( 1 ) .
"Reading tests from \"$path\"..." .
$this->term->reset() .
* @param $text String: the article text
* @param $line Integer: the input line number, for reporting errors
*/
- public function addArticle($name, $text, $line) {
+ public function addArticle( $name, $text, $line ) {
$this->setupGlobals();
$title = Title::newFromText( $name );
- if ( is_null($title) ) {
+ if ( is_null( $title ) ) {
wfDie( "invalid title at line $line\n" );
}
$aid = $title->getArticleID( GAID_FOR_UPDATE );
- if ($aid != 0) {
+ if ( $aid != 0 ) {
wfDie( "duplicate article '$name' at line $line\n" );
}
- $art = new Article($title);
- $art->insertNewArticle($text, '', false, false );
+ $art = new Article( $title );
+ $art->insertNewArticle( $text, '', false, false );
$this->teardownGlobals();
}
*/
public function requireHook( $name ) {
global $wgParser;
- $wgParser->firstCallInit( ); //make sure hooks are loaded.
- if( isset( $wgParser->mTagHooks[$name] ) ) {
+ $wgParser->firstCallInit( ); // make sure hooks are loaded.
+ if ( isset( $wgParser->mTagHooks[$name] ) ) {
$this->hooks[$name] = $wgParser->mTagHooks[$name];
} else {
wfDie( "This test suite requires the '$name' hook extension.\n" );
*/
public function requireFunctionHook( $name ) {
global $wgParser;
- $wgParser->firstCallInit( ); //make sure hooks are loaded.
- if( isset( $wgParser->mFunctionHooks[$name] ) ) {
+ $wgParser->firstCallInit( ); // make sure hooks are loaded.
+ if ( isset( $wgParser->mFunctionHooks[$name] ) ) {
$this->functionHooks[$name] = $wgParser->mFunctionHooks[$name];
} else {
wfDie( "This test suite requires the '$name' function hook extension.\n" );
*/
private function tidy( $text ) {
global $wgUseTidy;
- if ($wgUseTidy) {
- $text = Parser::tidy($text);
+ if ( $wgUseTidy ) {
+ $text = Parser::tidy( $text );
}
return $text;
}
# case folding violates XML standard, turn it off
xml_parser_set_option( $parser, XML_OPTION_CASE_FOLDING, false );
- if( !xml_parse( $parser, $html, true ) ) {
+ if ( !xml_parse( $parser, $html, true ) ) {
$err = xml_error_string( xml_get_error_code( $parser ) );
$position = xml_get_current_byte_index( $parser );
$fragment = $this->extractFragment( $html, $position );
function record( $test, $result ) {
$this->total++;
- $this->success += ($result ? 1 : 0);
+ $this->success += ( $result ? 1 : 0 );
}
function end() {
}
function report() {
- if( $this->total > 0 ) {
+ if ( $this->total > 0 ) {
$this->reportPercentage( $this->success, $this->total );
} else {
wfDie( "No tests found.\n" );
function reportPercentage( $success, $total ) {
$ratio = wfPercent( 100 * $success / $total );
print $this->term->color( 1 ) . "Passed $success of $total tests ($ratio)... ";
- if( $success == $total ) {
+ if ( $success == $total ) {
print $this->term->color( 32 ) . "ALL TESTS PASSED!";
} else {
$failed = $total - $success ;
print $this->term->color( 31 ) . "$failed tests failed!";
}
print $this->term->reset() . "\n";
- return ($success == $total);
+ return ( $success == $total );
}
}
class DbTestPreviewer extends TestRecorder {
- protected $lb; ///< Database load balancer
- protected $db; ///< Database connection to the main DB
- protected $curRun; ///< run ID number for the current run
- protected $prevRun; ///< run ID number for the previous run, if any
- protected $results; ///< Result array
+ protected $lb; // /< Database load balancer
+ protected $db; // /< Database connection to the main DB
+ protected $curRun; // /< run ID number for the current run
+ protected $prevRun; // /< run ID number for the previous run, if any
+ protected $results; // /< Result array
/**
* This should be called before the table prefix is changed
global $wgDBtype;
parent::start();
- if( ! $this->db->tableExists( 'testrun' )
+ if ( ! $this->db->tableExists( 'testrun' )
or ! $this->db->tableExists( 'testitem' ) )
{
print "WARNING> `testrun` table not found in database.\n";
}
function report() {
- if( $this->prevRun ) {
+ if ( $this->prevRun ) {
// f = fail, p = pass, n = nonexistent
// codes show before then after
$table = array(
# Write out results
foreach ( $table as $code => $label ) {
- if( !empty( $breakdown[$code] ) ) {
- $count = count($breakdown[$code]);
+ if ( !empty( $breakdown[$code] ) ) {
+ $count = count( $breakdown[$code] );
printf( "\n%4d %s\n", $count, $label );
- foreach ($breakdown[$code] as $differing_test_name => $statusInfo) {
+ foreach ( $breakdown[$code] as $differing_test_name => $statusInfo ) {
print " * $differing_test_name [$statusInfo]\n";
}
}
** Could help to track down when regressions were introduced, as distinct from tests
** which have never passed (which are more change requests than regressions).
*/
- private function getTestStatusInfo($testname, $after) {
+ private function getTestStatusInfo( $testname, $after ) {
// If we're looking at a test that has just been removed, then say when it first appeared.
if ( $after == 'n' ) {
// See when this test last had a different result to what we're seeing now.
$conds = array(
'ti_name' => $testname,
- 'ti_success' => ($after == 'f' ? "1" : "0") );
+ 'ti_success' => ( $after == 'f' ? "1" : "0" ) );
if ( $this->curRun ) {
$conds[] = "ti_run != " . $this->db->addQuotes ( $this->curRun );
}
// If no record of ever having had a different result.
if ( is_null ( $changedRun ) ) {
- if ($after == "f") {
+ if ( $after == "f" ) {
return "Has never passed";
} else {
return "Has never failed";
__METHOD__ );
$post = $this->db->selectRow ( 'testrun',
array( 'tr_date', 'tr_mw_version' ),
- array( "tr_id > " . $this->db->addQuotes ( $changedRun) ),
+ array( "tr_id > " . $this->db->addQuotes ( $changedRun ) ),
__METHOD__,
array( "LIMIT" => 1, "ORDER BY" => 'tr_id' )
);
global $wgDBtype, $options;
$this->db->begin();
- if( ! $this->db->tableExists( 'testrun' )
+ if ( ! $this->db->tableExists( 'testrun' )
or ! $this->db->tableExists( 'testitem' ) )
{
print "WARNING> `testrun` table not found in database. Trying to create table.\n";
- if ($wgDBtype === 'postgres')
- $this->db->sourceFile( dirname(__FILE__) . '/testRunner.postgres.sql' );
- elseif ($wgDBtype === 'oracle')
- $this->db->sourceFile( dirname(__FILE__) . '/testRunner.ora.sql' );
+ if ( $wgDBtype === 'postgres' )
+ $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.postgres.sql' );
+ elseif ( $wgDBtype === 'oracle' )
+ $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.ora.sql' );
else
- $this->db->sourceFile( dirname(__FILE__) . '/testRunner.sql' );
+ $this->db->sourceFile( dirname( __FILE__ ) . '/testRunner.sql' );
echo "OK, resuming.\n";
}
'tr_uname' => php_uname()
),
__METHOD__ );
- if ($wgDBtype === 'postgres')
- $this->curRun = $this->db->currentSequenceValue('testrun_id_seq');
+ if ( $wgDBtype === 'postgres' )
+ $this->curRun = $this->db->currentSequenceValue( 'testrun_id_seq' );
else
$this->curRun = $this->db->insertId();
}
* "abort" - something went horribly awry
* @param $results array of test name => true/false
*/
- function ping( $status, $results=false ) {
+ function ping( $status, $results = false ) {
global $wgParserTestRemote, $IP;
$remote = $wgParserTestRemote;
$revId = SpecialVersion::getSvnRevision( $IP );
$jsonResults = json_encode( $results );
- if( !$remote ) {
+ if ( !$remote ) {
print "Can't do remote upload without configuring \$wgParserTestRemote!\n";
exit( 1 );
}
$revId,
$status,
);
- if( $status == "complete" ) {
+ if ( $status == "complete" ) {
$message[] = $jsonResults;
}
$hmac = hash_hmac( "sha1", implode( "|", $message ), $remote['secret'] );
'status' => $status,
'hmac' => $hmac,
);
- if( $status == "complete" ) {
+ if ( $status == "complete" ) {
$postData['results'] = $jsonResults;
}
$response = $this->post( $remote['api-url'], $postData );
- if( $response === false ) {
+ if ( $response === false ) {
print "CodeReview info upload failed to reach server.\n";
exit( 1 );
}
$responseData = FormatJson::decode( $response, true );
- if( !is_array( $responseData ) ) {
+ if ( !is_array( $responseData ) ) {
print "CodeReview API response not recognized...\n";
wfDebug( "Unrecognized CodeReview API response: $response\n" );
exit( 1 );
}
- if( isset( $responseData['error'] ) ) {
+ if ( isset( $responseData['error'] ) ) {
$code = $responseData['error']['code'];
$info = $responseData['error']['info'];
print "CodeReview info upload failed: $code $info\n";
}
function post( $url, $data ) {
- return Http::post( $url, array( 'postData' => $data) );
+ return Http::post( $url, array( 'postData' => $data ) );
}
}
global $IP;
$this->file = $file;
- $this->fh = fopen($this->file, "rt");
- if( !$this->fh ) {
+ $this->fh = fopen( $this->file, "rt" );
+ if ( !$this->fh ) {
wfDie( "Couldn't open file '$file'\n" );
}
$this->parser = $parser;
- if( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
+ if ( $this->parser ) $this->parser->showRunFile( wfRelativePath( $this->file, $IP ) );
$this->lineNum = $this->index = 0;
}
}
function rewind() {
- if(fseek($this->fh, 0)) {
+ if ( fseek( $this->fh, 0 ) ) {
wfDie( "Couldn't fseek to the start of '$filename'\n" );
}
$this->index = -1;
}
function next() {
- if($this->readNextTest()) {
+ if ( $this->readNextTest() ) {
$this->index++;
return true;
} else {
$data = array();
$section = null;
- while( false !== ($line = fgets( $this->fh ) ) ) {
+ while ( false !== ( $line = fgets( $this->fh ) ) ) {
$this->lineNum++;
$matches = array();
- if( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
+ if ( preg_match( '/^!!\s*(\w+)/', $line, $matches ) ) {
$section = strtolower( $matches[1] );
- if( $section == 'endarticle') {
- if( !isset( $data['text'] ) ) {
+ if ( $section == 'endarticle' ) {
+ if ( !isset( $data['text'] ) ) {
wfDie( "'endarticle' without 'text' at line {$this->lineNum} of $filename\n" );
}
- if( !isset( $data['article'] ) ) {
+ if ( !isset( $data['article'] ) ) {
wfDie( "'endarticle' without 'article' at line {$this->lineNum} of $filename\n" );
}
- if( $this->parser ) {
- $this->parser->addArticle($this->parser->chomp($data['article']), $this->parser->chomp($data['text']),
- $this->lineNum);
+ if ( $this->parser ) {
+ $this->parser->addArticle( $this->parser->chomp( $data['article'] ), $this->parser->chomp( $data['text'] ),
+ $this->lineNum );
}
$data = array();
$section = null;
continue;
}
- if( $section == 'endhooks' ) {
- if( !isset( $data['hooks'] ) ) {
+ if ( $section == 'endhooks' ) {
+ if ( !isset( $data['hooks'] ) ) {
wfDie( "'endhooks' without 'hooks' at line {$this->lineNum} of $filename\n" );
}
- foreach( explode( "\n", $data['hooks'] ) as $line ) {
+ foreach ( explode( "\n", $data['hooks'] ) as $line ) {
$line = trim( $line );
- if( $line ) {
- if( $this->parser ) $this->parser->requireHook( $line );
+ if ( $line ) {
+ if ( $this->parser ) $this->parser->requireHook( $line );
}
}
$data = array();
$section = null;
continue;
}
- if( $section == 'endfunctionhooks' ) {
- if( !isset( $data['functionhooks'] ) ) {
+ if ( $section == 'endfunctionhooks' ) {
+ if ( !isset( $data['functionhooks'] ) ) {
wfDie( "'endfunctionhooks' without 'functionhooks' at line {$this->lineNum} of $filename\n" );
}
- foreach( explode( "\n", $data['functionhooks'] ) as $line ) {
+ foreach ( explode( "\n", $data['functionhooks'] ) as $line ) {
$line = trim( $line );
- if( $line ) {
- if( $this->parser ) $this->parser->requireFunctionHook( $line );
+ if ( $line ) {
+ if ( $this->parser ) $this->parser->requireFunctionHook( $line );
}
}
$data = array();
$section = null;
continue;
}
- if( $section == 'end' ) {
- if( !isset( $data['test'] ) ) {
+ if ( $section == 'end' ) {
+ if ( !isset( $data['test'] ) ) {
wfDie( "'end' without 'test' at line {$this->lineNum} of $filename\n" );
}
- if( !isset( $data['input'] ) ) {
+ if ( !isset( $data['input'] ) ) {
wfDie( "'end' without 'input' at line {$this->lineNum} of $filename\n" );
}
- if( !isset( $data['result'] ) ) {
+ if ( !isset( $data['result'] ) ) {
wfDie( "'end' without 'result' at line {$this->lineNum} of $filename\n" );
}
- if( !isset( $data['options'] ) ) {
+ if ( !isset( $data['options'] ) ) {
$data['options'] = '';
}
- if (!isset( $data['config'] ) )
+ if ( !isset( $data['config'] ) )
$data['config'] = '';
if ( $this->parser
- && ((preg_match('/\\bdisabled\\b/i', $data['options']) && !$this->parser->runDisabled)
- || !preg_match("/".$this->parser->regex."/i", $data['test'])) ) {
+ && ( ( preg_match( '/\\bdisabled\\b/i', $data['options'] ) && !$this->parser->runDisabled )
+ || !preg_match( "/" . $this->parser->regex . "/i", $data['test'] ) ) ) {
# disabled test
$data = array();
$section = null;
continue;
}
if ( $this->parser &&
- preg_match('/\\bmath\\b/i', $data['options']) && !$this->parser->savedGlobals['wgUseTeX'] ) {
+ preg_match( '/\\bmath\\b/i', $data['options'] ) && !$this->parser->savedGlobals['wgUseTeX'] ) {
# don't run math tests if $wgUseTeX is set to false in LocalSettings
$data = array();
$section = null;
continue;
}
- if( $this->parser ) {
+ if ( $this->parser ) {
$this->test = array(
'test' => $this->parser->chomp( $data['test'] ),
'input' => $this->parser->chomp( $data['input'] ),
}
return true;
}
- if ( isset ($data[$section] ) ) {
+ if ( isset ( $data[$section] ) ) {
wfDie( "duplicate section '$section' at line {$this->lineNum} of $filename\n" );
}
$data[$section] = '';
continue;
}
- if( $section ) {
+ if ( $section ) {
$data[$section] .= $line;
}
}
*/
/** */
-require('parserTests.inc');
+require( 'parserTests.inc' );
-if( isset( $options['help'] ) ) {
+if ( isset( $options['help'] ) ) {
echo <<<ENDS
MediaWiki $wgVersion parser test suite
Usage: php parserTests.php [options...]
$wgTitle = Title::newFromText( 'Parser test script do not use' );
$tester = new ParserTest();
-if( isset( $options['file'] ) ) {
+if ( isset( $options['file'] ) ) {
$files = array( $options['file'] );
} else {
// Default parser tests and any set from extensions or local config
$tester->fuzzTest( $files );
} else {
$ok = $tester->runTestsFromFiles( $files );
- exit ($ok ? 0 : 1);
+ exit ( $ok ? 0 : 1 );
}
$wgHooks['ParserGetVariableValueTs'][] = 'wfParserTimeSetup';
function wfParserTimeSetup( &$parser, &$ts ) {
- $ts = 123; //$ perl -le 'print scalar localtime 123' ==> Thu Jan 1 00:02:03 1970
-
+ $ts = 123; // $ perl -le 'print scalar localtime 123' ==> Thu Jan 1 00:02:03 1970
+
return true;
}
if ( ! count( $argv ) ) {
$parser->static_tag_buf = $in;
return '';
- } else if ( count( $argv ) === 1 && isset( $argv['action'] )
- && $argv['action'] === 'flush' && $in === null )
+ } else if ( count( $argv ) === 1 && isset( $argv['action'] )
+ && $argv['action'] === 'flush' && $in === null )
{
// Clear the buffer, we probably don't need to
if ( isset( $parser->static_tag_buf ) ) {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class PatchSql extends Maintenance {
public function __construct() {
public function execute() {
$dbw = wfGetDB( DB_MASTER );
- foreach( $this->mArgs as $arg ) {
+ foreach ( $this->mArgs as $arg ) {
$files = array(
$arg,
DatabaseBase::patchPath( $arg ),
DatabaseBase::patchPath( "patch-$arg.sql" ),
);
- foreach( $files as $file ) {
- if( file_exists( $file ) ) {
+ foreach ( $files as $file ) {
+ if ( file_exists( $file ) ) {
$this->output( "$file ...\n" );
$dbw->sourceFile( $file );
continue 2;
$optionsWithArgs = array( 'begin', 'max-slave-lag', 'throttle' );
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class PopulateCategory extends Maintenance {
When the script has finished, it will make a note of this in the database, and
will not run again without the --force option.
TEXT;
-#'
+# '
$this->addOption( 'begin', 'Only do categories whose names are alphabetically after the provided name', false, true );
$this->addOption( 'max-slave-lag', 'If slave lag exceeds this many seconds, wait until it drops before continuing. Default: 10', false, true );
$this->addOption( 'throttle', 'Wait this many milliseconds after each category. Default: 0', false, true );
private function doPopulateCategory( $begin, $maxlag, $throttle, $force ) {
$dbw = wfGetDB( DB_MASTER );
- if( !$force ) {
+ if ( !$force ) {
$row = $dbw->selectRow(
'updatelog',
'1',
array( 'ul_key' => 'populate category' ),
__FUNCTION__
);
- if( $row ) {
- $this->output( "Category table already populated. Use php ".
- "maintenance/populateCategory.php\n--force from the command line ".
+ if ( $row ) {
+ $this->output( "Category table already populated. Use php " .
+ "maintenance/populateCategory.php\n--force from the command line " .
"to override.\n" );
return true;
}
$maxlag = intval( $maxlag );
$throttle = intval( $throttle );
$force = (bool)$force;
- if( $begin !== '' ) {
- $where = 'cl_to > '.$dbw->addQuotes( $begin );
+ if ( $begin !== '' ) {
+ $where = 'cl_to > ' . $dbw->addQuotes( $begin );
} else {
$where = null;
}
$i = 0;
- while( true ) {
+ while ( true ) {
# Find which category to update
$row = $dbw->selectRow(
'categorylinks',
'ORDER BY' => 'cl_to'
)
);
- if( !$row ) {
+ if ( !$row ) {
# Done, hopefully.
break;
}
$name = $row->cl_to;
- $where = 'cl_to > '.$dbw->addQuotes( $name );
+ $where = 'cl_to > ' . $dbw->addQuotes( $name );
# Use the row to update the category count
$cat = Category::newFromName( $name );
- if( !is_object( $cat ) ) {
+ if ( !is_object( $cat ) ) {
$this->output( "The category named $name is not valid?!\n" );
} else {
$cat->refreshCounts();
}
++$i;
- if( !($i % self::REPORTING_INTERVAL) ) {
+ if ( !( $i % self::REPORTING_INTERVAL ) ) {
$this->output( "$name\n" );
wfWaitForSlaves( $maxlag );
}
- usleep( $throttle*1000 );
+ usleep( $throttle * 1000 );
}
- if( $dbw->insert(
+ if ( $dbw->insert(
'updatelog',
array( 'ul_key' => 'populate category' ),
__FUNCTION__,
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class PopulateLogSearch extends Maintenance {
const LOG_SEARCH_BATCH_SIZE = 100;
- static $tableMap = array('rev' => 'revision', 'fa' => 'filearchive', 'oi' => 'oldimage', 'ar' => 'archive');
+ static $tableMap = array( 'rev' => 'revision', 'fa' => 'filearchive', 'oi' => 'oldimage', 'ar' => 'archive' );
public function __construct() {
parent::__construct();
$this->error( "log_search does not exist", true );
}
$start = $db->selectField( 'logging', 'MIN(log_id)', false, __FUNCTION__ );
- if( !$start ) {
+ if ( !$start ) {
$this->output( "Nothing to do.\n" );
return true;
}
$blockStart = $start;
$blockEnd = $start + self::LOG_SEARCH_BATCH_SIZE - 1;
- $delTypes = array('delete','suppress'); // revisiondelete types
- while( $blockEnd <= $end ) {
+ $delTypes = array( 'delete', 'suppress' ); // revisiondelete types
+ while ( $blockEnd <= $end ) {
$this->output( "...doing log_id from $blockStart to $blockEnd\n" );
$cond = "log_id BETWEEN $blockStart AND $blockEnd";
$res = $db->select( 'logging', '*', $cond, __FUNCTION__ );
$batch = array();
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
// RevisionDelete logs - revisions
- if( LogEventsList::typeAction( $row, $delTypes, 'revision' ) ) {
+ if ( LogEventsList::typeAction( $row, $delTypes, 'revision' ) ) {
$params = LogPage::extractParams( $row->log_params );
// Param format: <urlparam> <item CSV> [<ofield> <nfield>]
- if( count($params) < 2 ) continue; // bad row?
- $field = RevisionDeleter::getRelationType($params[0]);
+ if ( count( $params ) < 2 ) continue; // bad row?
+ $field = RevisionDeleter::getRelationType( $params[0] );
// B/C, the params may start with a title key (<title> <urlparam> <CSV>)
- if( $field == null ) {
- array_shift($params); // remove title param
- $field = RevisionDeleter::getRelationType($params[0]);
- if( $field == null ) {
+ if ( $field == null ) {
+ array_shift( $params ); // remove title param
+ $field = RevisionDeleter::getRelationType( $params[0] );
+ if ( $field == null ) {
$this->output( "Invalid param type for {$row->log_id}\n" );
continue; // skip this row
} else {
// Clean up the row...
- $db->update( 'logging',
- array('log_params' => implode(',',$params) ),
- array('log_id' => $row->log_id ) );
+ $db->update( 'logging',
+ array( 'log_params' => implode( ',', $params ) ),
+ array( 'log_id' => $row->log_id ) );
}
}
- $items = explode(',',$params[1]);
+ $items = explode( ',', $params[1] );
$log = new LogPage( $row->log_type );
// Add item relations...
$log->addRelations( $field, $items, $row->log_id );
// Determine what table to query...
- $prefix = substr( $field, 0, strpos($field,'_') ); // db prefix
- if( !isset(self::$tableMap[$prefix]) )
+ $prefix = substr( $field, 0, strpos( $field, '_' ) ); // db prefix
+ if ( !isset( self::$tableMap[$prefix] ) )
continue; // bad row?
$table = self::$tableMap[$prefix];
- $userField = $prefix.'_user';
- $userTextField = $prefix.'_user_text';
+ $userField = $prefix . '_user';
+ $userTextField = $prefix . '_user_text';
// Add item author relations...
$userIds = $userIPs = array();
$sres = $db->select( $table,
- array($userField,$userTextField),
- array($field => $items)
+ array( $userField, $userTextField ),
+ array( $field => $items )
);
- foreach( $sres as $srow ) {
- if( $srow->$userField > 0 )
- $userIds[] = intval($srow->$userField);
- else if( $srow->$userTextField != '' )
+ foreach ( $sres as $srow ) {
+ if ( $srow->$userField > 0 )
+ $userIds[] = intval( $srow->$userField );
+ else if ( $srow->$userTextField != '' )
$userIPs[] = $srow->$userTextField;
}
// Add item author relations...
$log->addRelations( 'target_author_id', $userIds, $row->log_id );
$log->addRelations( 'target_author_ip', $userIPs, $row->log_id );
// RevisionDelete logs - log events
- } else if( LogEventsList::typeAction( $row, $delTypes, 'event' ) ) {
+ } else if ( LogEventsList::typeAction( $row, $delTypes, 'event' ) ) {
$params = LogPage::extractParams( $row->log_params );
// Param format: <item CSV> [<ofield> <nfield>]
- if( count($params) < 1 ) continue; // bad row
+ if ( count( $params ) < 1 ) continue; // bad row
$items = explode( ',', $params[0] );
$log = new LogPage( $row->log_type );
// Add item relations...
// Add item author relations...
$userIds = $userIPs = array();
$sres = $db->select( 'logging',
- array('log_user','log_user_text'),
- array('log_id' => $items)
+ array( 'log_user', 'log_user_text' ),
+ array( 'log_id' => $items )
);
- foreach( $sres as $srow ) {
- if( $srow->log_user > 0 )
- $userIds[] = intval($srow->log_user);
- else if( IP::isIPAddress($srow->log_user_text) )
+ foreach ( $sres as $srow ) {
+ if ( $srow->log_user > 0 )
+ $userIds[] = intval( $srow->log_user );
+ else if ( IP::isIPAddress( $srow->log_user_text ) )
$userIPs[] = $srow->log_user_text;
}
$log->addRelations( 'target_author_id', $userIds, $row->log_id );
$blockEnd += self::LOG_SEARCH_BATCH_SIZE;
wfWaitForSlaves( 5 );
}
- if( $db->insert(
+ if ( $db->insert(
'updatelog',
array( 'ul_key' => 'populate log_search' ),
__FUNCTION__,
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class PopulateLogUsertext extends Maintenance {
public function __construct() {
public function execute() {
$db = wfGetDB( DB_MASTER );
$start = $db->selectField( 'logging', 'MIN(log_id)', false, __METHOD__ );
- if( !$start ) {
+ if ( !$start ) {
$this->output( "Nothing to do.\n" );
return true;
}
$end += $this->mBatchSize - 1;
$blockStart = $start;
$blockEnd = $start + $this->mBatchSize - 1;
- while( $blockEnd <= $end ) {
+ while ( $blockEnd <= $end ) {
$this->output( "...doing log_id from $blockStart to $blockEnd\n" );
$cond = "log_id BETWEEN $blockStart AND $blockEnd AND log_user = user_id";
- $res = $db->select( array('logging','user'),
- array('log_id','user_name'), $cond, __METHOD__ );
+ $res = $db->select( array( 'logging', 'user' ),
+ array( 'log_id', 'user_name' ), $cond, __METHOD__ );
$batch = array();
$db->begin();
- foreach( $res as $row ) {
- $db->update( 'logging', array('log_user_text' => $row->user_name),
- array('log_id' => $row->log_id), __METHOD__ );
+ foreach ( $res as $row ) {
+ $db->update( 'logging', array( 'log_user_text' => $row->user_name ),
+ array( 'log_id' => $row->log_id ), __METHOD__ );
}
$db->commit();
$blockStart += $this->mBatchSize;
$blockEnd += $this->mBatchSize;
wfWaitForSlaves( 5 );
}
- if( $db->insert(
+ if ( $db->insert(
'updatelog',
array( 'ul_key' => 'populate log_usertext' ),
__METHOD__,
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class PopulateParentId extends Maintenance {
public function __construct() {
$this->output( "Populating rev_parent_id column\n" );
$start = $db->selectField( 'revision', 'MIN(rev_id)', false, __FUNCTION__ );
$end = $db->selectField( 'revision', 'MAX(rev_id)', false, __FUNCTION__ );
- if( is_null( $start ) || is_null( $end ) ){
+ if ( is_null( $start ) || is_null( $end ) ) {
$this->output( "...revision table seems to be empty.\n" );
$db->insert( 'updatelog',
array( 'ul_key' => 'populate rev_parent_id' ),
$blockEnd = intval( $start ) + $this->mBatchSize - 1;
$count = 0;
$changed = 0;
- while( $blockStart <= $end ) {
+ while ( $blockStart <= $end ) {
$this->output( "...doing rev_id from $blockStart to $blockEnd\n" );
$cond = "rev_id BETWEEN $blockStart AND $blockEnd";
- $res = $db->select( 'revision',
- array('rev_id','rev_page','rev_timestamp','rev_parent_id'),
+ $res = $db->select( 'revision',
+ array( 'rev_id', 'rev_page', 'rev_timestamp', 'rev_parent_id' ),
$cond, __METHOD__ );
# Go through and update rev_parent_id from these rows.
# Assume that the previous revision of the title was
# the original previous revision of the title when the
# edit was made...
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
# First, check rows with the same timestamp other than this one
# with a smaller rev ID. The highest ID "wins". This avoids loops
# as timestamp can only decrease and never loops with IDs (from parent to parent)
- $previousID = $db->selectField( 'revision', 'rev_id',
+ $previousID = $db->selectField( 'revision', 'rev_id',
array( 'rev_page' => $row->rev_page, 'rev_timestamp' => $row->rev_timestamp,
- "rev_id < " . intval( $row->rev_id ) ),
+ "rev_id < " . intval( $row->rev_id ) ),
__METHOD__,
array( 'ORDER BY' => 'rev_id DESC' ) );
# If there are none, check the the highest ID with a lower timestamp
- if( !$previousID ) {
+ if ( !$previousID ) {
# Get the highest older timestamp
- $lastTimestamp = $db->selectField( 'revision', 'rev_timestamp',
- array( 'rev_page' => $row->rev_page, "rev_timestamp < " . $db->addQuotes( $row->rev_timestamp ) ),
+ $lastTimestamp = $db->selectField( 'revision', 'rev_timestamp',
+ array( 'rev_page' => $row->rev_page, "rev_timestamp < " . $db->addQuotes( $row->rev_timestamp ) ),
__METHOD__,
array( 'ORDER BY' => 'rev_timestamp DESC' ) );
# If there is one, let the highest rev ID win
- if( $lastTimestamp ) {
- $previousID = $db->selectField( 'revision', 'rev_id',
- array( 'rev_page' => $row->rev_page, 'rev_timestamp' => $lastTimestamp ),
+ if ( $lastTimestamp ) {
+ $previousID = $db->selectField( 'revision', 'rev_id',
+ array( 'rev_page' => $row->rev_page, 'rev_timestamp' => $lastTimestamp ),
__METHOD__,
array( 'ORDER BY' => 'rev_id DESC' ) );
}
}
- $previousID = intval($previousID);
- if( $previousID != $row->rev_parent_id )
+ $previousID = intval( $previousID );
+ if ( $previousID != $row->rev_parent_id )
$changed++;
# Update the row...
$db->update( 'revision',
array( 'ul_key' => 'populate rev_parent_id' ),
__METHOD__,
'IGNORE' );
- if( $logged ) {
+ if ( $logged ) {
$this->output( "rev_parent_id population complete ... {$count} rows [{$changed} changed]\n" );
return true;
} else {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class PopulateRevisionLength extends Maintenance {
public function __construct() {
$this->output( "Populating rev_len column\n" );
$start = $db->selectField( 'revision', 'MIN(rev_id)', false, __FUNCTION__ );
$end = $db->selectField( 'revision', 'MAX(rev_id)', false, __FUNCTION__ );
- if( is_null( $start ) || is_null( $end ) ){
+ if ( is_null( $start ) || is_null( $end ) ) {
$this->output( "...revision table seems to be empty.\n" );
$db->insert( 'updatelog',
array( 'ul_key' => 'populate rev_len' ),
$blockEnd = intval( $start ) + $this->mBatchSize - 1;
$count = 0;
$missing = 0;
- while( $blockStart <= $end ) {
+ while ( $blockStart <= $end ) {
$this->output( "...doing rev_id from $blockStart to $blockEnd\n" );
$res = $db->select( 'revision',
Revision::selectFields(),
"rev_len IS NULL" ),
__METHOD__ );
# Go through and update rev_len from these rows.
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$rev = new Revision( $row );
$text = $rev->getRawText();
- if( !is_string( $text ) ) {
+ if ( !is_string( $text ) ) {
# This should not happen, but sometimes does (bug 20757)
- $this->output("Text of revision {$row->rev_id} unavailable!\n");
+ $this->output( "Text of revision {$row->rev_id} unavailable!\n" );
$missing++;
}
else {
array( 'ul_key' => 'populate rev_len' ),
__METHOD__,
'IGNORE' );
- if( $logged ) {
+ if ( $logged ) {
$this->output( "rev_len population complete ... {$count} rows changed ({$missing} missing)\n" );
return true;
} else {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__).'/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class PopulateSha1 extends Maintenance {
public function __construct() {
$t = -microtime( true );
$dbw = wfGetDB( DB_MASTER );
- if( $file ) {
- $res = $dbw->selectRow(
- 'image',
- array( 'img_name' ),
+ if ( $file ) {
+ $res = $dbw->selectRow(
+ 'image',
+ array( 'img_name' ),
array( 'img_name' => $dbw->addQuotes( $file ) ),
__METHOD__
);
- if( !$res ) {
+ if ( !$res ) {
$this->error( "No such file: $file", true );
return;
}
if ( $method == 'pipe' ) {
// @fixme kill this and replace with a second unbuffered DB connection.
global $wgDBuser, $wgDBserver, $wgDBpassword, $wgDBname;
- $cmd = 'mysql -u' . wfEscapeShellArg( $wgDBuser ) .
+ $cmd = 'mysql -u' . wfEscapeShellArg( $wgDBuser ) .
' -h' . wfEscapeShellArg( $wgDBserver ) .
' -p' . wfEscapeShellArg( $wgDBpassword, $wgDBname );
$this->output( "Using pipe method\n" );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
$wgHooks['BeforeParserFetchTemplateAndtitle'][] = 'PPFuzzTester::templateHook';
class PPFuzzTester {
var $hairs = array(
- '[[', ']]', '{{', '{{', '}}', '}}', '{{{', '}}}',
+ '[[', ']]', '{{', '{{', '}}', '}}', '{{{', '}}}',
'<', '>', '<nowiki', '<gallery', '</nowiki>', '</gallery>', '<nOwIkI>', '</NoWiKi>',
'<!--' , '-->',
"\n==", "==\n",
'|', '=', "\n", ' ', "\t", "\x7f",
'~~', '~~~', '~~~~', 'subst:',
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
+ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
// extensions
- //'<ref>', '</ref>', '<references/>',
+ // '<ref>', '</ref>', '<references/>',
);
var $minLength = 0;
var $maxLength = 20;
var $maxTemplates = 5;
- //var $outputTypes = array( 'OT_HTML', 'OT_WIKI', 'OT_PREPROCESS' );
+ // var $outputTypes = array( 'OT_HTML', 'OT_WIKI', 'OT_PREPROCESS' );
var $entryPoints = array( 'testSrvus', 'testPst', 'testPreprocess' );
var $verbose = false;
static $currentTest = false;
$exceptionReport = $e->getText();
$hash = md5( $testReport );
file_put_contents( "results/ppft-$hash.in", serialize( self::$currentTest ) );
- file_put_contents( "results/ppft-$hash.fail",
+ file_put_contents( "results/ppft-$hash.fail",
"Input:\n$testReport\n\nException report:\n$exceptionReport\n" );
print "Test $hash failed\n";
$passed = 'failed';
$this->parent = $tester;
$this->mainText = $tester->makeInputText();
$this->title = $tester->makeTitle();
- //$this->outputType = $tester->pickOutputType();
+ // $this->outputType = $tester->pickOutputType();
$this->entryPoint = $tester->pickEntryPoint();
- $this->nickname = $tester->makeInputText( $wgMaxSigChars + 10);
+ $this->nickname = $tester->makeInputText( $wgMaxSigChars + 10 );
$this->fancySig = (bool)mt_rand( 0, 1 );
$this->templates = array();
}
function getReport() {
$s = "Title: " . $this->title->getPrefixedDBkey() . "\n" .
// "Output type: {$this->outputType}\n" .
- "Entry point: {$this->entryPoint}\n" .
- "User: " . ( $this->fancySig ? 'fancy' : 'no-fancy' ) . ' ' . var_export( $this->nickname, true ) . "\n" .
+ "Entry point: {$this->entryPoint}\n" .
+ "User: " . ( $this->fancySig ? 'fancy' : 'no-fancy' ) . ' ' . var_export( $this->nickname, true ) . "\n" .
"Main text: " . var_export( $this->mainText, true ) . "\n";
foreach ( $this->templates as $titleText => $template ) {
$finalTitle = $template['finalTitle'];
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class Protect extends Maintenance {
public function __construct() {
$reason = $this->getOption( 'r', '' );
$protection = "sysop";
- if ( $this->hasOption('semiprotect') ) {
+ if ( $this->hasOption( 'semiprotect' ) ) {
$protection = "autoconfirmed";
- } elseif ( $this->hasOption('unprotect') ) {
+ } elseif ( $this->hasOption( 'unprotect' ) ) {
$protection = "";
}
# un/protect the article
$this->output( "Updating protection status... " );
- $success = $wgArticle->updateRestrictions($restrictions, $reason);
+ $success = $wgArticle->updateRestrictions( $restrictions, $reason );
if ( $success ) {
$this->output( "done\n" );
} else {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class PurgeList extends Maintenance {
public function __construct() {
$stdin = $this->getStdin();
$urls = array();
- while( !feof( $stdin ) ) {
+ while ( !feof( $stdin ) ) {
$page = trim( fgets( $stdin ) );
if ( substr( $page, 0, 7 ) == 'http://' ) {
$urls[] = $page;
- } elseif( $page !== '' ) {
+ } elseif ( $page !== '' ) {
$title = Title::newFromText( $page );
- if( $title ) {
+ if ( $title ) {
$url = $title->getFullUrl();
$this->output( "$url\n" );
$urls[] = $url;
- if( isset( $options['purge'] ) ) {
+ if ( isset( $options['purge'] ) ) {
$title->invalidateCache();
}
} else {
# Get "active" text records from the revisions table
echo( "Searching for active text records in revisions table..." );
$res = $dbw->query( "SELECT DISTINCT rev_text_id FROM $tbl_rev" );
- while( $row = $dbw->fetchObject( $res ) ) {
+ while ( $row = $dbw->fetchObject( $res ) ) {
$cur[] = $row->rev_text_id;
}
echo( "done.\n" );
# Get "active" text records from the archive table
echo( "Searching for active text records in archive table..." );
$res = $dbw->query( "SELECT DISTINCT ar_text_id FROM $tbl_arc" );
- while( $row = $dbw->fetchObject( $res ) ) {
+ while ( $row = $dbw->fetchObject( $res ) ) {
$cur[] = $row->ar_text_id;
}
echo( "done.\n" );
$set = implode( ', ', $cur );
$res = $dbw->query( "SELECT old_id FROM $tbl_txt WHERE old_id NOT IN ( $set )" );
$old = array();
- while( $row = $dbw->fetchObject( $res ) ) {
+ while ( $row = $dbw->fetchObject( $res ) ) {
$old[] = $row->old_id;
}
echo( "done.\n" );
echo( "$count inactive items found.\n" );
# Delete as appropriate
- if( $delete && $count ) {
+ if ( $delete && $count ) {
echo( "Deleting..." );
$set = implode( ', ', $old );
$dbw->query( "DELETE FROM $tbl_txt WHERE old_id IN ( $set )" );
* @author Rob Church <robchur@gmail.com>
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class PurgeOldText extends Maintenance {
public function __construct() {
}
public function execute() {
- $this->purgeRedundantText( $this->hasOption('purge') );
+ $this->purgeRedundantText( $this->hasOption( 'purge' ) );
}
}
* @licence GNU General Public Licence 2.0 or later
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class ReassignEdits extends Maintenance {
public function __construct() {
}
public function execute() {
- if( $this->hasArg(0) && $this->hasArg(1) ) {
+ if ( $this->hasArg( 0 ) && $this->hasArg( 1 ) ) {
# Set up the users involved
- $from = $this->initialiseUser( $this->getArg(0) );
- $to = $this->initialiseUser( $this->getArg(1) );
+ $from = $this->initialiseUser( $this->getArg( 0 ) );
+ $to = $this->initialiseUser( $this->getArg( 1 ) );
# If the target doesn't exist, and --force is not set, stop here
- if( $to->getId() || $this->hasOption('force') ) {
+ if ( $to->getId() || $this->hasOption( 'force' ) ) {
# Reassign the edits
- $report = $this->hasOption('report');
- $count = $this->doReassignEdits( $from, $to, !$this->hasOption('norc'), $report );
+ $report = $this->hasOption( 'report' );
+ $count = $this->doReassignEdits( $from, $to, !$this->hasOption( 'norc' ), $report );
# If reporting, and there were items, advise the user to run without --report
- if( $report )
+ if ( $report )
$this->output( "Run the script again without --report to update.\n" );
} else {
$ton = $to->getName();
$this->output( "found {$del}.\n" );
# Don't count recent changes if we're not supposed to
- if( $rc ) {
+ if ( $rc ) {
$this->output( "Checking recent changes..." );
$res = $dbw->select( 'recentchanges', 'COUNT(*) AS count', $this->userConditions( $from, 'rc_user', 'rc_user_text' ), __METHOD__ );
$row = $dbw->fetchObject( $res );
$total = $cur + $del + $rec;
$this->output( "\nTotal entries to change: {$total}\n" );
- if( !$report ) {
- if( $total ) {
+ if ( !$report ) {
+ if ( $total ) {
# Reassign edits
$this->output( "\nReassigning current edits..." );
$res = $dbw->update( 'revision', $this->userSpecification( $to, 'rev_user', 'rev_user_text' ), $this->userConditions( $from, 'rev_user', 'rev_user_text' ), __METHOD__ );
$res = $dbw->update( 'archive', $this->userSpecification( $to, 'ar_user', 'ar_user_text' ), $this->userConditions( $from, 'ar_user', 'ar_user_text' ), __METHOD__ );
$this->output( "done.\n" );
# Update recent changes if required
- if( $rc ) {
+ if ( $rc ) {
$this->output( "Updating recent changes..." );
$res = $dbw->update( 'recentchanges', $this->userSpecification( $to, 'rc_user', 'rc_user_text' ), $this->userConditions( $from, 'rc_user', 'rc_user_text' ), __METHOD__ );
$this->output( "done.\n" );
}
- }
+ }
}
$dbw->commit();
- return (int)$total;
+ return (int)$total;
}
/**
* @return User
*/
private function initialiseUser( $username ) {
- if( User::isIP( $username ) ) {
+ if ( User::isIP( $username ) ) {
$user = new User();
$user->setId( 0 );
$user->setName( $username );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RebuildFileCache extends Maintenance {
public function __construct() {
public function execute() {
global $wgUseFileCache, $wgDisableCounters, $wgContentNamespaces, $wgRequestTime;
global $wgTitle, $wgArticle, $wgOut, $wgUser;
- if( !$wgUseFileCache ) {
+ if ( !$wgUseFileCache ) {
$this->error( "Nothing to do -- \$wgUseFileCache is disabled.", true );
}
$wgDisableCounters = false;
$start = $this->getArg( 0, "0" );
- if( !ctype_digit($start) ) {
+ if ( !ctype_digit( $start ) ) {
$this->error( "Invalid value for start parameter.", true );
}
- $start = intval($start);
- $overwrite = $this->hasArg(1) && $this->getArg(1) === 'overwrite';
+ $start = intval( $start );
+ $overwrite = $this->hasArg( 1 ) && $this->getArg( 1 ) === 'overwrite';
$this->output( "Building content page file cache from page {$start}!\n" );
$dbr = wfGetDB( DB_SLAVE );
$start = $start > 0 ? $start : $dbr->selectField( 'page', 'MIN(page_id)', false, __FUNCTION__ );
$end = $dbr->selectField( 'page', 'MAX(page_id)', false, __FUNCTION__ );
- if( !$start ) {
+ if ( !$start ) {
$this->error( "Nothing to do.", true );
}
$dbw = wfGetDB( DB_MASTER );
// Go through each page and save the output
- while( $blockEnd <= $end ) {
+ while ( $blockEnd <= $end ) {
// Get the pages
- $res = $dbr->select( 'page', array('page_namespace','page_title','page_id'),
- array('page_namespace' => $wgContentNamespaces,
+ $res = $dbr->select( 'page', array( 'page_namespace', 'page_title', 'page_id' ),
+ array( 'page_namespace' => $wgContentNamespaces,
"page_id BETWEEN $blockStart AND $blockEnd" ),
- array('ORDER BY' => 'page_id ASC','USE INDEX' => 'PRIMARY')
+ array( 'ORDER BY' => 'page_id ASC', 'USE INDEX' => 'PRIMARY' )
);
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$rebuilt = false;
$wgRequestTime = wfTime(); # bug 22852
$wgTitle = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
- if( null == $wgTitle ) {
+ if ( null == $wgTitle ) {
$this->output( "Page {$row->page_id} has bad title\n" );
continue; // broken title?
}
$wgUser->getSkin( $wgTitle ); // set skin title
$wgArticle = new Article( $wgTitle );
// If the article is cacheable, then load it
- if( $wgArticle->isFileCacheable() ) {
+ if ( $wgArticle->isFileCacheable() ) {
$cache = new HTMLFileCache( $wgTitle );
- if( $cache->isFileCacheGood() ) {
- if( $overwrite ) {
+ if ( $cache->isFileCacheGood() ) {
+ if ( $overwrite ) {
$rebuilt = true;
} else {
$this->output( "Page {$row->page_id} already cached\n" );
$wgUseFileCache = true;
ob_end_clean(); // clear buffer
$wgOut = new OutputPage(); // empty out any output page garbage
- if( $rebuilt )
+ if ( $rebuilt )
$this->output( "Re-cached page {$row->page_id}\n" );
else
$this->output( "Cached page {$row->page_id}\n" );
$this->output( "Done!\n" );
// Remove these to be safe
- if( isset($wgTitle) )
- unset($wgTitle);
- if( isset($wgArticle) )
- unset($wgArticle);
+ if ( isset( $wgTitle ) )
+ unset( $wgTitle );
+ if ( isset( $wgArticle ) )
+ unset( $wgArticle );
}
}
$options = array( 'missing', 'dry-run' );
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
require_once( 'FiveUpgrade.inc' );
class ImageBuilder extends FiveUpgrade {
function progress( $updated ) {
$this->updated += $updated;
$this->processed++;
- if( $this->processed % 100 != 0 ) {
+ if ( $this->processed % 100 != 0 ) {
return;
}
$portion = $this->processed / $this->count;
$sql = "SELECT * FROM $tableName";
$result = $this->dbr->query( $sql, $fname );
- while( $row = $this->dbr->fetchObject( $result ) ) {
+ while ( $row = $this->dbr->fetchObject( $result ) ) {
$update = call_user_func( $callback, $row, null );
- if( $update ) {
+ if ( $update ) {
$this->progress( 1 );
} else {
$this->progress( 0 );
function checkMissingImage( $fullpath ) {
$fname = 'ImageBuilder::checkMissingImage';
$filename = wfBaseName( $fullpath );
- if( is_dir( $fullpath ) ) {
+ if ( is_dir( $fullpath ) ) {
return;
}
- if( is_link( $fullpath ) ) {
+ if ( is_link( $fullpath ) ) {
$this->log( "skipping symlink at $fullpath" );
return;
}
array( 'img_name' => $filename ),
$fname );
- if( $row ) {
+ if ( $row ) {
// already known, move on
return;
} else {
global $wgContLang;
$altname = $wgContLang->checkTitleEncoding( $filename );
- if( $altname != $filename ) {
- if( $this->dryrun ) {
+ if ( $altname != $filename ) {
+ if ( $this->dryrun ) {
$filename = $altname;
$this->log( "Estimating transcoding... $altname" );
} else {
}
}
- if( $filename == '' ) {
+ if ( $filename == '' ) {
$this->log( "Empty filename for $fullpath" );
return;
}
if ( !$this->dryrun ) {
$file = wfLocalFile( $filename );
- if ( !$file->recordUpload( '', '(recovered file, missing upload log entry)', '', '', '',
+ if ( !$file->recordUpload( '', '(recovered file, missing upload log entry)', '', '', '',
false, $timestamp ) )
{
$this->log( "Error uploading file $fullpath" );
}
$builder = new ImageBuilder( isset( $options['dry-run'] ) );
-if( isset( $options['missing'] ) ) {
+if ( isset( $options['missing'] ) ) {
$builder->crawlMissing();
} else {
$builder->build();
foreach ( $languageAliases as $alias => $lang ) {
$reserved[$alias] = 1;
}
- foreach( $sites as $site ) {
+ foreach ( $sites as $site ) {
$reserved[$site->lateral] = 1;
}
} else {
# Find out which site this DB belongs to
$site = false;
- foreach( $sites as $candidateSite ) {
+ foreach ( $sites as $candidateSite ) {
$suffix = $candidateSite->suffix;
if ( preg_match( "/(.*)$suffix$/", $db, $matches ) ) {
$site = $candidateSite;
# w link within wikipedias
# Other sites already have it as a lateral link
if ( $site->suffix == "wiki" ) {
- $sql .= makeLink( array("w", "http://en.wikipedia.org/wiki/$1", 1), $first, $db );
+ $sql .= makeLink( array( "w", "http://en.wikipedia.org/wiki/$1", 1 ), $first, $db );
}
# Extra links
- foreach ( $extraLinks as $link ){
+ foreach ( $extraLinks as $link ) {
$sql .= makeLink( $link, $first, $db );
}
$sql .= ";\n";
$oldCwd = getcwd();
$optionsWithArgs = array( "d" );
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
require( "rebuildInterwiki.inc" );
chdir( $oldCwd );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RebuildLocalisationCache extends Maintenance {
public function __construct() {
public function execute() {
global $wgLocalisationCacheConf;
- $force = $this->hasOption('force');
+ $force = $this->hasOption( 'force' );
$threads = $this->getOption( 'threads', 1 );
- if( $threads < 1 || $threads != intval( $threads ) ) {
+ if ( $threads < 1 || $threads != intval( $threads ) ) {
$this->output( "Invalid thread count specified; running single-threaded.\n" );
$threads = 1;
}
- if( $threads > 1 && wfIsWindows() ) {
+ if ( $threads > 1 && wfIsWindows() ) {
$this->output( "Threaded rebuild is not supported on Windows; running single-threaded.\n" );
$threads = 1;
}
- if( $threads > 1 && !function_exists( 'pcntl_fork' ) ) {
+ if ( $threads > 1 && !function_exists( 'pcntl_fork' ) ) {
$this->output( "PHP pcntl extension is not present; running single-threaded.\n" );
$threads = 1;
}
// Initialise and split into chunks
$numRebuilt = 0;
- $total = count($codes);
- $chunks = array_chunk( $codes, ceil(count($codes)/$threads) );
+ $total = count( $codes );
+ $chunks = array_chunk( $codes, ceil( count( $codes ) / $threads ) );
$pids = array();
foreach ( $chunks as $codes ) {
// Do not fork for only one thread
if ( $pid === 0 ) {
// Child, reseed because there is no bug in PHP:
// http://bugs.php.net/bug.php?id=42465
- mt_srand(getmypid());
+ mt_srand( getmypid() );
$numRebuilt = $this->doRebuild( $codes, $lc, $force );
// Abuse the exit value for the count of rebuild languages
- exit($numRebuilt);
- } elseif ($pid === -1) {
+ exit( $numRebuilt );
+ } elseif ( $pid === -1 ) {
// Fork failed or one thread, do it serialized
$numRebuilt += $this->doRebuild( $codes, $lc, $force );
} else {
// Wait for all children
foreach ( $pids as $pid ) {
$status = 0;
- pcntl_waitpid($pid, $status);
+ pcntl_waitpid( $pid, $status );
// Fetch the count from the return value
- $numRebuilt += pcntl_wexitstatus($status);
+ $numRebuilt += pcntl_wexitstatus( $status );
}
$this->output( "$numRebuilt languages rebuilt out of $total\n" );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RebuildAll extends Maintenance {
public function __construct() {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RebuildMessages extends Maintenance {
public function __construct() {
public function execute() {
global $wgLocalDatabases, $wgDBname, $wgEnableSidebarCache, $messageMemc;
- if( $wgLocalDatabases ) {
+ if ( $wgLocalDatabases ) {
$databases = $wgLocalDatabases;
} else {
$databases = array( $wgDBname );
}
- foreach( $databases as $db ) {
+ foreach ( $databases as $db ) {
$this->output( "Deleting message cache for {$db}... " );
$messageMemc->delete( "{$db}:messages" );
- if( $wgEnableSidebarCache )
+ if ( $wgEnableSidebarCache )
$messageMemc->delete( "{$db}:sidebar" );
$this->output( "Deleted\n" );
}
* @todo Document
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RebuildRecentchanges extends Maintenance {
public function __construct() {
$this->output( '$wgRCMaxAge=' . $wgRCMaxAge );
$days = $wgRCMaxAge / 24 / 3600;
- if ( intval($days) == $days ) {
+ if ( intval( $days ) == $days ) {
$this->output( " (" . $days . " days)\n" );
} else {
- $this->output( " (approx. " . intval($days) . " days)\n" );
+ $this->output( " (approx. " . intval( $days ) . " days)\n" );
}
$cutoff = time() - $wgRCMaxAge;
*/
private function rebuildRecentChangesTablePass2() {
$dbw = wfGetDB( DB_MASTER );
- list ($recentchanges, $revision) = $dbw->tableNamesN( 'recentchanges', 'revision' );
+ list ( $recentchanges, $revision ) = $dbw->tableNamesN( 'recentchanges', 'revision' );
$this->output( "Updating links and size differences...\n" );
$lastOldId = 0;
foreach ( $res as $obj ) {
$new = 0;
- if( $obj->rc_cur_id != $lastCurId ) {
+ if ( $obj->rc_cur_id != $lastCurId ) {
# Switch! Look up the previous last edit, if any
$lastCurId = intval( $obj->rc_cur_id );
$emit = $obj->rc_timestamp;
$sql2 = "SELECT rev_id,rev_len FROM $revision " .
- "WHERE rev_page={$lastCurId} ".
+ "WHERE rev_page={$lastCurId} " .
"AND rev_timestamp<'{$emit}' ORDER BY rev_timestamp DESC";
- $sql2 = $dbw->limitResult($sql2, 1, false);
+ $sql2 = $dbw->limitResult( $sql2, 1, false );
$res2 = $dbw->query( $sql2 );
- if( $row = $dbw->fetchObject( $res2 ) ) {
- $lastOldId = intval($row->rev_id);
+ if ( $row = $dbw->fetchObject( $res2 ) ) {
+ $lastOldId = intval( $row->rev_id );
# Grab the last text size if available
- $lastSize = !is_null($row->rev_len) ? intval($row->rev_len) : 'NULL';
+ $lastSize = !is_null( $row->rev_len ) ? intval( $row->rev_len ) : 'NULL';
} else {
# No previous edit
$lastOldId = 0;
}
$dbw->freeResult( $res2 );
}
- if( $lastCurId == 0 ) {
+ if ( $lastCurId == 0 ) {
$this->output( "Uhhh, something wrong? No curid\n" );
} else {
# Grab the entry's text size
- $size = $dbw->selectField( 'revision', 'rev_len', array('rev_id' => $obj->rc_this_oldid ) );
- $size = !is_null($size) ? intval($size) : 'NULL';
+ $size = $dbw->selectField( 'revision', 'rev_len', array( 'rev_id' => $obj->rc_this_oldid ) );
+ $size = !is_null( $size ) ? intval( $size ) : 'NULL';
$sql3 = "UPDATE $recentchanges SET rc_last_oldid=$lastOldId,rc_new=$new,rc_type=$new," .
"rc_old_len=$lastSize,rc_new_len=$size " .
// Escape...blah blah
$selectLogs = array();
- foreach( $basicRCLogs as $logtype ) {
+ foreach ( $basicRCLogs as $logtype ) {
$safetype = $dbw->strencode( $logtype );
$selectLogs[] = "'$safetype'";
}
$cutoff = time() - $wgRCMaxAge;
- list($logging, $page) = $dbw->tableNamesN( 'logging', 'page' );
+ list( $logging, $page ) = $dbw->tableNamesN( 'logging', 'page' );
$dbw->insertSelect( 'recentchanges', array( 'user', "$logging LEFT JOIN $page ON (log_namespace=page_namespace AND log_title=page_title)" ),
array(
'rc_timestamp' => 'log_timestamp',
), array(
'log_timestamp > ' . $dbw->addQuotes( $dbw->timestamp( $cutoff ) ),
'log_user=user_id',
- 'log_type IN(' . implode(',',$selectLogs) . ')'
+ 'log_type IN(' . implode( ',', $selectLogs ) . ')'
), __METHOD__,
array(), // INSERT options
array( 'ORDER BY' => 'log_timestamp DESC', 'LIMIT' => 5000 ) // SELECT options
$dbw = wfGetDB( DB_MASTER );
- list($recentchanges,$usergroups,$user) = $dbw->tableNamesN( 'recentchanges', 'user_groups', 'user' );
+ list( $recentchanges, $usergroups, $user ) = $dbw->tableNamesN( 'recentchanges', 'user_groups', 'user' );
$botgroups = $autopatrolgroups = array();
- foreach( $wgGroupPermissions as $group => $rights ) {
- if( isset( $rights['bot'] ) && $rights['bot'] == true ) {
+ foreach ( $wgGroupPermissions as $group => $rights ) {
+ if ( isset( $rights['bot'] ) && $rights['bot'] == true ) {
$botgroups[] = $dbw->addQuotes( $group );
}
- if( $wgUseRCPatrol && isset( $rights['autopatrol'] ) && $rights['autopatrol'] == true ) {
+ if ( $wgUseRCPatrol && isset( $rights['autopatrol'] ) && $rights['autopatrol'] == true ) {
$autopatrolgroups[] = $dbw->addQuotes( $group );
}
}
# Flag our recent bot edits
- if( !empty($botgroups) ) {
- $botwhere = implode(',',$botgroups);
+ if ( !empty( $botgroups ) ) {
+ $botwhere = implode( ',', $botgroups );
$botusers = array();
$this->output( "Flagging bot account edits...\n" );
"WHERE ug_group IN($botwhere) AND user_id = ug_user";
$res = $dbw->query( $sql, DB_MASTER );
- foreach( $res as $obj ) {
+ foreach ( $res as $obj ) {
$botusers[] = $dbw->addQuotes( $obj->user_name );
}
# Fill in the rc_bot field
- if( !empty($botusers) ) {
- $botwhere = implode(',',$botusers);
+ if ( !empty( $botusers ) ) {
+ $botwhere = implode( ',', $botusers );
$sql2 = "UPDATE $recentchanges SET rc_bot=1 " .
"WHERE rc_user_text IN($botwhere)";
$dbw->query( $sql2 );
}
global $wgMiserMode;
# Flag our recent autopatrolled edits
- if( !$wgMiserMode && !empty($autopatrolgroups) ) {
- $patrolwhere = implode(',',$autopatrolgroups);
+ if ( !$wgMiserMode && !empty( $autopatrolgroups ) ) {
+ $patrolwhere = implode( ',', $autopatrolgroups );
$patrolusers = array();
$this->output( "Flagging auto-patrolled edits...\n" );
"WHERE ug_group IN($patrolwhere) AND user_id = ug_user";
$res = $dbw->query( $sql, DB_MASTER );
- foreach( $res as $obj ) {
+ foreach ( $res as $obj ) {
$patrolusers[] = $dbw->addQuotes( $obj->user_name );
}
# Fill in the rc_patrolled field
- if( !empty($patrolusers) ) {
- $patrolwhere = implode(',',$patrolusers);
+ if ( !empty( $patrolusers ) ) {
+ $patrolwhere = implode( ',', $patrolusers );
$sql2 = "UPDATE $recentchanges SET rc_patrolled=1 " .
"WHERE rc_user_text IN($patrolwhere)";
$dbw->query( $sql2 );
$this->output( "Deleting feed timestamps.\n" );
- foreach( $wgFeedClasses as $feed => $className ) {
+ foreach ( $wgFeedClasses as $feed => $className ) {
$messageMemc->delete( wfMemcKey( 'rcfeed', $feed, 'timestamp' ) ); # Good enough for now.
}
}
* @todo document
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RebuildTextIndex extends Maintenance {
const RTI_CHUNK_SIZE = 500;
*/
protected function populateSearchIndex() {
$res = $this->db->select( 'page', 'MAX(page_id) AS count' );
- $s = $this->db->fetchObject($res);
+ $s = $this->db->fetchObject( $res );
$count = $s->count;
$this->output( "Rebuilding index fields for {$count} pages...\n" );
$n = 0;
$this->output( $n . "\n" );
$end = $n + self::RTI_CHUNK_SIZE - 1;
- $res = $this->db->select( array( 'page', 'revision', 'text' ),
+ $res = $this->db->select( array( 'page', 'revision', 'text' ),
array( 'page_id', 'page_namespace', 'page_title', 'old_flags', 'old_text' ),
array( "page_id BETWEEN $n AND $end", 'page_latest = rev_id', 'rev_text_id = old_id' ),
__METHOD__
);
- foreach( $res as $s ) {
+ foreach ( $res as $s ) {
$revtext = Revision::getRevisionText( $s );
$u = new SearchUpdate( $s->page_id, $s->page_title, $revtext );
$u->doUpdate();
if ( $this->db->indexExists( 'searchindex', 'si_title' ) ) {
$this->output( "Dropping index...\n" );
$sql = "ALTER TABLE $searchindex DROP INDEX si_title, DROP INDEX si_text";
- $this->db->query($sql, __METHOD__ );
+ $this->db->query( $sql, __METHOD__ );
}
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RefreshImageCount extends Maintenance {
public function __construct() {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RefreshLinks extends Maintenance {
public function __construct() {
}
public function execute() {
- if( !$this->hasOption( 'dfn-only' ) ) {
+ if ( !$this->hasOption( 'dfn-only' ) ) {
$start = $this->getArg( 0, 1 );
$new = $this->getOption( 'new-only', false );
$max = $this->getOption( 'm', false );
* @param $redirectsOnly bool Only fix redirects
* @param $oldRedirectsOnly bool Only fix redirects without redirect entries
*/
- private function doRefreshLinks( $start, $newOnly = false, $maxLag = false,
+ private function doRefreshLinks( $start, $newOnly = false, $maxLag = false,
$end = 0, $redirectsOnly = false, $oldRedirectsOnly = false ) {
global $wgUser, $wgParser, $wgUseTidy;
$start = intval( $start );
# Don't generate TeX PNGs (lack of a sensible current directory causes errors anyway)
- $wgUser->setOption('math', MW_MATH_SOURCE);
+ $wgUser->setOption( 'math', MW_MATH_SOURCE );
# Don't generate extension images (e.g. Timeline)
- if( method_exists( $wgParser, "clearTagHooks" ) ) {
+ if ( method_exists( $wgParser, "clearTagHooks" ) ) {
$wgParser->clearTagHooks();
}
$what = $redirectsOnly ? "redirects" : "links";
- if( $oldRedirectsOnly ) {
+ if ( $oldRedirectsOnly ) {
# This entire code path is cut-and-pasted from below. Hurrah.
$res = $dbr->query(
- "SELECT page_id ".
- "FROM page ".
- "LEFT JOIN redirect ON page_id=rd_from ".
- "WHERE page_is_redirect=1 AND rd_from IS NULL AND ".
- ($end == 0 ? "page_id >= $start"
- : "page_id BETWEEN $start AND $end"),
+ "SELECT page_id " .
+ "FROM page " .
+ "LEFT JOIN redirect ON page_id=rd_from " .
+ "WHERE page_is_redirect=1 AND rd_from IS NULL AND " .
+ ( $end == 0 ? "page_id >= $start"
+ : "page_id BETWEEN $start AND $end" ),
__METHOD__
);
$num = $dbr->numRows( $res );
$this->output( "Refreshing $num old redirects from $start...\n" );
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
if ( !( ++$i % $reportingInterval ) ) {
$this->output( "$i\n" );
wfWaitForSlaves( $maxLag );
}
$this->fixRedirect( $row->page_id );
}
- } elseif( $newOnly ) {
+ } elseif ( $newOnly ) {
$this->output( "Refreshing $what from " );
$res = $dbr->select( 'page',
array( 'page_id' ),
$this->output( "$i\n" );
wfWaitForSlaves( $maxLag );
}
- if($redirectsOnly)
+ if ( $redirectsOnly )
$this->fixRedirect( $row->page_id );
else
$this->fixLinksFromArticle( $row->page_id );
$this->output( "Refreshing redirects table.\n" );
$this->output( "Starting from page_id $start of $end.\n" );
- for ($id = $start; $id <= $end; $id++) {
+ for ( $id = $start; $id <= $end; $id++ ) {
- if ( !($id % $reportingInterval) ) {
+ if ( !( $id % $reportingInterval ) ) {
$this->output( "$id\n" );
wfWaitForSlaves( $maxLag );
}
$this->fixRedirect( $id );
}
- if(!$redirectsOnly) {
+ if ( !$redirectsOnly ) {
$this->output( "Refreshing links table.\n" );
$this->output( "Starting from page_id $start of $end.\n" );
- for ($id = $start; $id <= $end; $id++) {
+ for ( $id = $start; $id <= $end; $id++ ) {
- if ( !($id % $reportingInterval) ) {
+ if ( !( $id % $reportingInterval ) ) {
$this->output( "$id\n" );
wfWaitForSlaves( $maxLag );
}
* Update the redirect entry for a given page
* @param $id int The page_id of the redirect
*/
- private function fixRedirect( $id ){
+ private function fixRedirect( $id ) {
global $wgTitle, $wgArticle;
$wgTitle = Title::newFromID( $id );
__METHOD__ );
return;
}
- $wgArticle = new Article($wgTitle);
+ $wgArticle = new Article( $wgTitle );
$rt = $wgArticle->followRedirect();
- if($rt == false || !is_object($rt)) {
+ if ( $rt == false || !is_object( $rt ) ) {
// $wgTitle is not a redirect
// Delete any redirect table entry for it
$dbw->delete( 'redirect', array( 'rd_from' => $id ),
__METHOD__ );
} else {
- $wgArticle->updateRedirectOn($dbw,$rt);
+ $wgArticle->updateRedirectOn( $dbw, $rt );
}
}
// SELECT DISTINCT( $field ) FROM $table LEFT JOIN page ON $field=page_id WHERE page_id IS NULL;
$results = $dbr->select( array( $table, 'page' ),
$field,
- array('page_id' => null ),
+ array( 'page_id' => null ),
__METHOD__,
'DISTINCT',
- array( 'page' => array( 'LEFT JOIN', "$field=page_id"))
+ array( 'page' => array( 'LEFT JOIN', "$field=page_id" ) )
);
$counter = 0;
$list = array();
$this->output( "0.." );
- foreach( $results as $row ) {
+ foreach ( $results as $row ) {
$counter++;
$list[] = $row->$field;
if ( ( $counter % $batchSize ) == 0 ) {
- wfWaitForSlaves(5);
+ wfWaitForSlaves( 5 );
$dbw->delete( $table, array( $field => $list ), __METHOD__ );
$this->output( $counter . ".." );
}
}
$this->output( $counter );
- if (count($list) > 0) {
+ if ( count( $list ) > 0 ) {
$dbw->delete( $table, array( $field => $list ), __METHOD__ );
}
$this->output( "\n" );
* @author Rob Church <robchur@gmail.com>
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RemoveUnusedAccounts extends Maintenance {
public function __construct() {
$del = array();
$dbr = wfGetDB( DB_SLAVE );
$res = $dbr->select( 'user', array( 'user_id', 'user_name', 'user_touched' ), '', __METHOD__ );
- if( $this->hasOption('ignore-groups') ) {
- $excludedGroups = explode( ',', $this->getOption('ignore-groups') );
- } else {
+ if ( $this->hasOption( 'ignore-groups' ) ) {
+ $excludedGroups = explode( ',', $this->getOption( 'ignore-groups' ) );
+ } else {
$excludedGroups = array();
}
$touched = $this->getOption( 'ignore-touched', "1" );
- if( !ctype_digit( $touched ) ) {
+ if ( !ctype_digit( $touched ) ) {
$this->error( "Please put a valid positive integer on the --ignore-touched parameter.", true );
}
$touchedSeconds = 86400 * $touched;
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
# Check the account, but ignore it if it's within a $excludedGroups group or if it's touched within the $touchedSeconds seconds.
$instance = User::newFromId( $row->user_id );
- if( count( array_intersect( $instance->getEffectiveGroups(), $excludedGroups ) ) == 0
+ if ( count( array_intersect( $instance->getEffectiveGroups(), $excludedGroups ) ) == 0
&& $this->isInactiveAccount( $row->user_id, true )
&& wfTimestamp( TS_UNIX, $row->user_touched ) < wfTimestamp( TS_UNIX, time() - $touchedSeconds )
) {
$this->output( "...found {$count}.\n" );
# If required, go back and delete each marked account
- if( $count > 0 && $this->hasOption('delete') ) {
+ if ( $count > 0 && $this->hasOption( 'delete' ) ) {
$this->output( "\nDeleting inactive accounts..." );
$dbw = wfGetDB( DB_MASTER );
$dbw->delete( 'user', array( 'user_id' => $del ), __METHOD__ );
# Update the site_stats.ss_users field
$users = $dbw->selectField( 'user', 'COUNT(*)', array(), __METHOD__ );
$dbw->update( 'site_stats', array( 'ss_users' => $users ), array( 'ss_row_id' => 1 ), __METHOD__ );
- } elseif( $count > 0 ) {
+ } elseif ( $count > 0 ) {
$this->output( "\nRun the script again with --delete to remove them from the database.\n" );
}
$this->output( "\n" );
$count = 0;
$dbo->begin();
- foreach( $checks as $table => $fprefix ) {
+ foreach ( $checks as $table => $fprefix ) {
$conds = array( $fprefix . '_user' => $id );
$count += (int)$dbo->selectField( $table, 'COUNT(*)', $conds, __METHOD__ );
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RenameDbPrefix extends Maintenance {
public function __construct() {
public function execute() {
// Allow for no old prefix
- if( $this->getOption( 'old', 0 ) === '0' ) {
+ if ( $this->getOption( 'old', 0 ) === '0' ) {
$old = '';
} else {
// Use nice safe, sane, prefixes
- preg_match( '/^[a-zA-Z]+_$/', $this->getOption('old'), $m );
+ preg_match( '/^[a-zA-Z]+_$/', $this->getOption( 'old' ), $m );
$old = isset( $m[0] ) ? $m[0] : false;
}
// Allow for no new prefix
- if( $this->getOption( 'new', 0 ) === '0' ) {
+ if ( $this->getOption( 'new', 0 ) === '0' ) {
$new = '';
} else {
// Use nice safe, sane, prefixes
- preg_match( '/^[a-zA-Z]+_$/', $this->getOption('new'), $m );
+ preg_match( '/^[a-zA-Z]+_$/', $this->getOption( 'new' ), $m );
$new = isset( $m[0] ) ? $m[0] : false;
}
- if( $old === false || $new === false ) {
+ if ( $old === false || $new === false ) {
$this->error( "Invalid prefix!", true );
}
- if( $old === $new ) {
+ if ( $old === $new ) {
$this->output( "Same prefix. Nothing to rename!\n", true );
}
$count = 0;
$dbw = wfGetDB( DB_MASTER );
- $res = $dbw->query( "SHOW TABLES LIKE '".$dbw->escapeLike( $old )."%'" );
- foreach( $res as $row ) {
+ $res = $dbw->query( "SHOW TABLES LIKE '" . $dbw->escapeLike( $old ) . "%'" );
+ foreach ( $res as $row ) {
// XXX: odd syntax. MySQL outputs an oddly cased "Tables of X"
// sort of message. Best not to try $row->x stuff...
$fields = get_object_vars( $row );
// Silly for loop over one field...
- foreach( $fields as $resName => $table ) {
+ foreach ( $fields as $resName => $table ) {
// $old should be regexp safe ([a-zA-Z_])
- $newTable = preg_replace( '/^'.$old.'/', $new, $table );
+ $newTable = preg_replace( '/^' . $old . '/', $new, $table );
$this->output( "Renaming table $table to $newTable\n" );
$dbw->query( "RENAME TABLE $table TO $newTable" );
}
* @ingroup Wikimedia
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RenameWiki extends Maintenance {
public function __construct() {
$to = $this->getArg( 1 );
$this->output( "Renaming blob tables in ES from $from to $to...\n" );
$this->output( "Sleeping 5 seconds...\n" );
- sleep(5);
+ sleep( 5 );
# Initialise external storage
if ( is_array( $wgDefaultExternalStore ) ) {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class DumpRenderer extends Maintenance {
*/
private function handleRevision( $rev ) {
$title = $rev->getTitle();
- if (!$title) {
+ if ( !$title ) {
$this->error( "Got bogus revision with null title!" );
return;
}
$this->count++;
$sanitized = rawurlencode( $display );
- $filename = sprintf( "%s/wiki-%07d-%s.html",
+ $filename = sprintf( "%s/wiki-%07d-%s.html",
$this->outputDirectory,
$this->count,
$sanitized );
"<head>\n" .
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" .
"<title>" . htmlspecialchars( $display ) . "</title>\n" .
- "</head>\n" .
+ "</head>\n" .
"<body>\n" .
$output->getText() .
"</body>\n" .
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RollbackEdits extends Maintenance {
public function __construct() {
public function execute() {
$user = $this->getOption( 'user' );
$username = User::isIP( $user ) ? $user : User::getCanonicalName( $user );
- if( !$username ) {
+ if ( !$username ) {
$this->error( 'Invalid username', true );
}
$summary = $this->getOption( 'summary', $this->mSelf . ' mass rollback' );
$titles = array();
$results = array();
- if( $this->hasOption( 'titles' ) ) {
- foreach( explode( '|', $this->getOption( 'titles' ) ) as $title ) {
+ if ( $this->hasOption( 'titles' ) ) {
+ foreach ( explode( '|', $this->getOption( 'titles' ) ) as $title ) {
$t = Title::newFromText( $title );
- if( !$t ) {
+ if ( !$t ) {
$this->error( 'Invalid title, ' . $title );
} else {
$titles[] = $t;
$titles = $this->getRollbackTitles( $user );
}
- if( !$titles ) {
+ if ( !$titles ) {
$this->output( 'No suitable titles to be rolled back' );
return;
}
- foreach( $titles as $t ) {
+ foreach ( $titles as $t ) {
$a = new Article( $t );
$this->output( 'Processing ' . $t->getPrefixedText() . '...' );
- if( !$a->commitRollback( $user, $summary, $bot, $results ) ) {
+ if ( !$a->commitRollback( $user, $summary, $bot, $results ) ) {
$this->output( "done\n" );
} else {
$this->output( "failed\n" );
array( 'page_latest = rev_id', 'rev_user_text' => $user ),
__METHOD__
);
- while( $row = $dbr->fetchObject( $results ) ) {
+ while ( $row = $dbr->fetchObject( $results ) ) {
$titles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
}
return $titles;
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class BatchedQueryRunner extends Maintenance {
public function __construct() {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class RunJobs extends Maintenance {
public function __construct() {
public function execute() {
global $wgTitle;
if ( $this->hasOption( 'procs' ) ) {
- $procs = intval( $this->getOption('procs') );
+ $procs = intval( $this->getOption( 'procs' ) );
if ( $procs < 1 || $procs > 1000 ) {
$this->error( "Invalid argument to --procs", true );
}
$dbw = wfGetDB( DB_MASTER );
$n = 0;
$conds = '';
- if ($type !== false)
- $conds = "job_cmd = " . $dbw->addQuotes($type);
+ if ( $type !== false )
+ $conds = "job_cmd = " . $dbw->addQuotes( $type );
while ( $dbw->selectField( 'job', 'job_id', $conds, 'runJobs.php' ) ) {
- $offset=0;
- for (;;) {
- $job = ($type == false) ?
- Job::pop($offset)
- : Job::pop_type($type);
+ $offset = 0;
+ for ( ; ; ) {
+ $job = ( $type == false ) ?
+ Job::pop( $offset )
+ : Job::pop_type( $type );
- if ($job == false)
+ if ( $job == false )
break;
wfWaitForSlaves( 5 );
$t = microtime( true );
- $offset=$job->id;
+ $offset = $job->id;
$status = $job->run();
$t = microtime( true ) - $t;
$timeMs = intval( $t * 1000 );
* @author Ashar Voultoiz
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class ShowJobs extends Maintenance {
public function __construct() {
__METHOD__,
array( 'GROUP BY' => 'job_cmd' )
);
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$this->output( $row->job_cmd . ': ' . $row->count . "\n" );
}
} else {
* @license GNU General Public License 2.0 or later
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class ShowStats extends Maintenance {
public function __construct() {
// Get maximum size for each column
$max_length_value = $max_length_desc = 0;
- foreach( $fields as $field => $desc ) {
+ foreach ( $fields as $field => $desc ) {
$max_length_value = max( $max_length_value, strlen( $stats->$field ) );
- $max_length_desc = max( $max_length_desc , strlen( $desc )) ;
+ $max_length_desc = max( $max_length_desc , strlen( $desc ) ) ;
}
// Show them
- foreach( $fields as $field => $desc ) {
+ foreach ( $fields as $field => $desc ) {
$this->output( sprintf( "%-{$max_length_desc}s: %{$max_length_value}d\n", $desc, $stats->$field ) );
}
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class MwSql extends Maintenance {
public function __construct() {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class SqliteMaintenance extends Maintenance {
public function __construct() {
$prevSize = filesize( $this->db->mDatabaseFile );
if ( $prevSize == 0 ) {
$this->error( "Can't vacuum an empty database.\n", true );
- }
+ }
$this->output( 'VACUUM: ' );
if ( $this->db->query( 'VACUUM' ) ) {
clearstatcache();
$newSize = filesize( $this->db->mDatabaseFile );
$this->output( sprintf( "Database size was %d, now %d (%.1f%% reduction).\n",
- $prevSize, $newSize, ( $prevSize - $newSize) * 100.0 / $prevSize ) );
+ $prevSize, $newSize, ( $prevSize - $newSize ) * 100.0 / $prevSize ) );
} else {
$this->output( 'Error\n' );
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class CacheStats extends Maintenance {
global $wgMemc;
// Can't do stats if
- if( get_class( $wgMemc ) == 'FakeMemCachedClient' ) {
+ if ( get_class( $wgMemc ) == 'FakeMemCachedClient' ) {
$this->error( "You are running FakeMemCachedClient, I can not provide any statistics.", true );
}
- $session = intval($wgMemc->get(wfMemcKey('stats','request_with_session')));
- $noSession = intval($wgMemc->get(wfMemcKey('stats','request_without_session')));
+ $session = intval( $wgMemc->get( wfMemcKey( 'stats', 'request_with_session' ) ) );
+ $noSession = intval( $wgMemc->get( wfMemcKey( 'stats', 'request_without_session' ) ) );
$total = $session + $noSession;
if ( $total == 0 ) {
$this->error( "You either have no stats or the cache isn't running. Aborting.", true );
}
$this->output( "Requests\n" );
- $this->output( sprintf( "with session: %-10d %6.2f%%\n", $session, $session/$total*100 ) );
- $this->output( sprintf( "without session: %-10d %6.2f%%\n", $noSession, $noSession/$total*100 ) );
+ $this->output( sprintf( "with session: %-10d %6.2f%%\n", $session, $session / $total * 100 ) );
+ $this->output( sprintf( "without session: %-10d %6.2f%%\n", $noSession, $noSession / $total * 100 ) );
$this->output( sprintf( "total: %-10d %6.2f%%\n", $total, 100 ) );
$this->output( "\nParser cache\n" );
- $hits = intval($wgMemc->get(wfMemcKey('stats','pcache_hit')));
- $invalid = intval($wgMemc->get(wfMemcKey('stats','pcache_miss_invalid')));
- $expired = intval($wgMemc->get(wfMemcKey('stats','pcache_miss_expired')));
- $absent = intval($wgMemc->get(wfMemcKey('stats','pcache_miss_absent')));
- $stub = intval($wgMemc->get(wfMemcKey('stats','pcache_miss_stub')));
+ $hits = intval( $wgMemc->get( wfMemcKey( 'stats', 'pcache_hit' ) ) );
+ $invalid = intval( $wgMemc->get( wfMemcKey( 'stats', 'pcache_miss_invalid' ) ) );
+ $expired = intval( $wgMemc->get( wfMemcKey( 'stats', 'pcache_miss_expired' ) ) );
+ $absent = intval( $wgMemc->get( wfMemcKey( 'stats', 'pcache_miss_absent' ) ) );
+ $stub = intval( $wgMemc->get( wfMemcKey( 'stats', 'pcache_miss_stub' ) ) );
$total = $hits + $invalid + $expired + $absent + $stub;
- $this->output( sprintf( "hits: %-10d %6.2f%%\n", $hits, $hits/$total*100 ) );
- $this->output( sprintf( "invalid: %-10d %6.2f%%\n", $invalid, $invalid/$total*100 ) );
- $this->output( sprintf( "expired: %-10d %6.2f%%\n", $expired, $expired/$total*100 ) );
- $this->output( sprintf( "absent: %-10d %6.2f%%\n", $absent, $absent/$total*100 ) );
- $this->output( sprintf( "stub threshold: %-10d %6.2f%%\n", $stub, $stub/$total*100 ) );
+ $this->output( sprintf( "hits: %-10d %6.2f%%\n", $hits, $hits / $total * 100 ) );
+ $this->output( sprintf( "invalid: %-10d %6.2f%%\n", $invalid, $invalid / $total * 100 ) );
+ $this->output( sprintf( "expired: %-10d %6.2f%%\n", $expired, $expired / $total * 100 ) );
+ $this->output( sprintf( "absent: %-10d %6.2f%%\n", $absent, $absent / $total * 100 ) );
+ $this->output( sprintf( "stub threshold: %-10d %6.2f%%\n", $stub, $stub / $total * 100 ) );
$this->output( sprintf( "total: %-10d %6.2f%%\n", $total, 100 ) );
- $hits = intval($wgMemc->get(wfMemcKey('stats','image_cache_hit')));
- $misses = intval($wgMemc->get(wfMemcKey('stats','image_cache_miss')));
- $updates = intval($wgMemc->get(wfMemcKey('stats','image_cache_update')));
+ $hits = intval( $wgMemc->get( wfMemcKey( 'stats', 'image_cache_hit' ) ) );
+ $misses = intval( $wgMemc->get( wfMemcKey( 'stats', 'image_cache_miss' ) ) );
+ $updates = intval( $wgMemc->get( wfMemcKey( 'stats', 'image_cache_update' ) ) );
$total = $hits + $misses;
- $this->output("\nImage cache\n");
- $this->output( sprintf( "hits: %-10d %6.2f%%\n", $hits, $hits/$total*100 ) );
- $this->output( sprintf( "misses: %-10d %6.2f%%\n", $misses, $misses/$total*100 ) );
+ $this->output( "\nImage cache\n" );
+ $this->output( sprintf( "hits: %-10d %6.2f%%\n", $hits, $hits / $total * 100 ) );
+ $this->output( sprintf( "misses: %-10d %6.2f%%\n", $misses, $misses / $total * 100 ) );
$this->output( sprintf( "updates: %-10d\n", $updates ) );
- $hits = intval($wgMemc->get(wfMemcKey('stats','diff_cache_hit')));
- $misses = intval($wgMemc->get(wfMemcKey('stats','diff_cache_miss')));
- $uncacheable = intval($wgMemc->get(wfMemcKey('stats','diff_uncacheable')));
+ $hits = intval( $wgMemc->get( wfMemcKey( 'stats', 'diff_cache_hit' ) ) );
+ $misses = intval( $wgMemc->get( wfMemcKey( 'stats', 'diff_cache_miss' ) ) );
+ $uncacheable = intval( $wgMemc->get( wfMemcKey( 'stats', 'diff_uncacheable' ) ) );
$total = $hits + $misses + $uncacheable;
- $this->output("\nDiff cache\n");
- $this->output( sprintf( "hits: %-10d %6.2f%%\n", $hits, $hits/$total*100 ) );
- $this->output( sprintf( "misses: %-10d %6.2f%%\n", $misses, $misses/$total*100 ) );
- $this->output( sprintf( "uncacheable: %-10d %6.2f%%\n", $uncacheable, $uncacheable/$total*100 ) );
+ $this->output( "\nDiff cache\n" );
+ $this->output( sprintf( "hits: %-10d %6.2f%%\n", $hits, $hits / $total * 100 ) );
+ $this->output( sprintf( "misses: %-10d %6.2f%%\n", $misses, $misses / $total * 100 ) );
+ $this->output( sprintf( "uncacheable: %-10d %6.2f%%\n", $uncacheable, $uncacheable / $total * 100 ) );
}
}
define( 'CONCAT_HEADER', 'O:27:"concatenatedgziphistoryblob"' );
if ( !defined( 'MEDIAWIKI' ) ) {
- require_once( dirname(__FILE__) . '/../commandLine.inc' );
+ require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
$cs = new CheckStorage;
$fix = isset( $options['fix'] );
}
-//----------------------------------------------------------------------------------
+// ----------------------------------------------------------------------------------
/**
* @ingroup Maintenance ExternalStorage
'unfixable' => 'Unexpected errors with no automated fixing method',
'fixed' => 'Errors already fixed',
'fixable' => 'Errors which would already be fixed if --fix was specified',
- );
+ );
function check( $fix = false, $xml = '' ) {
$fname = 'checkStorage';
for ( $chunkStart = 1 ; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
$chunkEnd = $chunkStart + $chunkSize - 1;
- //print "$chunkStart of $maxRevId\n";
+ // print "$chunkStart of $maxRevId\n";
// Fetch revision rows
$this->oldIdMap = array();
- $dbr->ping();
- $res = $dbr->select( 'revision', array( 'rev_id', 'rev_text_id' ),
+ $dbr->ping();
+ $res = $dbr->select( 'revision', array( 'rev_id', 'rev_text_id' ),
array( "rev_id BETWEEN $chunkStart AND $chunkEnd" ), $fname );
while ( $row = $dbr->fetchObject( $res ) ) {
$this->oldIdMap[$row->rev_id] = $row->rev_text_id;
$missingTextRows = array_flip( $this->oldIdMap );
$externalRevs = array();
$objectRevs = array();
- $res = $dbr->select( 'text', array( 'old_id', 'old_flags' ),
+ $res = $dbr->select( 'text', array( 'old_id', 'old_flags' ),
'old_id IN (' . implode( ',', $this->oldIdMap ) . ')', $fname );
while ( $row = $dbr->fetchObject( $res ) ) {
$flags = $row->old_flags;
if ( $fix ) {
$this->error( 'fixed', "Warning: old_flags set to 0", $id );
$dbw->ping();
- $dbw->update( 'text', array( 'old_flags' => '' ),
+ $dbw->update( 'text', array( 'old_flags' => '' ),
array( 'old_id' => $id ), $fname );
echo "Fixed\n";
} else {
$externalConcatBlobs = array();
$externalNormalBlobs = array();
if ( count( $externalRevs ) ) {
- $res = $dbr->select( 'text', array( 'old_id', 'old_flags', 'old_text' ),
+ $res = $dbr->select( 'text', array( 'old_id', 'old_flags', 'old_text' ),
array( 'old_id IN (' . implode( ',', $externalRevs ) . ')' ), $fname );
while ( $row = $dbr->fetchObject( $res ) ) {
$urlParts = explode( '://', $row->old_text, 2 );
$blobIds = array_keys( $xBlobIds );
$extDb =& $this->dbStore->getSlave( $cluster );
$blobsTable = $this->dbStore->getTable( $extDb );
- $res = $extDb->select( $blobsTable,
- array( 'blob_id' ),
+ $res = $extDb->select( $blobsTable,
+ array( 'blob_id' ),
array( 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ), $fname );
while ( $row = $extDb->fetchObject( $res ) ) {
unset( $xBlobIds[$row->blob_id] );
$curIds = array();
if ( count( $objectRevs ) ) {
$headerLength = 300;
- $res = $dbr->select( 'text', array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
+ $res = $dbr->select( 'text', array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
array( 'old_id IN (' . implode( ',', $objectRevs ) . ')' ), $fname );
while ( $row = $dbr->fetchObject( $res ) ) {
$oldId = $row->old_id;
$externalConcatBlobs = array();
if ( count( $concatBlobs ) ) {
$headerLength = 300;
- $res = $dbr->select( 'text', array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
+ $res = $dbr->select( 'text', array( 'old_id', 'old_flags', "LEFT(old_text, $headerLength) AS header" ),
array( 'old_id IN (' . implode( ',', array_keys( $concatBlobs ) ) . ')' ), $fname );
while ( $row = $dbr->fetchObject( $res ) ) {
$flags = explode( ',', $row->old_flags );
if ( !isset( $externalConcatBlobs[$cluster][$id] ) ) {
$externalConcatBlobs[$cluster][$id] = array();
}
- $externalConcatBlobs[$cluster][$id] = array_merge(
+ $externalConcatBlobs[$cluster][$id] = array_merge(
$externalConcatBlobs[$cluster][$id], $concatBlobs[$row->old_id]
);
}
$concatBlobs[$row->old_id] );
}
} elseif ( strcasecmp( substr( $row->header, 0, strlen( CONCAT_HEADER ) ), CONCAT_HEADER ) ) {
- $this->error( 'restore text', "Error: Incorrect object header for concat bulk row {$row->old_id}",
+ $this->error( 'restore text', "Error: Incorrect object header for concat bulk row {$row->old_id}",
$concatBlobs[$row->old_id] );
} # else good
}
print "\n\nErrors:\n";
- foreach( $this->errors as $name => $errors ) {
+ foreach ( $this->errors as $name => $errors ) {
if ( count( $errors ) ) {
$description = $this->errorDescriptions[$name];
echo "$description: " . implode( ',', array_keys( $errors ) ) . "\n";
foreach ( $ids as $id ) {
$revIds = array_merge( $revIds, array_keys( $this->oldIdMap, $id ) );
}
- print "$msg in text rows " . implode( ', ', $ids ) .
+ print "$msg in text rows " . implode( ', ', $ids ) .
", revisions " . implode( ', ', $revIds ) . "\n";
} else {
$id = $ids;
$extDb =& $this->dbStore->getSlave( $cluster );
$blobsTable = $this->dbStore->getTable( $extDb );
$headerLength = strlen( CONCAT_HEADER );
- $res = $extDb->select( $blobsTable,
- array( 'blob_id', "LEFT(blob_text, $headerLength) AS header" ),
+ $res = $extDb->select( $blobsTable,
+ array( 'blob_id', "LEFT(blob_text, $headerLength) AS header" ),
array( 'blob_id IN( ' . implode( ',', $blobIds ) . ')' ), $fname );
while ( $row = $extDb->fetchObject( $res ) ) {
if ( strcasecmp( $row->header, CONCAT_HEADER ) ) {
- $this->error( 'restore text', "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
+ $this->error( 'restore text', "Error: invalid header on target $cluster/{$row->blob_id} of two-part ES URL",
$oldIds[$row->blob_id] );
}
unset( $oldIds[$row->blob_id] );
// Run mwdumper
echo "Filtering XML dump...\n";
$exitStatus = 0;
- passthru( 'mwdumper ' .
- wfEscapeShellArg(
+ passthru( 'mwdumper ' .
+ wfEscapeShellArg(
"--output=file:$filteredXmlFileName",
"--filter=revlist:$revFileName",
$xml
// Update the text row
$dbw = wfGetDB( DB_MASTER );
- $dbw->update( 'text',
+ $dbw->update( 'text',
array( 'old_flags' => $flags, 'old_text' => $text ),
array( 'old_id' => $oldId ),
$fname, array( 'LIMIT' => 1 )
*/
$optionsWithArgs = array( 't', 'c', 's', 'f', 'h', 'extdb', 'endid', 'e' );
-require_once( dirname(__FILE__) . '/../commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
require_once( "compressOld.inc" );
-if( !function_exists( "gzdeflate" ) ) {
+if ( !function_exists( "gzdeflate" ) ) {
print "You must enable zlib support in PHP to compress old revisions!\n";
print "Please see http://www.php.net/manual/en/ref.zlib.php\n\n";
wfDie();
}
if ( $options['extdb'] != '' ) {
- print "Compressing database $wgDBname to external cluster {$options['extdb']}\n" . str_repeat('-', 76) . "\n\n";
+ print "Compressing database $wgDBname to external cluster {$options['extdb']}\n" . str_repeat( '-', 76 ) . "\n\n";
} else {
- print "Compressing database $wgDBname\n" . str_repeat('-', 76) . "\n\n";
+ print "Compressing database $wgDBname\n" . str_repeat( '-', 76 ) . "\n\n";
}
$success = true;
print "Done.\n";
}
-exit(0);
+exit( 0 );
* @ingroup Maintenance ExternalStorage
*/
-require_once( dirname(__FILE__) . '/../Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
class DumpRev extends Maintenance {
public function __construct() {
public function execute() {
$dbr = wfGetDB( DB_SLAVE );
- $row = $dbr->selectRow(
- array( 'text', 'revision' ),
- array( 'old_flags', 'old_text' ),
+ $row = $dbr->selectRow(
+ array( 'text', 'revision' ),
+ array( 'old_flags', 'old_text' ),
array( 'old_id=rev_text_id', 'rev_id' => $this->getArg() )
);
if ( !$row ) {
if ( is_object( $text ) ) {
$this->error( "Unexpectedly got object of type: " . get_class( $text ) );
} else {
- $this->output( "Text length: " . strlen( $text ) ."\n" );
+ $this->output( "Text length: " . strlen( $text ) . "\n" );
$this->output( substr( $text, 0, 100 ) . "\n" );
}
}
$totalRevs = $dbr->selectField( 'text', 'MAX(old_id)', false, __METHOD__ );
- if ( $dbr->getType() == 'mysql'
+ if ( $dbr->getType() == 'mysql'
&& version_compare( $dbr->getServerVersion(), '4.1.0', '>=' ) )
{
// In MySQL 4.1+, the binary field old_text has a non-working LOWER() function
$res = $dbr->select(
'text',
array( 'old_id', 'old_flags', 'old_text' ),
- array(
+ array(
'old_id > ' . intval( $startId ),
'old_flags LIKE \'%object%\' AND old_flags NOT LIKE \'%external%\'',
"$lowerLeft = 'o:15:\"historyblobstub\"'",
),
__METHOD__,
- array(
+ array(
'ORDER BY' => 'old_id',
'LIMIT' => $this->batchSize,
)
}
if ( !is_object( $obj ) ) {
- print "{$row->old_id}: unrecoverable: unserialized to type " .
+ print "{$row->old_id}: unrecoverable: unserialized to type " .
gettype( $obj ) . ", possible double-serialization\n";
++$numBad;
continue;
$secondaryId = $stub['secondaryId'];
if ( !isset( $trackedBlobs[$secondaryId] ) ) {
// No tracked blob. Work out what went wrong
- $secondaryRow = $dbr->selectRow(
- 'text',
+ $secondaryRow = $dbr->selectRow(
+ 'text',
array( 'old_flags', 'old_text' ),
- array( 'old_id' => $secondaryId ),
+ array( 'old_id' => $secondaryId ),
__METHOD__
);
if ( !$secondaryRow ) {
$dbr = wfGetDB( DB_SLAVE );
$map = array();
- $res = $dbr->select( 'revision',
+ $res = $dbr->select( 'revision',
array( 'rev_id', 'rev_text_id' ),
array( 'rev_page' => $pageId ),
__METHOD__
function isUnbrokenStub( $stub, $secondaryRow ) {
$flags = explode( ',', $secondaryRow->old_flags );
$text = $secondaryRow->old_text;
- if( in_array( 'external', $flags ) ) {
+ if ( in_array( 'external', $flags ) ) {
$url = $text;
@list( /* $proto */ , $path ) = explode( '://', $url, 2 );
if ( $path == "" ) {
}
$text = ExternalStore::fetchFromUrl( $url );
}
- if( !in_array( 'object', $flags ) ) {
+ if ( !in_array( 'object', $flags ) ) {
return false;
}
- if( in_array( 'gzip', $flags ) ) {
+ if ( in_array( 'gzip', $flags ) ) {
$obj = unserialize( gzinflate( $text ) );
} else {
$obj = unserialize( $text );
}
- if( !is_object( $obj ) ) {
+ if ( !is_object( $obj ) ) {
// Correct for old double-serialization bug.
$obj = unserialize( $obj );
}
if ( !defined( 'MEDIAWIKI' ) ) {
$optionsWithArgs = array( 'e', 's' );
- require_once( dirname(__FILE__) . '/../commandLine.inc' );
+ require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
require_once( 'ExternalStoreDB.php' );
require_once( 'resolveStubs.php' );
$blockStart = $block * $blockSize + $minID;
$blockEnd = $blockStart + $blockSize - 1;
- if ( !($block % REPORTING_INTERVAL) ) {
+ if ( !( $block % REPORTING_INTERVAL ) ) {
print "oldid=$blockStart, moved=$numMoved\n";
wfWaitForSlaves( 2 );
}
$obj = unserialize( $text );
$className = strtolower( get_class( $obj ) );
if ( $className == 'historyblobstub' ) {
- #resolveStub( $id, $row->old_text, $row->old_flags );
- #$numStubs++;
+ # resolveStub( $id, $row->old_text, $row->old_flags );
+ # $numStubs++;
continue;
} elseif ( $className == 'historyblobcurstub' ) {
$text = gzdeflate( $obj->getText() );
continue;
}
- #print "Storing " . strlen( $text ) . " bytes to $url\n";
- #print "old_id=$id\n";
+ # print "Storing " . strlen( $text ) . " bytes to $url\n";
+ # print "old_id=$id\n";
$url = $ext->store( $cluster, $text );
if ( !$url ) {
*
* @ingroup Maintenance ExternalStorage
*/
-require_once( dirname(__FILE__) . '/../Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
class OrphanStats extends Maintenance {
public function __construct() {
public function execute() {
$extDBs = array();
$dbr = wfGetDB( DB_SLAVE );
- if( !$dbr->tableExists( 'blob_orphans' ) ) {
+ if ( !$dbr->tableExists( 'blob_orphans' ) ) {
$this->error( "blob_orphans doesn't seem to exist, need to run trackBlobs.php first", true );
}
$res = $dbr->select( 'blob_orphans', '*', false, __METHOD__ );
$this->output( "Number of orphans: $num\n" );
if ( $num > 0 ) {
$this->output( "Average size: " . round( $totalSize / $num, 0 ) . " bytes\n" .
- "Max size: $maxSize\n" .
+ "Max size: $maxSize\n" .
"Number of unique texts: " . count( $hashes ) . "\n" );
}
}
<?php
$optionsWithArgs = RecompressTracked::getOptionsWithArgs();
-require( dirname( __FILE__ ) .'/../commandLine.inc' );
+require( dirname( __FILE__ ) . '/../commandLine.inc' );
if ( count( $args ) < 1 ) {
echo "Usage: php recompressTracked.php [options] <cluster> [... <cluster>...]
}
function logToFile( $msg, $file ) {
- $header = '[' . date('d\TH:i:s') . '] ' . wfHostname() . ' ' . posix_getpid();
+ $header = '[' . date( 'd\TH:i:s' ) . '] ' . wfHostname() . ' ' . posix_getpid();
if ( $this->slaveId !== false ) {
$header .= "({$this->slaveId})";
}
$cmd .= " --$cmdOption";
}
}
- $cmd .= ' --child' .
+ $cmd .= ' --child' .
' --wiki ' . wfEscapeShellArg( wfWikiID() ) .
' ' . call_user_func_array( 'wfEscapeShellArg', $this->destClusters );
$this->slavePipes = $this->slaveProcs = array();
for ( $i = 0; $i < $this->numProcs; $i++ ) {
$pipes = false;
- $spec = array(
+ $spec = array(
array( 'pipe', 'r' ),
array( 'file', 'php://stdout', 'w' ),
array( 'file', 'php://stderr', 'w' )
function dispatch( /*...*/ ) {
$args = func_get_args();
$pipes = $this->slavePipes;
- $numPipes = stream_select( $x=array(), $pipes, $y=array(), 3600 );
+ $numPipes = stream_select( $x = array(), $pipes, $y = array(), 3600 );
if ( !$numPipes ) {
$this->critical( "Error waiting to write to slaves. Aborting" );
exit( 1 );
if ( $this->noCount ) {
$numPages = '[unknown]';
} else {
- $numPages = $dbr->selectField( 'blob_tracking',
- 'COUNT(DISTINCT bt_page)',
+ $numPages = $dbr->selectField( 'blob_tracking',
+ 'COUNT(DISTINCT bt_page)',
# A condition is required so that this query uses the index
array( 'bt_moved' => 0 ),
__METHOD__
$this->info( "Moving pages..." );
}
while ( true ) {
- $res = $dbr->select( 'blob_tracking',
+ $res = $dbr->select( 'blob_tracking',
array( 'bt_page' ),
- array(
+ array(
'bt_moved' => 0,
'bt_page > ' . $dbr->addQuotes( $startId )
),
__METHOD__,
- array(
- 'DISTINCT',
+ array(
+ 'DISTINCT',
'ORDER BY' => 'bt_page',
'LIMIT' => $this->batchSize,
)
if ( $this->noCount ) {
$numOrphans = '[unknown]';
} else {
- $numOrphans = $dbr->selectField( 'blob_tracking',
- 'COUNT(DISTINCT bt_text_id)',
+ $numOrphans = $dbr->selectField( 'blob_tracking',
+ 'COUNT(DISTINCT bt_text_id)',
array( 'bt_moved' => 0, 'bt_page' => 0 ),
__METHOD__ );
if ( !$numOrphans ) {
$trx = new CgzCopyTransaction( $this, $this->pageBlobClass );
while ( true ) {
- $res = $dbr->select(
- array( 'blob_tracking', 'text' ),
+ $res = $dbr->select(
+ array( 'blob_tracking', 'text' ),
'*',
array(
'bt_page' => $pageId,
'bt_text_id=old_id',
),
__METHOD__,
- array(
+ array(
'ORDER BY' => 'bt_text_id',
'LIMIT' => $this->batchSize
)
$dbr = wfGetDB( DB_SLAVE );
$startId = 0;
- $conds = array_merge( $conds, array(
+ $conds = array_merge( $conds, array(
'bt_moved' => 0,
'bt_new_url IS NOT NULL'
- ));
+ ) );
while ( true ) {
$res = $dbr->select( 'blob_tracking',
'*',
array_merge( $conds, array( 'bt_text_id > ' . $dbr->addQuotes( $startId ) ) ),
__METHOD__,
- array(
+ array(
'ORDER BY' => 'bt_text_id',
'LIMIT' => $this->batchSize,
)
$trx = new CgzCopyTransaction( $this, $this->orphanBlobClass );
$res = wfGetDB( DB_SLAVE )->select(
- array( 'text', 'blob_tracking' ),
- array( 'old_id', 'old_text', 'old_flags' ),
- array(
+ array( 'text', 'blob_tracking' ),
+ array( 'old_id', 'old_text', 'old_flags' ),
+ array(
'old_id' => $textIds,
'bt_text_id=old_id',
'bt_moved' => 0,
- ),
+ ),
__METHOD__,
array( 'DISTINCT' )
);
// We do a locking read to prevent closer-run race conditions.
$dbw = wfGetDB( DB_MASTER );
$dbw->begin();
- $res = $dbw->select( 'blob_tracking',
+ $res = $dbw->select( 'blob_tracking',
array( 'bt_text_id', 'bt_moved' ),
array( 'bt_text_id' => array_keys( $this->referrers ) ),
__METHOD__, array( 'FOR UPDATE' ) );
if ( !defined( 'MEDIAWIKI' ) ) {
$optionsWithArgs = array( 'm' );
- require_once( dirname(__FILE__) . '/../commandLine.inc' );
+ require_once( dirname( __FILE__ ) . '/../commandLine.inc' );
resolveStubs();
}
wfWaitForSlaves( 2 );
printf( "%5.2f%%\n", $b / $numBlocks * 100 );
- $start = intval($maxID / $numBlocks) * $b + 1;
- $end = intval($maxID / $numBlocks) * ($b + 1);
+ $start = intval( $maxID / $numBlocks ) * $b + 1;
+ $end = intval( $maxID / $numBlocks ) * ( $b + 1 );
$res = $dbr->select( 'text', array( 'old_id', 'old_text', 'old_flags' ),
"old_id>=$start AND old_id<=$end " .
- "AND old_flags LIKE '%object%' AND old_flags NOT LIKE '%external%' ".
- 'AND LOWER(CONVERT(LEFT(old_text,22) USING latin1)) = \'o:15:"historyblobstub"\'',
+ "AND old_flags LIKE '%object%' AND old_flags NOT LIKE '%external%' " .
+ 'AND LOWER(CONVERT(LEFT(old_text,22) USING latin1)) = \'o:15:"historyblobstub"\'',
$fname );
while ( $row = $dbr->fetchObject( $res ) ) {
resolveStub( $row->old_id, $row->old_text, $row->old_flags );
}
# Update the row
- #print "oldid=$id\n";
+ # print "oldid=$id\n";
$dbw->update( 'text',
array( /* SET */
'old_flags' => $newFlags,
<?php
-require_once( dirname(__FILE__).'/../Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/../Maintenance.php' );
class StorageTypeStats extends Maintenance {
function execute() {
echo str_repeat( '-', 120 ) . "\n";
foreach ( $stats as $flags => $flagStats ) {
foreach ( $flagStats as $class => $entry ) {
- printf( $format, $flags, $class, $entry['count'],
+ printf( $format, $flags, $class, $entry['count'],
sprintf( "%-13d - %-13d", $entry['first'], $entry['last'] ) );
}
}
<?php
$optionsWithArgs = array( 'start', 'limit', 'type' );
-require( dirname(__FILE__).'/../commandLine.inc' );
+require( dirname( __FILE__ ) . '/../commandLine.inc' );
if ( !isset( $args[0] ) ) {
echo "Usage: php testCompression.php [--type=<type>] [--start=<start-date>] [--limit=<num-revs>] <page-title>\n";
$dbr = wfGetDB( DB_SLAVE );
-$res = $dbr->select(
+$res = $dbr->select(
array( 'page', 'revision', 'text' ),
'*',
- array(
+ array(
'page_namespace' => $title->getNamespace(),
'page_title' => $title->getDBkey(),
'page_id=rev_page',
$serialized = serialize( $blob );
$t += microtime( true );
-#print_r( $blob->mDiffMap );
+# print_r( $blob->mDiffMap );
-printf( "%s\nCompression ratio for %d revisions: %5.2f, %s -> %d\n",
+printf( "%s\nCompression ratio for %d revisions: %5.2f, %s -> %d\n",
$type,
count( $hashes ),
$uncompressedSize / strlen( $serialized ),
$text = $blob->getItem( $key );
if ( md5( $text ) != $hashes[$id] ) {
echo "Content hash mismatch for rev_id $id\n";
- #var_dump( $text );
+ # var_dump( $text );
}
}
$t += microtime( true );
<?php
-require( dirname( __FILE__ ) .'/../commandLine.inc' );
+require( dirname( __FILE__ ) . '/../commandLine.inc' );
if ( count( $args ) < 1 ) {
$dbr = wfGetDB( DB_SLAVE );
// Scan for HistoryBlobStub objects in the text table (bug 20757)
-
+
$exists = $dbr->selectField( 'text', 1,
- 'old_flags LIKE \'%object%\' AND old_flags NOT LIKE \'%external%\' ' .
+ 'old_flags LIKE \'%object%\' AND old_flags NOT LIKE \'%external%\' ' .
'AND LOWER(CONVERT(LEFT(old_text,22) USING latin1)) = \'o:15:"historyblobstub"\'',
__METHOD__
);
if ( $exists ) {
- echo "Integrity check failed: found HistoryBlobStub objects in your text table.\n".
+ echo "Integrity check failed: found HistoryBlobStub objects in your text table.\n" .
"This script could destroy these objects if it continued. Run resolveStubs.php\n" .
"to fix this.\n";
exit( 1 );
// Scan the archive table for HistoryBlobStub objects or external flags (bug 22624)
$flags = $dbr->selectField( 'archive', 'ar_flags',
'ar_flags LIKE \'%external%\' OR (' .
- 'ar_flags LIKE \'%object%\' ' .
+ 'ar_flags LIKE \'%object%\' ' .
'AND LOWER(CONVERT(LEFT(ar_text,22) USING latin1)) = \'o:15:"historyblobstub"\' )',
__METHOD__
);
if ( strpos( $flags, 'external' ) !== false ) {
- echo "Integrity check failed: found external storage pointers in your archive table.\n" .
+ echo "Integrity check failed: found external storage pointers in your archive table.\n" .
"Run normaliseArchiveTable.php to fix this.\n";
exit( 1 );
} elseif ( $flags ) {
# Scan the text table for orphan text
while ( true ) {
- $res = $dbr->select( array( 'text', 'blob_tracking' ),
+ $res = $dbr->select( array( 'text', 'blob_tracking' ),
array( 'old_id', 'old_flags', 'old_text' ),
- array(
+ array(
'old_id>' . $dbr->addQuotes( $startId ),
$textClause,
'old_flags ' . $dbr->buildLike( $dbr->anyString(), 'external', $dbr->anyString() ),
__METHOD__,
array(
'ORDER BY' => 'old_id',
- 'LIMIT' => $this->batchSize
+ 'LIMIT' => $this->batchSize
),
array( 'blob_tracking' => array( 'LEFT JOIN', 'bt_text_id=old_id' ) )
);
// Build a bitmap of actual blob rows
while ( true ) {
- $res = $extDB->select( $table,
- array( 'blob_id' ),
+ $res = $extDB->select( $table,
+ array( 'blob_id' ),
array( 'blob_id > ' . $extDB->addQuotes( $startId ) ),
__METHOD__,
array( 'LIMIT' => $this->batchSize, 'ORDER BY' => 'blob_id' )
global $wgServerName, $wgServer, $wgContLang, $wgAuth, $wgScriptPath,
$wgScriptExtension, $wgMemc, $wgRequest;
- self::$apiUrl = $wgServer.$wgScriptPath."/api".$wgScriptExtension;
+ self::$apiUrl = $wgServer . $wgScriptPath . "/api" . $wgScriptExtension;
$wgMemc = new FakeMemCachedClient;
$wgContLang = Language::factory( 'en' );
$wgAuth = new StubObject( 'wgAuth', 'AuthPlugin' );
- $wgRequest = new FauxRequest(array());
+ $wgRequest = new FauxRequest( array() );
self::setupUser();
}
self::$userName = "Useruser";
self::$passWord = User::randomPassword();
- self::$user = User::newFromName(self::$userName);
+ self::$user = User::newFromName( self::$userName );
if ( !self::$user->getID() ) {
- self::$user = User::createNew(self::$userName, array(
+ self::$user = User::createNew( self::$userName, array(
"email" => "test@example.com",
- "real_name" => "Test User"));
+ "real_name" => "Test User" ) );
}
- self::$user->setPassword(self::$passWord);
+ self::$user->setPassword( self::$passWord );
self::$user->saveSettings();
}
}
require_once( "ApiSetup.php" );
class MockApi extends ApiBase {
- public function execute() {}
- public function getVersion() {}
+ public function execute() { }
+ public function getVersion() { }
- public function __construct() {}
+ public function __construct() { }
public function getAllowedParams() {
$params = array(
$mock = new MockApi();
$this->assertEquals(
- null, $mock->requireOnlyOneParameter(array("filename" => "foo.txt",
- "enablechunks" => false), "filename", "enablechunks"));
+ null, $mock->requireOnlyOneParameter( array( "filename" => "foo.txt",
+ "enablechunks" => false ), "filename", "enablechunks" ) );
}
/**
$mock = new MockApi();
$this->assertEquals(
- null, $mock->requireOnlyOneParameter(array("filename" => "foo.txt",
- "enablechunks" => 0), "filename", "enablechunks"));
+ null, $mock->requireOnlyOneParameter( array( "filename" => "foo.txt",
+ "enablechunks" => 0 ), "filename", "enablechunks" ) );
}
/**
$mock = new MockApi();
$this->assertEquals(
- null, $mock->requireOnlyOneParameter(array("filename" => "foo.txt",
- "enablechunks" => true), "filename", "enablechunks"));
+ null, $mock->requireOnlyOneParameter( array( "filename" => "foo.txt",
+ "enablechunks" => true ), "filename", "enablechunks" ) );
}
function testApi() {
global $wgServerName, $wgServer, $wgDBprefix, $wgDBtype;
- if($wgDBprefix === "parsertest_" || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_'))
- $this->markTestSkipped("This test can't (yet?) be run with the parser tests");
- if(!isset($wgServerName) || !isset($wgServer)) {
- $this->markTestIncomplete('This test needs $wgServerName and $wgServer to '.
- 'be set in LocalSettings.php');
+ if ( $wgDBprefix === "parsertest_" || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) )
+ $this->markTestSkipped( "This test can't (yet?) be run with the parser tests" );
+ if ( !isset( $wgServerName ) || !isset( $wgServer ) ) {
+ $this->markTestIncomplete( 'This test needs $wgServerName and $wgServer to ' .
+ 'be set in LocalSettings.php' );
}
/* Haven't thought about test ordering yet -- but this depends on HttpTest.php */
$resp = Http::get( self::$apiUrl . "?format=xml" );
function testApiLoginNoName() {
global $wgServerName, $wgServer, $wgDBprefix, $wgDBtype;
- if($wgDBprefix === "parsertest_" || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_'))
- $this->markTestSkipped("This test can't (yet?) be run with the parser tests");
- if(!isset($wgServerName) || !isset($wgServer)) {
- $this->markTestIncomplete('This test needs $wgServerName and $wgServer to '.
- 'be set in LocalSettings.php');
+ if ( $wgDBprefix === "parsertest_" || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) )
+ $this->markTestSkipped( "This test can't (yet?) be run with the parser tests" );
+ if ( !isset( $wgServerName ) || !isset( $wgServer ) ) {
+ $this->markTestIncomplete( 'This test needs $wgServerName and $wgServer to ' .
+ 'be set in LocalSettings.php' );
}
$resp = Http::post( self::$apiUrl . "?action=login&format=xml",
array( "postData" => array(
function testApiLoginBadPass() {
global $wgServerName, $wgServer, $wgDBprefix, $wgDBtype;
- if($wgDBprefix === "parsertest_" || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_'))
- $this->markTestSkipped("This test can't (yet?) be run with the parser tests");
- if(!isset($wgServerName) || !isset($wgServer)) {
- $this->markTestIncomplete('This test needs $wgServerName and $wgServer to '.
- 'be set in LocalSettings.php');
+ if ( $wgDBprefix === "parsertest_" || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) )
+ $this->markTestSkipped( "This test can't (yet?) be run with the parser tests" );
+ if ( !isset( $wgServerName ) || !isset( $wgServer ) ) {
+ $this->markTestIncomplete( 'This test needs $wgServerName and $wgServer to ' .
+ 'be set in LocalSettings.php' );
}
$resp = Http::post( self::$apiUrl . "?action=login&format=xml",
array( "postData" => array(
function testApiLoginGoodPass() {
global $wgServerName, $wgServer, $wgDBprefix, $wgDBtype;
- if($wgDBprefix === "parsertest_" || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_'))
- $this->markTestSkipped("This test can't (yet?) be run with the parser tests");
- if(!isset($wgServerName) || !isset($wgServer)) {
- $this->markTestIncomplete('This test needs $wgServerName and $wgServer to '.
- 'be set in LocalSettings.php');
+ if ( $wgDBprefix === "parsertest_" || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) )
+ $this->markTestSkipped( "This test can't (yet?) be run with the parser tests" );
+ if ( !isset( $wgServerName ) || !isset( $wgServer ) ) {
+ $this->markTestIncomplete( 'This test needs $wgServerName and $wgServer to ' .
+ 'be set in LocalSettings.php' );
}
- $req = HttpRequest::factory(self::$apiUrl . "?action=login&format=xml",
+ $req = HttpRequest::factory( self::$apiUrl . "?action=login&format=xml",
array( "method" => "POST",
"postData" => array(
"lgname" => self::$userName,
$this->assertEquals( ' result="NeedToken"', $a->asXML() );
$token = (string)$sxe->login[0]->attributes()->token;
- $req->setData(array(
+ $req->setData( array(
"lgtoken" => $token,
"lgname" => self::$userName,
"lgpassword" => self::$passWord ) );
function testApiGotCookie() {
global $wgServerName, $wgServer, $wgScriptPath, $wgDBprefix, $wgDBtype;
- if($wgDBprefix === "parsertest_" || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_'))
- $this->markTestSkipped("This test can't (yet?) be run with the parser tests");
- if(!isset($wgServerName) || !isset($wgServer)) {
- $this->markTestIncomplete('This test needs $wgServerName and $wgServer to '.
- 'be set in LocalSettings.php');
+ if ( $wgDBprefix === "parsertest_" || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) )
+ $this->markTestSkipped( "This test can't (yet?) be run with the parser tests" );
+ if ( !isset( $wgServerName ) || !isset( $wgServer ) ) {
+ $this->markTestIncomplete( 'This test needs $wgServerName and $wgServer to ' .
+ 'be set in LocalSettings.php' );
}
- $req = HttpRequest::factory(self::$apiUrl . "?action=login&format=xml",
+ $req = HttpRequest::factory( self::$apiUrl . "?action=login&format=xml",
array( "method" => "POST",
"postData" => array(
"lgname" => self::$userName,
$this->assertEquals( ' result="NeedToken"', $a->asXML() );
$token = (string)$sxe->login[0]->attributes()->token;
- $req->setData(array(
+ $req->setData( array(
"lgtoken" => $token,
"lgname" => self::$userName,
"lgpassword" => self::$passWord ) );
/**
* @depends testApiGotCookie
*/
- function testApiListPages(CookieJar $cj) {
- $this->markTestIncomplete("Not done with this yet");
+ function testApiListPages( CookieJar $cj ) {
+ $this->markTestIncomplete( "Not done with this yet" );
global $wgServerName, $wgServer, $wgDBprefix, $wgDBtype;
- if($wgDBprefix === "parsertest_" || ($wgDBtype == 'oracle' && $wgDBprefix === 'pt_'))
- $this->markTestSkipped("This test can't (yet?) be run with the parser tests");
- if($wgServerName == "localhost" || $wgServer == "http://localhost") {
- $this->markTestIncomplete('This test needs $wgServerName and $wgServer to '.
- 'be set in LocalSettings.php');
+ if ( $wgDBprefix === "parsertest_" || ( $wgDBtype == 'oracle' && $wgDBprefix === 'pt_' ) )
+ $this->markTestSkipped( "This test can't (yet?) be run with the parser tests" );
+ if ( $wgServerName == "localhost" || $wgServer == "http://localhost" ) {
+ $this->markTestIncomplete( 'This test needs $wgServerName and $wgServer to ' .
+ 'be set in LocalSettings.php' );
}
- $req = HttpRequest::factory( self::$apiUrl . "?action=query&format=xml&prop=revisions&".
+ $req = HttpRequest::factory( self::$apiUrl . "?action=query&format=xml&prop=revisions&" .
"titles=Main%20Page&rvprop=timestamp|user|comment|content" );
- $req->setCookieJar($cj);
+ $req->setCookieJar( $cj );
$req->execute();
libxml_use_internal_errors( true );
$sxe = simplexml_load_string( $req->getContent() );
'action' => 'query',
'titles' => 'Main Page',
'intoken' => 'edit|delete|protect|move|block|unblock',
- 'prop' => 'info'), $data);
+ 'prop' => 'info' ), $data );
$this->assertArrayHasKey( 'query', $data[0] );
$this->assertArrayHasKey( 'pages', $data[0]['query'] );
$key = array_pop( array_keys( $data[0]['query']['pages'] ) );
$this->assertArrayHasKey( $key, $data[0]['query']['pages'] );
- $this->assertArrayHasKey( 'edittoken', $data[0]['query']['pages'][$key]);
- $this->assertArrayHasKey( 'movetoken', $data[0]['query']['pages'][$key]);
- $this->assertArrayHasKey( 'deletetoken', $data[0]['query']['pages'][$key]);
- $this->assertArrayHasKey( 'blocktoken', $data[0]['query']['pages'][$key]);
- $this->assertArrayHasKey( 'unblocktoken', $data[0]['query']['pages'][$key]);
- $this->assertArrayHasKey( 'protecttoken', $data[0]['query']['pages'][$key]);
+ $this->assertArrayHasKey( 'edittoken', $data[0]['query']['pages'][$key] );
+ $this->assertArrayHasKey( 'movetoken', $data[0]['query']['pages'][$key] );
+ $this->assertArrayHasKey( 'deletetoken', $data[0]['query']['pages'][$key] );
+ $this->assertArrayHasKey( 'blocktoken', $data[0]['query']['pages'][$key] );
+ $this->assertArrayHasKey( 'unblocktoken', $data[0]['query']['pages'][$key] );
+ $this->assertArrayHasKey( 'protecttoken', $data[0]['query']['pages'][$key] );
return $data;
}
'title' => 'Main Page',
'text' => 'new text',
'token' => $pageinfo['edittoken'],
- 'watchlist' => 'watch'), $data);
+ 'watchlist' => 'watch' ), $data );
$this->assertArrayHasKey( 'edit', $data[0] );
$this->assertArrayHasKey( 'result', $data[0]['edit'] );
$this->assertEquals( 'Success', $data[0]['edit']['result'] );
global $wgUser;
$data = $this->doApiRequest( array(
'action' => 'query',
- 'list' => 'watchlist'), $data);
+ 'list' => 'watchlist' ), $data );
- if(isset($data[0]['query']['watchlist'])) {
+ if ( isset( $data[0]['query']['watchlist'] ) ) {
$wl = $data[0]['query']['watchlist'];
- foreach($wl as $page) {
+ foreach ( $wl as $page ) {
$data = $this->doApiRequest( array(
'action' => 'watch',
'title' => $page['title'],
- 'unwatch' => true), $data);
+ 'unwatch' => true ), $data );
}
}
$data = $this->doApiRequest( array(
'action' => 'query',
- 'list' => 'watchlist'), $data);
+ 'list' => 'watchlist' ), $data );
$this->assertArrayHasKey( 'query', $data[0] );
$this->assertArrayHasKey( 'watchlist', $data[0]['query'] );
- $this->assertEquals( 0, count($data[0]['query']['watchlist']) );
+ $this->assertEquals( 0, count( $data[0]['query']['watchlist'] ) );
return $data;
}
'token' => $pageinfo['protecttoken'],
'title' => 'Main Page',
'protections' => 'edit=sysop',
- 'watchlist' => 'unwatch'), $data);
+ 'watchlist' => 'unwatch' ), $data );
$this->assertArrayHasKey( 'protect', $data[0] );
$this->assertArrayHasKey( 'protections', $data[0]['protect'] );
- $this->assertEquals( 1, count($data[0]['protect']['protections']) );
+ $this->assertEquals( 1, count( $data[0]['protect']['protections'] ) );
$this->assertArrayHasKey( 'edit', $data[0]['protect']['protections'][0] );
}
'action' => 'query',
'prop' => 'revisions',
'titles' => 'Main Page',
- 'rvtoken' => 'rollback'), $data);
+ 'rvtoken' => 'rollback' ), $data );
$this->assertArrayHasKey( 'query', $data[0] );
$this->assertArrayHasKey( 'pages', $data[0]['query'] );
$key = array_pop( array_keys( $data[0]['query']['pages'] ) );
- $this->assertArrayHasKey( 'pageid', $data[0]['query']['pages'][$key]);
- $this->assertArrayHasKey( 'revisions', $data[0]['query']['pages'][$key]);
+ $this->assertArrayHasKey( 'pageid', $data[0]['query']['pages'][$key] );
+ $this->assertArrayHasKey( 'revisions', $data[0]['query']['pages'][$key] );
$this->assertArrayHasKey( 0, $data[0]['query']['pages'][$key]['revisions'] );
$this->assertArrayHasKey( 'rollbacktoken', $data[0]['query']['pages'][$key]['revisions'][0] );
'title' => 'Main Page',
'user' => 'WikiSysop',
'token' => $pageinfo['rollbacktoken'],
- 'watchlist' => 'watch'), $data);
+ 'watchlist' => 'watch' ), $data );
$this->assertArrayHasKey( 'rollback', $data[0] );
$this->assertArrayHasKey( 'title', $data[0]['rollback'] );
$data = $this->doApiRequest( array(
'action' => 'delete',
'token' => $pageinfo['deletetoken'],
- 'title' => 'Main Page'), $data);
+ 'title' => 'Main Page' ), $data );
$this->assertArrayHasKey( 'delete', $data[0] );
$this->assertArrayHasKey( 'title', $data[0]['delete'] );
$data = $this->doApiRequest( array(
'action' => 'query',
- 'list' => 'watchlist'), $data);
+ 'list' => 'watchlist' ), $data );
}
}
$v1 = $v1 === false ? '(not found)' : $v1;
$v2 = $v2 === false ? '(not found)' : $v2;
- #cdbAssert( 'Mismatch', $key, $v1, $v2 );
+ # cdbAssert( 'Mismatch', $key, $v1, $v2 );
$this->cdbAssert( "PHP error", $key, $v1, $value );
$this->cdbAssert( "DBA error", $key, $v2, $value );
}
);
$this->assertEquals( "ALTER TABLE foo ADD COLUMN foo_bar INTEGER DEFAULT 42",
- $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42")
+ $this->replaceVars( "ALTER TABLE foo\nADD COLUMN foo_bar int(10) unsigned DEFAULT 42" )
);
}
}
\ No newline at end of file
'SELECT * FROM interwiki', array() );
$this->assertEquals(
"SELECT * FROM interwiki",
- $sql);
+ $sql );
}
function testFillPreparedQuestion() {
array( '"user"', "Slash's Dot" ) );
$this->assertEquals(
"SELECT * FROM cur WHERE cur_title='This_&_that,_WTF?!'",
- $sql);
+ $sql );
}
}
function setUp() {
global $wgReadOnlyFile;
$this->originals['wgReadOnlyFile'] = $wgReadOnlyFile;
- $wgReadOnlyFile = tempnam(wfTempDir(), "mwtest_readonly");
+ $wgReadOnlyFile = tempnam( wfTempDir(), "mwtest_readonly" );
unlink( $wgReadOnlyFile );
}
function tearDown() {
global $wgReadOnlyFile;
- if( file_exists( $wgReadOnlyFile ) ) {
+ if ( file_exists( $wgReadOnlyFile ) ) {
unlink( $wgReadOnlyFile );
}
$wgReadOnlyFile = $this->originals['wgReadOnlyFile'];
'C:\\Progra~1\\Wikime~1\\Wikipe~1\\VIEWER.EXE' => 'VIEWER.EXE',
'Östergötland_coat_of_arms.png' => 'Östergötland_coat_of_arms.png',
);
- foreach( $sets as $from => $to ) {
+ foreach ( $sets as $from => $to ) {
$this->assertEquals( $to, wfBaseName( $from ),
- "wfBaseName('$from') => '$to'");
+ "wfBaseName('$from') => '$to'" );
}
}
<?php
class MockCookie extends Cookie {
- public function canServeDomain($arg) { return parent::canServeDomain($arg); }
- public function canServePath($arg) { return parent::canServePath($arg); }
+ public function canServeDomain( $arg ) { return parent::canServeDomain( $arg ); }
+ public function canServePath( $arg ) { return parent::canServePath( $arg ); }
public function isUnExpired() { return parent::isUnExpired(); }
}
var $test_posturl = array( "http://www.comp.leeds.ac.uk/cgi-bin/Perl/environment-example" => "review=test" );
function setup() {
- putenv("http_proxy"); /* Remove any proxy env var, so curl doesn't get confused */
+ putenv( "http_proxy" ); /* Remove any proxy env var, so curl doesn't get confused */
if ( is_array( self::$content ) ) {
return;
}
self::$has_curl = function_exists( 'curl_init' );
self::$has_fopen = wfIniGetBool( 'allow_url_fopen' );
- if ( !file_exists("/usr/bin/curl") ) {
- $this->markTestIncomplete("This test requires the curl binary at /usr/bin/curl. If you have curl, please file a bug on this test, or, better yet, provide a patch.");
+ if ( !file_exists( "/usr/bin/curl" ) ) {
+ $this->markTestIncomplete( "This test requires the curl binary at /usr/bin/curl. If you have curl, please file a bug on this test, or, better yet, provide a patch." );
}
$content = tempnam( wfTempDir(), "" );
}
// This probably isn't the best test for a proxy, but it works on my system!
- system("curl -0 -o $content -s ".self::$proxy);
+ system( "curl -0 -o $content -s " . self::$proxy );
$out = file_get_contents( $content );
- if( $out ) {
+ if ( $out ) {
self::$has_proxy = true;
}
function testInstantiation() {
Http::$httpEngine = false;
- $r = HttpRequest::factory("http://www.example.com/");
+ $r = HttpRequest::factory( "http://www.example.com/" );
if ( self::$has_curl ) {
- $this->assertThat($r, $this->isInstanceOf( 'CurlHttpRequest' ));
+ $this->assertThat( $r, $this->isInstanceOf( 'CurlHttpRequest' ) );
} else {
- $this->assertThat($r, $this->isInstanceOf( 'PhpHttpRequest' ));
+ $this->assertThat( $r, $this->isInstanceOf( 'PhpHttpRequest' ) );
}
- unset($r);
+ unset( $r );
- if( !self::$has_fopen ) {
+ if ( !self::$has_fopen ) {
$this->setExpectedException( 'MWException' );
}
Http::$httpEngine = 'php';
- $r = HttpRequest::factory("http://www.example.com/");
- $this->assertThat($r, $this->isInstanceOf( 'PhpHttpRequest' ));
- unset($r);
+ $r = HttpRequest::factory( "http://www.example.com/" );
+ $this->assertThat( $r, $this->isInstanceOf( 'PhpHttpRequest' ) );
+ unset( $r );
- if( !self::$has_curl ) {
+ if ( !self::$has_curl ) {
$this->setExpectedException( 'MWException' );
}
Http::$httpEngine = 'curl';
- $r = HttpRequest::factory("http://www.example.com/");
- if( self::$has_curl ) {
- $this->assertThat($r, $this->isInstanceOf( 'CurlHttpRequest' ));
+ $r = HttpRequest::factory( "http://www.example.com/" );
+ if ( self::$has_curl ) {
+ $this->assertThat( $r, $this->isInstanceOf( 'CurlHttpRequest' ) );
}
}
$timeout = 1;
$start_time = time();
- $r = HTTP::get( "http://www.example.com:1/", $timeout);
+ $r = HTTP::get( "http://www.example.com:1/", $timeout );
$end_time = time();
- $this->assertLessThan($timeout+2, $end_time - $start_time,
- "Request took less than {$timeout}s via ".Http::$httpEngine);
- $this->assertEquals($r, false, "false -- what we get on error from Http::get()");
+ $this->assertLessThan( $timeout + 2, $end_time - $start_time,
+ "Request took less than {$timeout}s via " . Http::$httpEngine );
+ $this->assertEquals( $r, false, "false -- what we get on error from Http::get()" );
- $r = HTTP::get( "http://www.example.com/this-file-does-not-exist", $timeout);
- $this->assertFalse($r, "False on 404s");
+ $r = HTTP::get( "http://www.example.com/this-file-does-not-exist", $timeout );
+ $this->assertFalse( $r, "False on 404s" );
$r = HttpRequest::factory( "http://www.example.com/this-file-does-not-exist" );
$er = $r->execute();
- if ( is_a($r, 'PhpHttpRequest') && version_compare( '5.2.10', phpversion(), '>' ) ) {
- $this->assertRegexp("/HTTP request failed/", $er->getWikiText());
+ if ( is_a( $r, 'PhpHttpRequest' ) && version_compare( '5.2.10', phpversion(), '>' ) ) {
+ $this->assertRegexp( "/HTTP request failed/", $er->getWikiText() );
} else {
- $this->assertRegexp("/404 Not Found/", $er->getWikiText());
+ $this->assertRegexp( "/404 Not Found/", $er->getWikiText() );
}
}
/* ./phase3/includes/Import.php:1108: $data = Http::request( $method, $url ); */
/* ./includes/Import.php:1124: $link = Title::newFromText( "$interwiki:Special:Export/$page" ); */
/* ./includes/Import.php:1134: return ImportStreamSource::newFromURL( $url, "POST" ); */
- function runHTTPRequests($proxy=null) {
+ function runHTTPRequests( $proxy = null ) {
$opt = array();
- if($proxy) {
+ if ( $proxy ) {
$opt['proxy'] = $proxy;
- } elseif( $proxy === false ) {
+ } elseif ( $proxy === false ) {
$opt['noProxy'] = true;
}
/* no postData here because the only request I could find in code so far didn't have any */
foreach ( $this->test_requesturl as $u ) {
$r = Http::request( "POST", $u, $opt );
- $this->assertEquals( self::$content["POST $u"], "$r", "POST $u with ".Http::$httpEngine );
+ $this->assertEquals( self::$content["POST $u"], "$r", "POST $u with " . Http::$httpEngine );
}
}
/* ./extensions/APC/SpecialAPC.php:245: $rss = Http::get( 'http://pecl.php.net/feeds/pkg_apc.rss' ); */
/* ./extensions/Interlanguage/Interlanguage.php:56: $a = Http::get( $url ); */
/* ./extensions/MWSearch/MWSearch_body.php:492: $data = Http::get( $searchUrl, $wgLuceneSearchTimeout, $httpOpts); */
- function runHTTPGets($proxy=null) {
+ function runHTTPGets( $proxy = null ) {
$opt = array();
- if($proxy) {
+ if ( $proxy ) {
$opt['proxy'] = $proxy;
- } elseif( $proxy === false ) {
+ } elseif ( $proxy === false ) {
$opt['noProxy'] = true;
}
foreach ( $this->test_geturl as $u ) {
$r = Http::get( $u, 30, $opt ); /* timeout of 30s */
- $this->assertEquals( self::$content["GET $u"], "$r", "Get $u with ".Http::$httpEngine );
+ $this->assertEquals( self::$content["GET $u"], "$r", "Get $u with " . Http::$httpEngine );
}
}
}
/* ./phase3/maintenance/parserTests.inc:1618: return Http::post( $url, array( 'postData' => wfArrayToCGI( $data ) ) ); */
- function runHTTPPosts($proxy=null) {
+ function runHTTPPosts( $proxy = null ) {
$opt = array();
- if($proxy) {
+ if ( $proxy ) {
$opt['proxy'] = $proxy;
- } elseif( $proxy === false ) {
+ } elseif ( $proxy === false ) {
$opt['noProxy'] = true;
}
$opt['postData'] = $postData;
$r = Http::post( $u, $opt );
$this->assertEquals( self::$content["POST $u => $postData"], "$r",
- "POST $u (postData=$postData) with ".Http::$httpEngine );
+ "POST $u (postData=$postData) with " . Http::$httpEngine );
}
}
}
function runProxyRequests() {
- if(!self::$has_proxy) {
+ if ( !self::$has_proxy ) {
$this->markTestIncomplete( "This test requires a proxy." );
}
- self::runHTTPGets(self::$proxy);
- self::runHTTPPosts(self::$proxy);
- self::runHTTPRequests(self::$proxy);
+ self::runHTTPGets( self::$proxy );
+ self::runHTTPPosts( self::$proxy );
+ self::runHTTPRequests( self::$proxy );
// Set false here to do noProxy
- self::runHTTPGets(false);
- self::runHTTPPosts(false);
- self::runHTTPRequests(false);
+ self::runHTTPGets( false );
+ self::runHTTPPosts( false );
+ self::runHTTPRequests( false );
}
function testProxyDefault() {
"domain" => "ac.th",
"path" => "/path/",
) );
- $this->assertFalse($c->canServeDomain("ac.th"));
+ $this->assertFalse( $c->canServeDomain( "ac.th" ) );
$c = new MockCookie( "name", "value",
array(
"path" => "/path/",
) );
- $this->assertTrue($c->canServeDomain("example.com"));
- $this->assertFalse($c->canServeDomain("www.example.com"));
+ $this->assertTrue( $c->canServeDomain( "example.com" ) );
+ $this->assertFalse( $c->canServeDomain( "www.example.com" ) );
$c = new MockCookie( "name", "value",
array(
"path" => "/path/",
) );
- $this->assertFalse($c->canServeDomain("www.example.net"));
- $this->assertFalse($c->canServeDomain("example.com"));
- $this->assertTrue($c->canServeDomain("www.example.com"));
+ $this->assertFalse( $c->canServeDomain( "www.example.net" ) );
+ $this->assertFalse( $c->canServeDomain( "example.com" ) );
+ $this->assertTrue( $c->canServeDomain( "www.example.com" ) );
- $this->assertFalse($c->canServePath("/"));
- $this->assertFalse($c->canServePath("/bogus/path/"));
- $this->assertFalse($c->canServePath("/path"));
- $this->assertTrue($c->canServePath("/path/"));
+ $this->assertFalse( $c->canServePath( "/" ) );
+ $this->assertFalse( $c->canServePath( "/bogus/path/" ) );
+ $this->assertFalse( $c->canServePath( "/path" ) );
+ $this->assertTrue( $c->canServePath( "/path/" ) );
- $this->assertTrue($c->isUnExpired());
+ $this->assertTrue( $c->isUnExpired() );
- $this->assertEquals("", $c->serializeToHttpRequest("/path/", "www.example.net"));
- $this->assertEquals("", $c->serializeToHttpRequest("/", "www.example.com"));
- $this->assertEquals("name=value", $c->serializeToHttpRequest("/path/", "www.example.com"));
+ $this->assertEquals( "", $c->serializeToHttpRequest( "/path/", "www.example.net" ) );
+ $this->assertEquals( "", $c->serializeToHttpRequest( "/", "www.example.com" ) );
+ $this->assertEquals( "name=value", $c->serializeToHttpRequest( "/path/", "www.example.com" ) );
$c = new MockCookie( "name", "value",
array(
"domain" => "www.example.com",
"path" => "/path/",
) );
- $this->assertFalse($c->canServeDomain("example.com"));
- $this->assertFalse($c->canServeDomain("www.example.net"));
- $this->assertTrue($c->canServeDomain("www.example.com"));
+ $this->assertFalse( $c->canServeDomain( "example.com" ) );
+ $this->assertFalse( $c->canServeDomain( "www.example.net" ) );
+ $this->assertTrue( $c->canServeDomain( "www.example.com" ) );
$c = new MockCookie( "name", "value",
array(
"path" => "/path/",
"expires" => "-1 day",
) );
- $this->assertFalse($c->isUnExpired());
- $this->assertEquals("", $c->serializeToHttpRequest("/path/", "www.example.com"));
+ $this->assertFalse( $c->isUnExpired() );
+ $this->assertEquals( "", $c->serializeToHttpRequest( "/path/", "www.example.com" ) );
$c = new MockCookie( "name", "value",
array(
"path" => "/path/",
"expires" => "+1 day",
) );
- $this->assertTrue($c->isUnExpired());
- $this->assertEquals("name=value", $c->serializeToHttpRequest("/path/", "www.example.com"));
+ $this->assertTrue( $c->isUnExpired() );
+ $this->assertEquals( "name=value", $c->serializeToHttpRequest( "/path/", "www.example.com" ) );
}
function testCookieJarSetCookie() {
"expires" => "-1 day",
) );
- $this->assertEquals("name4=value", $cj->serializeToHttpRequest("/path/", "www.example.net"));
- $this->assertEquals("name3=value", $cj->serializeToHttpRequest("/", "www.example.com"));
- $this->assertEquals("name=value; name3=value", $cj->serializeToHttpRequest("/path/", "www.example.com"));
+ $this->assertEquals( "name4=value", $cj->serializeToHttpRequest( "/path/", "www.example.net" ) );
+ $this->assertEquals( "name3=value", $cj->serializeToHttpRequest( "/", "www.example.com" ) );
+ $this->assertEquals( "name=value; name3=value", $cj->serializeToHttpRequest( "/path/", "www.example.com" ) );
$cj->setCookie( "name5", "value",
array(
"path" => "/path/",
"expires" => "+1 day",
) );
- $this->assertEquals("name4=value; name5=value", $cj->serializeToHttpRequest("/path/", "www.example.net"));
+ $this->assertEquals( "name4=value; name5=value", $cj->serializeToHttpRequest( "/path/", "www.example.net" ) );
$cj->setCookie( "name4", "value",
array(
"path" => "/path/",
"expires" => "-1 day",
) );
- $this->assertEquals("name5=value", $cj->serializeToHttpRequest("/path/", "www.example.net"));
+ $this->assertEquals( "name5=value", $cj->serializeToHttpRequest( "/path/", "www.example.net" ) );
}
function testParseResponseHeader() {
$h[] = "Set-Cookie: name4=value; domain=.example.com; path=/; expires=Mon, 09-Dec-2029 13:46:00 GMT";
$cj->parseCookieResponseHeader( $h[0], "www.example.com" );
- $this->assertEquals("name4=value", $cj->serializeToHttpRequest("/", "www.example.com"));
+ $this->assertEquals( "name4=value", $cj->serializeToHttpRequest( "/", "www.example.com" ) );
$h[] = "name4=value2; domain=.example.com; path=/path/; expires=Mon, 09-Dec-2029 13:46:00 GMT";
$cj->parseCookieResponseHeader( $h[1], "www.example.com" );
- $this->assertEquals("", $cj->serializeToHttpRequest("/", "www.example.com"));
- $this->assertEquals("name4=value2", $cj->serializeToHttpRequest("/path/", "www.example.com"));
+ $this->assertEquals( "", $cj->serializeToHttpRequest( "/", "www.example.com" ) );
+ $this->assertEquals( "name4=value2", $cj->serializeToHttpRequest( "/path/", "www.example.com" ) );
$h[] = "name5=value3; domain=.example.com; path=/path/; expires=Mon, 09-Dec-2029 13:46:00 GMT";
$cj->parseCookieResponseHeader( $h[2], "www.example.com" );
- $this->assertEquals("name4=value2; name5=value3", $cj->serializeToHttpRequest("/path/", "www.example.com"));
+ $this->assertEquals( "name4=value2; name5=value3", $cj->serializeToHttpRequest( "/path/", "www.example.com" ) );
$h[] = "name6=value3; domain=.example.net; path=/path/; expires=Mon, 09-Dec-2029 13:46:00 GMT";
$cj->parseCookieResponseHeader( $h[3], "www.example.com" );
- $this->assertEquals("", $cj->serializeToHttpRequest("/path/", "www.example.net"));
+ $this->assertEquals( "", $cj->serializeToHttpRequest( "/path/", "www.example.net" ) );
$h[] = "name6=value0; domain=.example.net; path=/path/; expires=Mon, 09-Dec-1999 13:46:00 GMT";
$cj->parseCookieResponseHeader( $h[4], "www.example.net" );
- $this->assertEquals("", $cj->serializeToHttpRequest("/path/", "www.example.net"));
+ $this->assertEquals( "", $cj->serializeToHttpRequest( "/path/", "www.example.net" ) );
$h[] = "name6=value4; domain=.example.net; path=/path/; expires=Mon, 09-Dec-2029 13:46:00 GMT";
$cj->parseCookieResponseHeader( $h[5], "www.example.net" );
- $this->assertEquals("name6=value4", $cj->serializeToHttpRequest("/path/", "www.example.net"));
+ $this->assertEquals( "name6=value4", $cj->serializeToHttpRequest( "/path/", "www.example.net" ) );
}
function runCookieRequests() {
$jar = $r->getCookieJar();
$this->assertThat( $jar, $this->isInstanceOf( 'CookieJar' ) );
- if ( is_a($r, 'PhpHttpRequest') && version_compare( '5.1.7', phpversion(), '>' ) ) {
+ if ( is_a( $r, 'PhpHttpRequest' ) && version_compare( '5.1.7', phpversion(), '>' ) ) {
$this->markTestSkipped( 'Redirection fails or crashes PHP on 5.1.6 and prior' );
}
$serialized = $jar->serializeToHttpRequest( "/search?q=test", "www.php.net" );
50 => 12,
17 => 4,
18 => 4 ) ) );
- foreach( $vals as $row ) {
+ foreach ( $vals as $row ) {
extract( $row );
- foreach( $tests as $max => $expected ) {
+ foreach ( $tests as $max => $expected ) {
$y = round( $expected * $height / $width );
$result = wfFitBoxWidth( $width, $height, $max );
$y2 = round( $result * $height / $width );
global $wgMemc, $wgRequest, $wgUser, $wgContLang;
$wgUser = new User;
- $wgRequest = new FauxRequest(array());
+ $wgRequest = new FauxRequest( array() );
$wgMemc = new FakeMemCachedClient;
$wgContLang = Language::factory( 'tg' );
$this->lang = new LanguageTest();
function tearDown() {
global $wgMemc;
- unset($wgMemc);
- unset($this->lc);
- unset($this->lang);
+ unset( $wgMemc );
+ unset( $this->lc );
+ unset( $this->lang );
}
function testGetPreferredVariantDefaults() {
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, false));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, true));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, false));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, true));
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, false ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, true ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, false ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, true ) );
}
function testGetPreferredVariantHeaders() {
global $wgRequest;
- $wgRequest->setHeader('Accept-Language', 'tg-latn');
+ $wgRequest->setHeader( 'Accept-Language', 'tg-latn' );
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, false));
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(false, true));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, false));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, true));
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, false ) );
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( false, true ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, false ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, true ) );
}
function testGetPreferredVariantHeaderWeight() {
global $wgRequest;
- $wgRequest->setHeader('Accept-Language', 'tg;q=1');
+ $wgRequest->setHeader( 'Accept-Language', 'tg;q=1' );
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, false));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, true));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, false));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, true));
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, false ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, true ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, false ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, true ) );
}
function testGetPreferredVariantHeaderWeight2() {
global $wgRequest;
- $wgRequest->setHeader('Accept-Language', 'tg-latn;q=1');
+ $wgRequest->setHeader( 'Accept-Language', 'tg-latn;q=1' );
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, false));
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(false, true));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, false));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, true));
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, false ) );
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( false, true ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, false ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, true ) );
}
function testGetPreferredVariantHeaderMulti() {
global $wgRequest;
- $wgRequest->setHeader('Accept-Language', 'en, tg-latn;q=1');
+ $wgRequest->setHeader( 'Accept-Language', 'en, tg-latn;q=1' );
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, false));
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(false, true));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, false));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, true));
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, false ) );
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( false, true ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, false ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, true ) );
}
function testGetPreferredVariantUserOption() {
global $wgUser;
$wgUser = new User;
- $wgUser->setId(1);
+ $wgUser->setId( 1 );
$wgUser->mDataLoaded = true;
- $wgUser->setOption('variant', 'tg-latn');
+ $wgUser->setOption( 'variant', 'tg-latn' );
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, false));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, true));
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(true, false));
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(true, true));
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, false ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, true ) );
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( true, false ) );
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( true, true ) );
}
function testGetPreferredVariantHeaderUserVsUrl() {
global $wgRequest, $wgUser, $wgContLang;
$wgContLang = Language::factory( 'tg-latn' );
- $wgRequest->setVal('variant', 'tg');
- $wgUser = User::newFromId("admin");
- $wgUser->setId(1);
- $wgUser->setOption('variant', 'tg-latn'); // The user's data is ignored
+ $wgRequest->setVal( 'variant', 'tg' );
+ $wgUser = User::newFromId( "admin" );
+ $wgUser->setId( 1 );
+ $wgUser->setOption( 'variant', 'tg-latn' ); // The user's data is ignored
// because the variant is set in the URL.
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, false));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(true, true));
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, false ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( true, true ) );
}
global $wgDefaultLanguageVariant;
$wgDefaultLanguageVariant = 'tg-latn';
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(false, false));
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(false, true));
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(true, false));
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(true, true));
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( false, false ) );
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( false, true ) );
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( true, false ) );
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( true, true ) );
}
function testGetPreferredVariantDefaultLanguageVsUrlVariant() {
$wgContLang = Language::factory( 'tg-latn' );
$wgDefaultLanguageVariant = 'tg';
- $wgRequest->setVal('variant', null);
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, false));
- $this->assertEquals('tg', $this->lc->getPreferredVariant(false, true));
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(true, false));
- $this->assertEquals('tg-latn', $this->lc->getPreferredVariant(true, true));
+ $wgRequest->setVal( 'variant', null );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, false ) );
+ $this->assertEquals( 'tg', $this->lc->getPreferredVariant( false, true ) );
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( true, false ) );
+ $this->assertEquals( 'tg-latn', $this->lc->getPreferredVariant( true, true ) );
}
}
function tearDown() {
global $wgContLang;
- unset($wgContLang);
+ unset( $wgContLang );
}
function testGetHashPath() {
$this->assertEquals( '/testdir/archive/a/a2/!', $this->file_hl2->getArchivePath( '!' ) );
}
- function testGetThumbPath() {
+ function testGetThumbPath() {
$this->assertEquals( '/testdir/thumb/Test!', $this->file_hl0->getThumbPath() );
$this->assertEquals( '/testdir/thumb/a/a2/Test!', $this->file_hl2->getThumbPath() );
$this->assertEquals( '/testdir/thumb/Test!/x', $this->file_hl0->getThumbPath( 'x' ) );
}
- function reportPercentage( $success, $total ) {}
+ function reportPercentage( $success, $total ) { }
}
class MediaWikiParserTestSuite extends PHPUnit_Framework_TestSuite {
static public $parser;
static public $iter;
- public static function addTables(&$tables) {
+ public static function addTables( &$tables ) {
$tables[] = 'user_properties';
$tables[] = 'filearchive';
$tables[] = 'logging';
self::$iter = new TestFileIterator( PARSER_TESTS );
- foreach(self::$iter as $i => $test) {
- $suite->addTest(new ParserUnitTest($i, $test['test']));
+ foreach ( self::$iter as $i => $test ) {
+ $suite->addTest( new ParserUnitTest( $i, $test['test'] ) );
self::$count++;
}
- unset($tests);
+ unset( $tests );
self::$parser = new PTShell;
- self::$iter->setParser(self::$parser);
+ self::$iter->setParser( self::$parser );
self::$parser->recorder->start();
self::$parser->setupDatabase();
self::$iter->rewind();
$wgMessageCache = new StubObject( 'wgMessageCache', 'MessageCache',
array( $messageMemc, $wgUseDatabaseMessages,
$wgMsgCacheExpiry, wfWikiID() ) );
- if( $wgStyleDirectory === false) $wgStyleDirectory = "$IP/skins";
+ if ( $wgStyleDirectory === false ) $wgStyleDirectory = "$IP/skins";
return $suite;
}
/* $this->teardownDatabase(); */
$this->recorder->report();
$this->recorder->end();
- $this->teardownUploadDir($this->uploadDir);
+ $this->teardownUploadDir( $this->uploadDir );
}
- public function count() {return self::$count;}
+ public function count() { return self::$count; }
public function toString() {
return "MediaWiki Parser Tests";
* @param array $files full paths to files to delete.
*/
private static function deleteFiles( $files ) {
- foreach( $files as $file ) {
- if( file_exists( $file ) ) {
+ foreach ( $files as $file ) {
+ if ( file_exists( $file ) ) {
unlink( $file );
}
}
* @param array $dirs full paths to directories to delete.
*/
private static function deleteDirs( $dirs ) {
- foreach( $dirs as $dir ) {
- if( is_dir( $dir ) ) {
+ foreach ( $dirs as $dir ) {
+ if ( is_dir( $dir ) ) {
rmdir( $dir );
}
}
private $test = "";
public function testBogus() {
- $this->markTestSkipped("This is a stub");
+ $this->markTestSkipped( "This is a stub" );
}
- public function __construct($number = null, $test = null) {
+ public function __construct( $number = null, $test = null ) {
$this->number = $number;
$this->test = $test;
}
- function count() {return 1;}
+ function count() { return 1; }
- public function run(PHPUnit_Framework_TestResult $result = NULL) {
+ public function run( PHPUnit_Framework_TestResult $result = NULL ) {
PHPUnit_Framework_Assert::resetCount();
- if ($result === NULL) {
+ if ( $result === NULL ) {
$result = new PHPUnit_Framework_TestResult;
}
$t = MediaWikiParserTestSuite::$iter->current();
$k = MediaWikiParserTestSuite::$iter->key();
- if(!MediaWikiParserTestSuite::$iter->valid()) {
+ if ( !MediaWikiParserTestSuite::$iter->valid() ) {
return;
}
// The only way this should happen is if the parserTest.txt
// file were modified while the script is running.
- if($k != $this->number) {
+ if ( $k != $this->number ) {
$i = $this->number;
- wfDie("I got confused!\n");
+ wfDie( "I got confused!\n" );
}
- $result->startTest($this);
+ $result->startTest( $this );
PHPUnit_Util_Timer::start();
$r = false;
$r = MediaWikiParserTestSuite::$parser->runTest(
$t['test'], $t['input'], $t['result'], $t['options'], $t['config']
);
- PHPUnit_Framework_Assert::assertTrue(true, $t['test']);
+ PHPUnit_Framework_Assert::assertTrue( true, $t['test'] );
}
- catch (PHPUnit_Framework_AssertionFailedError $e) {
- $result->addFailure($this, $e, PHPUnit_Util_Timer::stop());
+ catch ( PHPUnit_Framework_AssertionFailedError $e ) {
+ $result->addFailure( $this, $e, PHPUnit_Util_Timer::stop() );
}
- catch (Exception $e) {
- $result->addError($this, $e, PHPUnit_Util_Timer::stop());
+ catch ( Exception $e ) {
+ $result->addError( $this, $e, PHPUnit_Util_Timer::stop() );
}
- PHPUnit_Framework_Assert::assertTrue(true, $t['test']);
+ PHPUnit_Framework_Assert::assertTrue( true, $t['test'] );
- $result->endTest($this, PHPUnit_Util_Timer::stop());
+ $result->endTest( $this, PHPUnit_Util_Timer::stop() );
- MediaWikiParserTestSuite::$parser->recorder->record($t['test'], $r);
+ MediaWikiParserTestSuite::$parser->recorder->record( $t['test'], $r );
MediaWikiParserTestSuite::$iter->next();
- $this->addToAssertionCount(PHPUnit_Framework_Assert::getCount());
+ $this->addToAssertionCount( PHPUnit_Framework_Assert::getCount() );
return $result;
}
}
function showSuccess( $desc ) {
- PHPUnit_Framework_Assert::assertTrue(true, $desc);
+ PHPUnit_Framework_Assert::assertTrue( true, $desc );
return true;
}
function showFailure( $desc, $expected, $got ) {
- PHPUnit_Framework_Assert::assertEquals($expected, $got, $desc);
+ PHPUnit_Framework_Assert::assertEquals( $expected, $got, $desc );
}
}
$db = wfGetDB( DB_MASTER );
$oldTableNames = array();
- foreach( $tables as $table )
+ foreach ( $tables as $table )
$oldTableNames[$table] = $db->tableName( $table );
- if($db->getType() == 'oracle') {
+ if ( $db->getType() == 'oracle' ) {
$wgDBprefix = 'pt_';
} else {
$wgDBprefix = 'parsertest_';
$db->tablePrefix( $wgDBprefix );
- if( $db->isOpen() ) {
+ if ( $db->isOpen() ) {
foreach ( $tables as $tbl ) {
$newTableName = $db->tableName( $tbl );
$tableName = $oldTableNames[$tbl];
'wgCompressRevisions' => false,
'wgInputEncoding' => 'utf-8',
'wgOutputEncoding' => 'utf-8' );
- foreach( $globalSet as $var => $data ) {
+ foreach ( $globalSet as $var => $data ) {
$this->saveGlobals[$var] = $GLOBALS[$var];
$GLOBALS[$var] = $data;
}
}
function tearDown() {
- foreach( $this->saveGlobals as $var => $data ) {
+ foreach ( $this->saveGlobals as $var => $data ) {
$GLOBALS[$var] = $data;
}
}
// Command line only
$wgSeleniumTestsRunMode = 'cli';
-if( $wgSeleniumTestsRunMode == 'cli' && php_sapi_name() != 'cli' ) {
+if ( $wgSeleniumTestsRunMode == 'cli' && php_sapi_name() != 'cli' ) {
echo 'Must be run from the command line.';
die( -1 );
}
// include path and installation instructions
// URL: http://localhost/tests/RunSeleniumTests.php
-//set_include_path( get_include_path() . PATH_SEPARATOR . './PEAR/' );
+// set_include_path( get_include_path() . PATH_SEPARATOR . './PEAR/' );
// Hostname of selenium server
$wgSeleniumTestsSeleniumHost = 'http://localhost';
// Common browsers on Windows platform
// Use the *chrome handler in order to be able to test file uploads
// further solution suggestions: http://www.brokenbuild.com/blog/2007/06/07/testing-file-uploads-with-selenium-rc-and-firefoxor-reducing-javascript-security-in-firefox-for-fun-and-profit/
-//$wgSeleniumTestsBrowsers['firefox'] = '*firefox c:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe';
+// $wgSeleniumTestsBrowsers['firefox'] = '*firefox c:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe';
$wgSeleniumTestsBrowsers['firefox'] = '*chrome c:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe';
$wgSeleniumTestsBrowsers['iexplorer'] = '*iexploreproxy';
$wgSeleniumTestSuites = array();
// Todo: include automatically
-#include_once '<your tests>';
+# include_once '<your tests>';
// Here, you can override standard setting
if ( file_exists( 'LocalSeleniumSettings.php' ) ) {
function setUp() {
global $wgDBprefix, $wgDBtype;
$this->db = wfGetDB( DB_MASTER );
- if( !$this->db ) {
+ if ( !$this->db ) {
$this->markTestIncomplete( "Can't find a database to test with." );
}
$this->insertSearchData();
$this->insertSearchData();
- $searchType = preg_replace("/Database/", "Search",
- get_class($this->db));
+ $searchType = preg_replace( "/Database/", "Search",
+ get_class( $this->db ) );
$this->search = new $searchType( $this->db );
}
function tearDown() {
$this->removeSearchData();
- if( !is_null( $this->db ) ) {
+ if ( !is_null( $this->db ) ) {
wfGetLB()->closeConnecton( $this->db );
}
unset( $this->db );
}
function insertSearchData() {
- if( $this->pageExists( 'Not_Main_Page' ) ) {
+ if ( $this->pageExists( 'Not_Main_Page' ) ) {
return;
}
- $this->insertPage("Not_Main_Page", "This is not a main page", 0);
- $this->insertPage('Talk:Not_Main_Page', 'This is not a talk page to the main page, see [[smithee]]', 1);
- $this->insertPage('Smithee', 'A smithee is one who smiths. See also [[Alan Smithee]]', 0);
- $this->insertPage('Talk:Smithee', 'This article sucks.', 1);
- $this->insertPage('Unrelated_page', 'Nothing in this page is about the S word.', 0);
- $this->insertPage('Another_page', 'This page also is unrelated.', 0);
- $this->insertPage('Help:Help', 'Help me!', 4);
- $this->insertPage('Thppt', 'Blah blah', 0);
- $this->insertPage('Alan_Smithee', 'yum', 0);
- $this->insertPage('Pages', 'are\'food', 0);
- $this->insertPage('HalfOneUp', 'AZ', 0);
- $this->insertPage('FullOneUp', 'AZ', 0);
- $this->insertPage('HalfTwoLow', 'az', 0);
- $this->insertPage('FullTwoLow', 'az', 0);
- $this->insertPage('HalfNumbers', '1234567890', 0);
- $this->insertPage('FullNumbers', '1234567890', 0);
- $this->insertPage('DomainName', 'example.com', 0);
+ $this->insertPage( "Not_Main_Page", "This is not a main page", 0 );
+ $this->insertPage( 'Talk:Not_Main_Page', 'This is not a talk page to the main page, see [[smithee]]', 1 );
+ $this->insertPage( 'Smithee', 'A smithee is one who smiths. See also [[Alan Smithee]]', 0 );
+ $this->insertPage( 'Talk:Smithee', 'This article sucks.', 1 );
+ $this->insertPage( 'Unrelated_page', 'Nothing in this page is about the S word.', 0 );
+ $this->insertPage( 'Another_page', 'This page also is unrelated.', 0 );
+ $this->insertPage( 'Help:Help', 'Help me!', 4 );
+ $this->insertPage( 'Thppt', 'Blah blah', 0 );
+ $this->insertPage( 'Alan_Smithee', 'yum', 0 );
+ $this->insertPage( 'Pages', 'are\'food', 0 );
+ $this->insertPage( 'HalfOneUp', 'AZ', 0 );
+ $this->insertPage( 'FullOneUp', 'AZ', 0 );
+ $this->insertPage( 'HalfTwoLow', 'az', 0 );
+ $this->insertPage( 'FullTwoLow', 'az', 0 );
+ $this->insertPage( 'HalfNumbers', '1234567890', 0 );
+ $this->insertPage( 'FullNumbers', '1234567890', 0 );
+ $this->insertPage( 'DomainName', 'example.com', 0 );
}
function removeSearchData() {
return;
- while( count($this->pageList) ) {
+ while ( count( $this->pageList ) ) {
list( $title, $id ) = array_pop( $this->pageList );
$article = new Article( $title, $id );
- $article->doDeleteArticle("Search Test");
+ $article->doDeleteArticle( "Search Test" );
}
}
function fetchIds( $results ) {
$matches = array();
- while( $row = $results->next() ) {
+ while ( $row = $results->next() ) {
$matches[] = $row->getTitle()->getPrefixedText();
}
$results->free();
$article = new Article( $title );
$pageId = $article->getId();
$created = false;
- if( $pageId == 0 ) {
+ if ( $pageId == 0 ) {
# must create the page...
$pageId = $article->insertOn( $dbw );
$created = true;
$changed = $article->updateIfNewerOn( $dbw, $revision );
$GLOBALS['wgTitle'] = $title;
- if( $created ) {
+ if ( $created ) {
Article::onArticleCreate( $title );
$article->createUpdates( $revision );
- } elseif( $changed ) {
+ } elseif ( $changed ) {
Article::onArticleEdit( $title );
$article->editUpdates(
$text, $comment, false, 0, $revId );
}
- $su = new SearchUpdate($article->getId(), $pageName, $text);
+ $su = new SearchUpdate( $article->getId(), $pageName, $text );
$su->doUpdate();
$this->pageList[] = array( $title, $article->getId() );
}
function open( $server, $user, $password, $dbName ) { return true; }
- function doQuery( $sql ) {}
- function fetchObject( $res ) {}
- function fetchRow( $res ) {}
- function numRows( $res ) {}
- function numFields( $res ) {}
- function fieldName( $res, $n ) {}
- function insertId() {}
- function dataSeek( $res, $row ) {}
+ function doQuery( $sql ) { }
+ function fetchObject( $res ) { }
+ function fetchRow( $res ) { }
+ function numRows( $res ) { }
+ function numFields( $res ) { }
+ function fieldName( $res, $n ) { }
+ function insertId() { }
+ function dataSeek( $res, $row ) { }
function lastErrno() { return 0; }
function lastError() { return ''; }
- function affectedRows() {}
- function fieldInfo( $table, $field ) {}
- function strencode( $s ) {}
- function getSoftwareLink() {}
- function getServerVersion() {}
- function getType() {}
+ function affectedRows() { }
+ function fieldInfo( $table, $field ) { }
+ function strencode( $s ) { }
+ function getSoftwareLink() { }
+ function getServerVersion() { }
+ function getType() { }
}
class MockSearch extends SearchEngine {
function getSiteParams( $conf, $wiki ) {
$site = null;
$lang = null;
- foreach( $conf->suffixes as $suffix ) {
+ foreach ( $conf->suffixes as $suffix ) {
if ( substr( $wiki, -strlen( $suffix ) ) == $suffix ) {
$site = $suffix;
$lang = substr( $wiki, 0, -strlen( $suffix ) );
$this->mConf->get( 'merge', 'enwiki', 'wiki', array(), array( 'tag' ) ),
'get(): merging setting on an existing wiki (with tag)'
);
- $this->assertEquals(
+ $this->assertEquals(
array( 'dewiki' => 'dewiki' ) + $common,
$this->mConf->get( 'merge', 'dewiki', 'wiki' ),
'get(): merging setting on an existing wiki (2)'
$wgContLang = $en = Language::factory( 'en' );
- # Collection of parameters for Language_t_Offset.
+ # Collection of parameters for Language_t_Offset.
# Format: date to be formatted, localTZoffset value, expected date
$userAdjust_tests = array(
array( 20061231235959, 0, 20061231235959 ),
array( 20061231235959, -60, 20061231225959 ),
);
- foreach( $userAdjust_tests as $data ) {
+ foreach ( $userAdjust_tests as $data ) {
$wgLocalTZoffset = $data[1];
$this->assertEquals(
self::$userName = "Useruser";
self::$altUserName = "Altuseruser";
date_default_timezone_set( $wgLocaltimezone );
- $wgLocalTZoffset = date("Z") / 60;
+ $wgLocalTZoffset = date( "Z" ) / 60;
- self::$title = Title::makeTitle(NS_MAIN, "Main Page");
- if( !isset(self::$userUser) || !(self::$userUser instanceOf User) ) {
- self::$userUser = User::newFromName(self::$userName);
+ self::$title = Title::makeTitle( NS_MAIN, "Main Page" );
+ if ( !isset( self::$userUser ) || !( self::$userUser instanceOf User ) ) {
+ self::$userUser = User::newFromName( self::$userName );
if ( !self::$userUser->getID() ) {
- self::$userUser = User::createNew(self::$userName, array(
+ self::$userUser = User::createNew( self::$userName, array(
"email" => "test@example.com",
- "real_name" => "Test User"));
+ "real_name" => "Test User" ) );
}
- self::$altUser = User::newFromName(self::$altUserName);
+ self::$altUser = User::newFromName( self::$altUserName );
if ( !self::$altUser->getID() ) {
- self::$altUser = User::createNew(self::$altUserName, array(
+ self::$altUser = User::createNew( self::$altUserName, array(
"email" => "alttest@example.com",
- "real_name" => "Test User Alt"));
+ "real_name" => "Test User Alt" ) );
}
- self::$anonUser = User::newFromId(0);
+ self::$anonUser = User::newFromId( 0 );
self::$user = self::$userUser;
}
function setUserPerm( $perm ) {
global $wgUseRCPatrol, $wgUseNPPatrol;
- if( is_array( $perm ) ) {
+ if ( is_array( $perm ) ) {
self::$user->mRights = $perm;
} else {
- self::$user->mRights = array($perm);
+ self::$user->mRights = array( $perm );
}
}
function setTitle( $ns, $title = "Main_Page" ) {
- self::$title = Title::makeTitle($ns, $title);
+ self::$title = Title::makeTitle( $ns, $title );
}
function setUser( $userName = null ) {
$this->setTitle( NS_TALK );
$this->setUserPerm( "createtalk" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array(), $res);
+ $this->assertEquals( array(), $res );
$this->setTitle( NS_TALK );
$this->setUserPerm( "createpage" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array( array( "nocreatetext") ), $res);
+ $this->assertEquals( array( array( "nocreatetext" ) ), $res );
$this->setTitle( NS_TALK );
$this->setUserPerm( "" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array( array( 'nocreatetext' ) ), $res);
+ $this->assertEquals( array( array( 'nocreatetext' ) ), $res );
$this->setTitle( NS_MAIN );
$this->setUserPerm( "createpage" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array( ), $res);
+ $this->assertEquals( array( ), $res );
$this->setTitle( NS_MAIN );
$this->setUserPerm( "createtalk" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array( array( 'nocreatetext' ) ), $res);
+ $this->assertEquals( array( array( 'nocreatetext' ) ), $res );
$this->setUser( self::$userName );
$this->setTitle( NS_TALK );
$this->setUserPerm( "createtalk" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array( ), $res);
+ $this->assertEquals( array( ), $res );
$this->setTitle( NS_TALK );
$this->setUserPerm( "createpage" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res);
+ $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res );
$this->setTitle( NS_TALK );
$this->setUserPerm( "" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res);
+ $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res );
$this->setTitle( NS_MAIN );
$this->setUserPerm( "createpage" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array( ), $res);
+ $this->assertEquals( array( ), $res );
$this->setTitle( NS_MAIN );
$this->setUserPerm( "createtalk" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res);
+ $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res );
$this->setTitle( NS_MAIN );
$this->setUserPerm( "" );
$res = self::$title->getUserPermissionsErrors( 'create', self::$user );
- $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res);
+ $this->assertEquals( array( array( 'nocreate-loggedin' ) ), $res );
$this->setUser( 'anon' );
$this->setTitle( NS_USER, self::$userName . '' );
$this->setUserPerm( "" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals( array( array( 'cant-move-user-page' ), array( 'movenologintext' ) ), $res);
+ $this->assertEquals( array( array( 'cant-move-user-page' ), array( 'movenologintext' ) ), $res );
$this->setTitle( NS_USER, self::$userName . '/subpage' );
$this->setUserPerm( "" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals( array( array( 'movenologintext' ) ), $res);
+ $this->assertEquals( array( array( 'movenologintext' ) ), $res );
$this->setTitle( NS_USER, self::$userName . '' );
$this->setUserPerm( "move-rootuserpages" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals( array( array( 'movenologintext' ) ), $res);
+ $this->assertEquals( array( array( 'movenologintext' ) ), $res );
$this->setTitle( NS_USER, self::$userName . '/subpage' );
$this->setUserPerm( "move-rootuserpages" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals(array( array( 'movenologintext' ) ), $res);
+ $this->assertEquals( array( array( 'movenologintext' ) ), $res );
$this->setTitle( NS_USER, self::$userName . '' );
$this->setUserPerm( "" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals( array( array( 'cant-move-user-page' ), array( 'movenologintext' ) ), $res);
+ $this->assertEquals( array( array( 'cant-move-user-page' ), array( 'movenologintext' ) ), $res );
$this->setTitle( NS_USER, self::$userName . '/subpage' );
$this->setUserPerm( "" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals( array( array( 'movenologintext' ) ), $res);
+ $this->assertEquals( array( array( 'movenologintext' ) ), $res );
$this->setTitle( NS_USER, self::$userName . '' );
$this->setUserPerm( "move-rootuserpages" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals( array( array( 'movenologintext' ) ), $res);
+ $this->assertEquals( array( array( 'movenologintext' ) ), $res );
$this->setTitle( NS_USER, self::$userName . '/subpage' );
$this->setUserPerm( "move-rootuserpages" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals(array( array( 'movenologintext' ) ), $res);
+ $this->assertEquals( array( array( 'movenologintext' ) ), $res );
$this->setUser( self::$userName );
$this->setTitle( NS_FILE, "img.png" );
$this->setUserPerm( "" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals( array( array( 'movenotallowedfile' ), array( 'movenotallowed' ) ), $res);
+ $this->assertEquals( array( array( 'movenotallowedfile' ), array( 'movenotallowed' ) ), $res );
$this->setTitle( NS_FILE, "img.png" );
$this->setUserPerm( "movefile" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals( array( array( 'movenotallowed' ) ), $res);
+ $this->assertEquals( array( array( 'movenotallowed' ) ), $res );
$this->setUser( 'anon' );
$this->setTitle( NS_FILE, "img.png" );
$this->setUserPerm( "" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals( array( array( 'movenotallowedfile' ), array( 'movenologintext' ) ), $res);
+ $this->assertEquals( array( array( 'movenotallowedfile' ), array( 'movenologintext' ) ), $res );
$this->setTitle( NS_FILE, "img.png" );
$this->setUserPerm( "movefile" );
$res = self::$title->getUserPermissionsErrors( 'move', self::$user );
- $this->assertEquals( array( array( 'movenologintext' ) ), $res);
+ $this->assertEquals( array( array( 'movenologintext' ) ), $res );
$this->setUser( self::$userName );
$this->setUserPerm( "move" );
'' => array( array( ), array( ), array( ), true ) );
global $wgUser;
$wgUser = self::$user;
- foreach(array("edit", "protect", "") as $action) {
+ foreach ( array( "edit", "protect", "" ) as $action ) {
$this->setUserPerm( null );
$this->assertEquals( $check[$action][0],
self::$title->getUserPermissionsErrors( $action, self::$user, true ) );
function runGroupPermissions( $action, $result, $result2 = null ) {
global $wgGroupPermissions;
- if( $result2 === null ) $result2 = $result;
+ if ( $result2 === null ) $result2 = $result;
$wgGroupPermissions['autoconfirmed']['move'] = false;
$wgGroupPermissions['user']['move'] = false;
$this->assertEquals( $result2, $res );
}
- function testPermissionHooks() {}
+ function testPermissionHooks() { }
function testSpecialsAndNSPermissions() {
$this->setUser( self::$userName );
global $wgUser;
$wgNamespaceProtection[NS_USER] = array ( 'bogus' );
$this->setTitle( NS_USER );
$this->setUserPerm( '' );
- $this->assertEquals( array( array( 'badaccess-group0'), array( 'namespaceprotected', 'User' ) ),
+ $this->assertEquals( array( array( 'badaccess-group0' ), array( 'namespaceprotected', 'User' ) ),
self::$title->getUserPermissionsErrors( 'bogus', self::$user ) );
$this->setTitle( NS_MEDIAWIKI );
global $wgUser;
$wgUser = self::$user;
- $this->setTitle( NS_USER, self::$altUserName .'/test.js' );
+ $this->setTitle( NS_USER, self::$altUserName . '/test.js' );
$this->runCSSandJSPermissions(
array( array( 'badaccess-group0' ), array( 'customcssjsprotected' ) ),
array( array( 'badaccess-group0' ), array( 'customcssjsprotected' ) ),
array( array( 'badaccess-group0' ) ) );
- $this->setTitle( NS_USER, self::$altUserName .'/test.css' );
+ $this->setTitle( NS_USER, self::$altUserName . '/test.css' );
$this->runCSSandJSPermissions(
array( array( 'badaccess-group0' ), array( 'customcssjsprotected' ) ),
array( array( 'badaccess-group0' ) ),
array( array( 'badaccess-group0' ), array( 'customcssjsprotected' ) ) );
- $this->setTitle( NS_USER, self::$altUserName .'/tempo' );
+ $this->setTitle( NS_USER, self::$altUserName . '/tempo' );
$this->runCSSandJSPermissions(
array( array( 'badaccess-group0' ) ),
array( array( 'badaccess-group0' ) ),
$wgUser = self::$user;
$this->setTitle( NS_MAIN );
self::$title->mRestrictionsLoaded = true;
- $this->setUserPerm("edit");
- self::$title->mRestrictions= array("bogus" => array('bogus', "sysop", "protect", ""));
+ $this->setUserPerm( "edit" );
+ self::$title->mRestrictions = array( "bogus" => array( 'bogus', "sysop", "protect", "" ) );
$this->assertEquals( array( ),
self::$title->getUserPermissionsErrors( 'edit',
$this->assertEquals( true,
self::$title->quickUserCan( 'edit', false ) );
- self::$title->mRestrictions= array("edit" => array('bogus', "sysop", "protect", ""),
- "bogus" => array('bogus', "sysop", "protect", ""));
+ self::$title->mRestrictions = array( "edit" => array( 'bogus', "sysop", "protect", "" ),
+ "bogus" => array( 'bogus', "sysop", "protect", "" ) );
$this->assertEquals( array( array( 'badaccess-group0' ),
array( 'protectedpagetext', 'bogus' ),
array( 'protectedpagetext', 'protect' ) ),
self::$title->getUserPermissionsErrors( 'edit',
self::$user ) );
- $this->setUserPerm("");
+ $this->setUserPerm( "" );
$this->assertEquals( array( array( 'badaccess-group0' ),
array( 'protectedpagetext', 'bogus' ),
array( 'protectedpagetext', 'protect' ),
array( 'protectedpagetext', 'protect' ) ),
self::$title->getUserPermissionsErrors( 'edit',
self::$user ) );
- $this->setUserPerm(array("edit", "editprotected") );
+ $this->setUserPerm( array( "edit", "editprotected" ) );
$this->assertEquals( array( array( 'badaccess-group0' ),
array( 'protectedpagetext', 'bogus' ),
array( 'protectedpagetext', 'protect' ),
function testCascadingSourcesRestrictions() {
global $wgUser;
$wgUser = self::$user;
- $this->setTitle(NS_MAIN, "test page");
- $this->setUserPerm(array("edit", "bogus"));
+ $this->setTitle( NS_MAIN, "test page" );
+ $this->setUserPerm( array( "edit", "bogus" ) );
- self::$title->mCascadeSources = array( Title::makeTitle(NS_MAIN, "Bogus"), Title::makeTitle(NS_MAIN, "UnBogus") );
- self::$title->mCascadingRestrictions = array( "bogus" => array('bogus', "sysop", "protect", "" ) );
+ self::$title->mCascadeSources = array( Title::makeTitle( NS_MAIN, "Bogus" ), Title::makeTitle( NS_MAIN, "UnBogus" ) );
+ self::$title->mCascadingRestrictions = array( "bogus" => array( 'bogus', "sysop", "protect", "" ) );
$this->assertEquals( false,
self::$title->userCan( 'bogus' ) );
$wgUser = self::$user;
$this->setUserPerm( array( "createpage" ) );
- $this->setTitle(NS_MAIN, "test page");
+ $this->setTitle( NS_MAIN, "test page" );
self::$title->mTitleProtection['pt_create_perm'] = '';
self::$title->mTitleProtection['pt_user'] = self::$user->getID();
self::$title->mTitleProtection['pt_expiry'] = Block::infinity();
$wgUser = self::$user;
$this->setUserPerm( array( "createpage", "move" ) );
- $this->setTitle(NS_MAIN, "test page");
+ $this->setTitle( NS_MAIN, "test page" );
# $short
$this->assertEquals( array( array( 'confirmedittext' ) ),
$prev = time();
$now = time() + 120;
self::$user->mBlockedby = self::$user->getId();
- self::$user->mBlock = new Block('127.0.8.1', self::$user->getId(), self::$user->getId(),
- 'no reason given', $prev + 3600, 1, 0);
+ self::$user->mBlock = new Block( '127.0.8.1', self::$user->getId(), self::$user->getId(),
+ 'no reason given', $prev + 3600, 1, 0 );
self::$user->mBlock->mTimestamp = 0;
$this->assertEquals( array( array( 'autoblockedtext',
'[[User:Useruser|Useruser]]', 'no reason given', '127.0.0.1',
global $wgLocalTZoffset;
$wgLocalTZoffset = -60;
self::$user->mBlockedby = self::$user->getName();
- self::$user->mBlock = new Block('127.0.8.1', 2, 1, 'no reason given', $now, 0, 10 );
+ self::$user->mBlock = new Block( '127.0.8.1', 2, 1, 'no reason given', $now, 0, 10 );
$this->assertEquals( array( array( 'blockedtext',
'[[User:Useruser|Useruser]]', 'no reason given', '127.0.0.1',
'Useruser', 0, '23:00, 31 December 1969', '127.0.8.1',
require_once( dirname( dirname( __FILE__ ) ) . "/deleteArchivedRevisions.inc" );
class nullClass {
- public function handleOutput(){}
- public function purgeRedundantText(){}
+ public function handleOutput() { }
+ public function purgeRedundantText() { }
}
class UploadFromUrlTest extends ApiSetup {
}
function testClearQueue() {
- while ( $job = Job::pop() ) {}
- $this->assertFalse($job);
+ while ( $job = Job::pop() ) { }
+ $this->assertFalse( $job );
}
function testLogin() {
}
$this->assertTrue( $exception, "Got exception" );
- $wgUser->removeGroup('sysop');
+ $wgUser->removeGroup( 'sysop' );
$exception = false;
try {
$this->doApiRequest( array(
}
$this->assertTrue( $exception, "Got exception" );
- $wgUser->addGroup('*');
- $wgUser->addGroup('sysop');
+ $wgUser->addGroup( '*' );
+ $wgUser->addGroup( 'sysop' );
$exception = false;
$data = $this->doApiRequest( array(
'action' => 'upload',
'token' => $token,
), $data );
- $this->assertTrue( $data[0]['upload']['queued'], 'Job added');
+ $this->assertTrue( $data[0]['upload']['queued'], 'Job added' );
$job = Job::pop();
$this->assertThat( $job, $this->isInstanceOf( 'UploadFromUrlJob' ),
$data[2]['wsEditToken'] = $data[2]['wsToken'];
$token = md5( $data[2]['wsToken'] ) . EDIT_TOKEN_SUFFIX;
- $wgUser->addGroup('users');
+ $wgUser->addGroup( 'users' );
$data = $this->doApiRequest( array(
'action' => 'upload',
'filename' => 'Test.png',
), $data );
$job = Job::pop();
- $this->assertEquals( 'UploadFromUrlJob', get_class($job) );
+ $this->assertEquals( 'UploadFromUrlJob', get_class( $job ) );
$status = $job->run();
$this->assertTrue( $status->isOk() );
* @depends testDoDownload
*/
function testVerifyDownload( $data ) {
- $t = Title::newFromText("Test.png", NS_FILE);
+ $t = Title::newFromText( "Test.png", NS_FILE );
- $this->assertTrue($t->exists());
+ $this->assertTrue( $t->exists() );
}
}
<?php
-require_once('UploadFromUrlTest.php');
+require_once( 'UploadFromUrlTest.php' );
class UploadFromUrlTestSuite extends PHPUnit_Framework_TestSuite
{
- public static function addTables(&$tables) {
+ public static function addTables( &$tables ) {
$tables[] = 'user_properties';
$tables[] = 'filearchive';
$tables[] = 'logging';
$wgMessageCache = new StubObject( 'wgMessageCache', 'MessageCache',
array( $messageMemc, $wgUseDatabaseMessages,
$wgMsgCacheExpiry, wfWikiID() ) );
- if( $wgStyleDirectory === false) $wgStyleDirectory = "$IP/skins";
+ if ( $wgStyleDirectory === false ) $wgStyleDirectory = "$IP/skins";
}
public function tearDown() {
- $this->teardownUploadDir($this->uploadDir);
+ $this->teardownUploadDir( $this->uploadDir );
}
private $uploadDir;
* @param array $files full paths to files to delete.
*/
private static function deleteFiles( $files ) {
- foreach( $files as $file ) {
- if( file_exists( $file ) ) {
+ foreach ( $files as $file ) {
+ if ( file_exists( $file ) ) {
unlink( $file );
}
}
* @param array $dirs full paths to directories to delete.
*/
private static function deleteDirs( $dirs ) {
- foreach( $dirs as $dir ) {
- if( is_dir( $dir ) ) {
+ foreach ( $dirs as $dir ) {
+ if ( is_dir( $dir ) ) {
rmdir( $dir );
}
}
public static function suite()
{
- return new UploadFromUrlTestSuite('UploadFromUrlTest');
+ return new UploadFromUrlTestSuite( 'UploadFromUrlTest' );
}
}
}
class UploadTestHandler extends UploadBase {
- public function initializeFromRequest( &$request ) {}
+ public function initializeFromRequest( &$request ) { }
public function testTitleValidation( $name ) {
$this->mTitle = false;
$this->mDesiredDestName = $name;
require_once( "$IP/maintenance/commandLine.inc" );
$wgLocaltimezone = 'UTC';
-if( !version_compare(PHPUnit_Runner_Version::id(), "3.4.1", ">") ) {
+if ( !version_compare( PHPUnit_Runner_Version::id(), "3.4.1", ">" ) ) {
echo <<<EOF
************************************************************
}
// Prevent external cloning
- protected function __clone() {}
+ protected function __clone() { }
// Prevent external construction
- //protected function __construct() {}
+ // protected function __construct() {}
}
exit( 1 );
}
-class SeleniumTestCase extends PHPUnit_Framework_TestCase { //PHPUnit_Extensions_SeleniumTestCase
+class SeleniumTestCase extends PHPUnit_Framework_TestCase { // PHPUnit_Extensions_SeleniumTestCase
protected $selenium;
public function setUp() {
public function write( $message, $mode = false ) {
$out = '';
- //if ( $mode == MW_TESTLOGGER_RESULT_OK ) $out .= '<font color="green">';
+ // if ( $mode == MW_TESTLOGGER_RESULT_OK ) $out .= '<font color="green">';
$out .= htmlentities( $message );
- //if ( $mode == MW_TESTLOGGER_RESULT_OK ) $out .= '</font>';
+ // if ( $mode == MW_TESTLOGGER_RESULT_OK ) $out .= '</font>';
if ( $mode != MW_TESTLOGGER_CONTINUE_LINE ) {
$out .= "\n";
}
$this->selenium = Selenium::getInstance();
$this->selenium->start();
$this->login();
- //$this->loadPage( 'Testpage', 'edit' );
+ // $this->loadPage( 'Testpage', 'edit' );
}
public function tearDown() {
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class Undelete extends Maintenance {
public function __construct() {
/** */
define( 'MW_CMDLINE_CALLBACK', 'wfSetupUpdateScript' );
$wgUseMasterForMaintenance = true;
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
require( "updaters.inc" );
$wgTitle = Title::newFromText( "MediaWiki database updater" );
echo( "MediaWiki {$wgVersion} Updater\n\n" );
-if( !isset( $options['skip-compat-checks'] ) ) {
+if ( !isset( $options['skip-compat-checks'] ) ) {
install_version_checks();
} else {
print "Skipping compatibility checks, proceed at your own risk (Ctrl+C to abort)\n";
- wfCountdown(5);
+ wfCountdown( 5 );
}
# Attempt to connect to the database as a privileged user
# This will vomit up an error if there are permissions problems
$wgDatabase = wfGetDB( DB_MASTER );
-print "Going to run database updates for ".wfWikiID()."\n";
+print "Going to run database updates for " . wfWikiID() . "\n";
print "Depending on the size of your database this may take a while!\n";
-if( !isset( $options['quick'] ) ) {
+if ( !isset( $options['quick'] ) ) {
print "Abort with control-c in the next five seconds (skip this countdown with --quick) ... ";
wfCountDown( 5 );
}
# This needs to be disabled early since extensions will try to use the l10n
# cache from $wgExtensionSetupFunctions (bug 20471)
$wgLocalisationCacheConf = array(
- 'class' => 'LocalisationCache',
+ 'class' => 'LocalisationCache',
'storeClass' => 'LCStore_Null',
'storeDirectory' => false,
'manualRecache' => false,
* @author Rob Church <robchur@gmail.com>
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class UpdateArticleCount extends Maintenance {
$this->output( "Counting articles..." );
$result = $this->count();
- if( $result !== false ) {
+ if ( $result !== false ) {
$this->output( "found {$result}.\n" );
- if( $this->hasOption( 'update' ) ) {
+ if ( $this->hasOption( 'update' ) ) {
$this->output( "Updating site statistics table... " );
$dbw = wfGetDB( DB_MASTER );
$dbw->update( 'site_stats', array( 'ss_good_articles' => $result ), array( 'ss_row_id' => 1 ), __METHOD__ );
* @return string
*/
private function makeNsSet() {
- foreach( $this->namespaces as $namespace )
+ foreach ( $this->namespaces as $namespace )
$namespaces[] = intval( $namespace );
return implode( ', ', $namespaces );
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class UpdateDoubleWidthSearch extends Maintenance {
$lockTime = time();
$dbw = wfGetDB( DB_MASTER );
- if( $dbw->getType() !== 'mysql' ) {
+ if ( $dbw->getType() !== 'mysql' ) {
$this->output( "This change is only needed on MySQL, quitting..." );
- exit(1);
+ exit( 1 );
}
- $res = $this->findRows($dbw);
- $this->updateSearchIndex($maxLockTime, array($this, 'searchIndexUpdateCallback'), $dbw, $res);
+ $res = $this->findRows( $dbw );
+ $this->updateSearchIndex( $maxLockTime, array( $this, 'searchIndexUpdateCallback' ), $dbw, $res );
$this->output( "Done\n" );
}
- public function searchIndexUpdateCallback($dbw, $row) {
+ public function searchIndexUpdateCallback( $dbw, $row ) {
return $this->updateSearchIndexForPage( $dbw, $row->si_page );
}
- private function findRows($dbw) {
+ private function findRows( $dbw ) {
$searchindex = $dbw->tableName( 'searchindex' );
$regexp = '[[:<:]]u8efbd([89][1-9a]|8[b-f]|90)[[:>:]]';
$sql = "SELECT si_page FROM $searchindex
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class UpdateRestrictions extends Maintenance {
public function __construct() {
public function execute() {
$db = wfGetDB( DB_MASTER );
- if( !$db->tableExists( 'page_restrictions' ) ) {
+ if ( !$db->tableExists( 'page_restrictions' ) ) {
$this->error( "page_restrictions table does not exist", true );
}
$start = $db->selectField( 'page', 'MIN(page_id)', false, __METHOD__ );
- if( !$start ) {
+ if ( !$start ) {
$this->error( "Nothing to do.", true );
}
$end = $db->selectField( 'page', 'MAX(page_id)', false, __METHOD__ );
$blockStart = $start;
$blockEnd = $start + $this->mBatchSize - 1;
$encodedExpiry = 'infinity';
- while( $blockEnd <= $end ) {
+ while ( $blockEnd <= $end ) {
$this->output( "...doing page_id from $blockStart to $blockEnd\n" );
$cond = "page_id BETWEEN $blockStart AND $blockEnd AND page_restrictions !=''";
- $res = $db->select( 'page', array('page_id','page_namespace','page_restrictions'), $cond, __METHOD__ );
+ $res = $db->select( 'page', array( 'page_id', 'page_namespace', 'page_restrictions' ), $cond, __METHOD__ );
$batch = array();
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
$oldRestrictions = array();
- foreach( explode( ':', trim( $row->page_restrictions ) ) as $restrict ) {
+ foreach ( explode( ':', trim( $row->page_restrictions ) ) as $restrict ) {
$temp = explode( '=', trim( $restrict ) );
// Make sure we are not settings restrictions to ""
- if( count($temp) == 1 && $temp[0] ) {
+ if ( count( $temp ) == 1 && $temp[0] ) {
// old old format should be treated as edit/move restriction
$oldRestrictions["edit"] = trim( $temp[0] );
$oldRestrictions["move"] = trim( $temp[0] );
- } else if( $temp[1] ) {
+ } else if ( $temp[1] ) {
$oldRestrictions[$temp[0]] = trim( $temp[1] );
}
}
# Clear invalid columns
- if( $row->page_namespace == NS_MEDIAWIKI ) {
+ if ( $row->page_namespace == NS_MEDIAWIKI ) {
$db->update( 'page', array( 'page_restrictions' => '' ),
array( 'page_id' => $row->page_id ), __FUNCTION__ );
$this->output( "...removed dead page_restrictions column for page {$row->page_id}\n" );
}
# Update restrictions table
- foreach( $oldRestrictions as $action => $restrictions ) {
- $batch[] = array(
+ foreach ( $oldRestrictions as $action => $restrictions ) {
+ $batch[] = array(
'pr_page' => $row->page_id,
'pr_type' => $action,
'pr_level' => $restrictions,
# We use insert() and not replace() as Article.php replaces
# page_restrictions with '' when protected in the restrictions table
if ( count( $batch ) ) {
- $ok = $db->deadlockLoop( array( $db, 'insert' ), 'page_restrictions',
+ $ok = $db->deadlockLoop( array( $db, 'insert' ), 'page_restrictions',
$batch, __FUNCTION__, array( 'IGNORE' ) );
- if( !$ok ) {
+ if ( !$ok ) {
throw new MWException( "Deadlock loop failed wtf :(" );
}
}
// Kill any broken rows from previous imports
$db->delete( 'page_restrictions', array( 'pr_level' => '' ) );
// Kill other invalid rows
- $db->deleteJoin( 'page_restrictions', 'page', 'pr_page', 'page_id', array('page_namespace' => NS_MEDIAWIKI) );
+ $db->deleteJoin( 'page_restrictions', 'page', 'pr_page', 'page_id', array( 'page_namespace' => NS_MEDIAWIKI ) );
$this->output( "...Done!\n" );
}
}
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class UpdateSearchIndex extends Maintenance {
$posFile = $this->getOption( 'p', 'searchUpdate.' . wfWikiId() . '.pos' );
$end = $this->getOption( 'e', wfTimestampNow() );
if ( $this->hasOption( 's' ) ) {
- $start = $this->getOption('s');
- } elseif( is_readable( 'searchUpdate.pos' ) ) {
+ $start = $this->getOption( 's' );
+ } elseif ( is_readable( 'searchUpdate.pos' ) ) {
# B/c to the old position file name which was hardcoded
# We can safely delete the file when we're done though.
$start = file_get_contents( 'searchUpdate.pos' );
$lockTime = $this->getOption( 'l', 20 );
$this->doUpdateSearchIndex( $start, $end, $lockTime );
- if( is_writable( dirname( realpath( $posFile ) ) ) ) {
+ if ( is_writable( dirname( realpath( $posFile ) ) ) ) {
$file = fopen( $posFile, 'w' );
- if( $file !== false ) {
+ if ( $file !== false ) {
fwrite( $file, $end );
fclose( $file );
} else {
";
$res = $dbw->query( $sql, __METHOD__ );
- $this->updateSearchIndex($maxLockTime, array($this, 'searchIndexUpdateCallback'), $dbw, $res);
+ $this->updateSearchIndex( $maxLockTime, array( $this, 'searchIndexUpdateCallback' ), $dbw, $res );
$this->output( "Done\n" );
}
- public function searchIndexUpdateCallback($dbw, $row) {
+ public function searchIndexUpdateCallback( $dbw, $row ) {
if ( $row->rc_type == RC_MOVE || $row->rc_type == RC_MOVE_OVER_REDIRECT ) {
# Rename searchindex entry
$titleObj = Title::makeTitle( $row->rc_moved_to_ns, $row->rc_moved_to_title );
* @ingroup Maintenance
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class UpdateSpecialPages extends Maintenance {
public function __construct() {
$wgOut->disable();
$dbw = wfGetDB( DB_MASTER );
- foreach( $wgSpecialPageCacheUpdates as $special => $call ) {
- if( !is_callable($call) ) {
+ foreach ( $wgSpecialPageCacheUpdates as $special => $call ) {
+ if ( !is_callable( $call ) ) {
$this->error( "Uncallable function $call!" );
continue;
}
call_user_func( $call, $dbw );
$t2 = explode( ' ', microtime() );
$this->output( sprintf( '%-30s ', $special ) );
- $elapsed = ($t2[0] - $t1[0]) + ($t2[1] - $t1[1]);
+ $elapsed = ( $t2[0] - $t1[0] ) + ( $t2[1] - $t1[1] );
$hours = intval( $elapsed / 3600 );
$minutes = intval( $elapsed % 3600 / 60 );
$seconds = $elapsed - $hours * 3600 - $minutes * 60;
// This is needed to initialise $wgQueryPages
require_once( "$IP/includes/QueryPage.php" );
- foreach( $wgQueryPages as $page ) {
+ foreach ( $wgQueryPages as $page ) {
@list( $class, $special, $limit ) = $page;
# --list : just show the name of pages
- if( $this->hasOption('list') ) {
+ if ( $this->hasOption( 'list' ) ) {
$this->output( "$special\n" );
continue;
}
- if ( !$this->hasOption('override') && $wgDisableQueryPageUpdate && in_array( $special, $wgDisableQueryPageUpdate ) ) {
+ if ( !$this->hasOption( 'override' ) && $wgDisableQueryPageUpdate && in_array( $special, $wgDisableQueryPageUpdate ) ) {
$this->output( sprintf( "%-30s disabled\n", $special ) );
continue;
}
}
$queryPage = new $class;
- if( !$this->hasOption('only') || $this->getOption('only') == $queryPage->getName() ) {
+ if ( !$this->hasOption( 'only' ) || $this->getOption( 'only' ) == $queryPage->getName() ) {
$this->output( sprintf( '%-30s ', $special ) );
if ( $queryPage->isExpensive() ) {
$t1 = explode( ' ', microtime() );
} else {
$this->output( "got $num rows in " );
- $elapsed = ($t2[0] - $t1[0]) + ($t2[1] - $t1[1]);
+ $elapsed = ( $t2[0] - $t1[0] ) + ( $t2[1] - $t1[1] );
$hours = intval( $elapsed / 3600 );
$minutes = intval( $elapsed % 3600 / 60 );
$seconds = $elapsed - $hours * 3600 - $minutes * 60;
$this->output( sprintf( "%.2fs\n", $seconds ) );
}
# Reopen any connections that have closed
- if ( !wfGetLB()->pingAll()) {
+ if ( !wfGetLB()->pingAll() ) {
$this->output( "\n" );
do {
$this->error( "Connection failed, reconnecting in 10 seconds..." );
array( 'do_logging_timestamp_index' ),
array( 'add_field', 'ipblocks', 'ipb_range_start', 'patch-ipb_range_start.sql' ),
array( 'do_page_random_update' ),
- array( 'add_field', 'user', 'user_registration','patch-user_registration.sql' ),
+ array( 'add_field', 'user', 'user_registration', 'patch-user_registration.sql' ),
array( 'do_templatelinks_update' ),
array( 'add_table', 'externallinks', 'patch-externallinks.sql' ),
array( 'add_table', 'job', 'patch-job.sql' ),
// 1.11
array( 'add_field', 'ipblocks', 'ipb_block_email', 'patch-ipb_emailban.sql' ),
array( 'do_categorylinks_indices_update' ),
- array( 'add_field', 'oldimage', 'oi_metadata', 'patch-oi_metadata.sql'),
+ array( 'add_field', 'oldimage', 'oi_metadata', 'patch-oi_metadata.sql' ),
array( 'do_archive_user_index' ),
array( 'do_image_user_index' ),
array( 'do_oldimage_user_index' ),
- array( 'add_field', 'archive', 'ar_page_id', 'patch-archive-page_id.sql'),
+ array( 'add_field', 'archive', 'ar_page_id', 'patch-archive-page_id.sql' ),
array( 'add_field', 'image', 'img_sha1', 'patch-img_sha1.sql' ),
// 1.12
array( 'add_table', 'updatelog', 'patch-updatelog.sql' ),
array( 'add_table', 'category', 'patch-category.sql' ),
array( 'do_category_population' ),
- array( 'add_field', 'archive', 'ar_parent_id', 'patch-ar_parent_id.sql'),
- array( 'add_field', 'user_newtalk', 'user_last_timestamp', 'patch-user_last_timestamp.sql'),
+ array( 'add_field', 'archive', 'ar_parent_id', 'patch-ar_parent_id.sql' ),
+ array( 'add_field', 'user_newtalk', 'user_last_timestamp', 'patch-user_last_timestamp.sql' ),
array( 'do_populate_parent_id' ),
array( 'check_bin', 'protected_titles', 'pt_title', 'patch-pt_title-encoding.sql', ),
array( 'maybe_do_profiling_memory_update' ),
$wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
$wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
$wgExtNewIndexes = array(); // table, index, dir
-$wgExtModifiedFields = array(); //table, index, dir
+$wgExtModifiedFields = array(); // table, index, dir
# Helper function: check if the given key is present in the updatelog table.
# Obviously, only use this for updates that occur after the updatelog table was
wfOut( "...can't move table $from to $to, $to already exists.\n" );
} else {
wfOut( "Moving table $from to $to..." );
- $wgDatabase->sourceFile( archive($patch) );
+ $wgDatabase->sourceFile( archive( $patch ) );
wfOut( "ok\n" );
}
} else {
}
}
-function add_table( $name, $patch, $fullpath=false ) {
+function add_table( $name, $patch, $fullpath = false ) {
global $wgDatabase;
if ( $wgDatabase->tableExists( $name ) ) {
wfOut( "...$name table already exists.\n" );
} else {
wfOut( "Creating $name table..." );
- if( $fullpath ) {
+ if ( $fullpath ) {
$wgDatabase->sourceFile( $patch );
} else {
- $wgDatabase->sourceFile( archive($patch) );
+ $wgDatabase->sourceFile( archive( $patch ) );
}
wfOut( "ok\n" );
}
}
-function modify_field($table, $field, $patch, $fullpath=false){
+function modify_field( $table, $field, $patch, $fullpath = false ) {
global $wgDatabase;
if ( !$wgDatabase->tableExists( $table ) ) {
wfOut( "...$table table does not exist, skipping modify field patch\n" );
- } elseif (! $wgDatabase->fieldExists( $table, $field ) ) {
+ } elseif ( ! $wgDatabase->fieldExists( $table, $field ) ) {
wfOut( "...$field field does not exist in $table table, skipping modify field patch\n" );
} else {
wfOut( "Modifying $field field of table $table..." );
- if( $fullpath ) {
+ if ( $fullpath ) {
$wgDatabase->sourceFile( $patch );
} else {
- $wgDatabase->sourceFile( archive($patch) );
+ $wgDatabase->sourceFile( archive( $patch ) );
}
wfOut( "ok\n" );
}
-function add_field( $table, $field, $patch, $fullpath=false ) {
+function add_field( $table, $field, $patch, $fullpath = false ) {
global $wgDatabase;
if ( !$wgDatabase->tableExists( $table ) ) {
wfOut( "...$table table does not exist, skipping new field patch\n" );
wfOut( "...have $field field in $table table.\n" );
} else {
wfOut( "Adding $field field to table $table..." );
- if( $fullpath ) {
+ if ( $fullpath ) {
$wgDatabase->sourceFile( $patch );
} else {
- $wgDatabase->sourceFile( archive($patch) );
+ $wgDatabase->sourceFile( archive( $patch ) );
}
wfOut( "ok\n" );
}
}
-function add_index( $table, $index, $patch, $fullpath=false ) {
+function add_index( $table, $index, $patch, $fullpath = false ) {
global $wgDatabase;
- if( $wgDatabase->indexExists( $table, $index ) ) {
+ if ( $wgDatabase->indexExists( $table, $index ) ) {
wfOut( "...$index key already set on $table table.\n" );
} else {
wfOut( "Adding $index key to table $table... " );
- if( $fullpath ) {
+ if ( $fullpath ) {
$wgDatabase->sourceFile( $patch );
} else {
- $wgDatabase->sourceFile( archive($patch) );
+ $wgDatabase->sourceFile( archive( $patch ) );
}
wfOut( "ok\n" );
}
function do_interwiki_update() {
# Check that interwiki table exists; if it doesn't source it
global $wgDatabase, $IP;
- if( $wgDatabase->tableExists( "interwiki" ) ) {
+ if ( $wgDatabase->tableExists( "interwiki" ) ) {
wfOut( "...already have interwiki table\n" );
return true;
}
wfOut( "Creating interwiki table: " );
- $wgDatabase->sourceFile( archive("patch-interwiki.sql") );
+ $wgDatabase->sourceFile( archive( "patch-interwiki.sql" ) );
wfOut( "ok\n" );
wfOut( "Adding default interwiki definitions: " );
$wgDatabase->sourceFile( "$IP/maintenance/interwiki.sql" );
# Check that proper indexes are in place
global $wgDatabase;
$meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
- if( !$meta->isMultipleKey() ) {
+ if ( !$meta->isMultipleKey() ) {
wfOut( "Updating indexes to 20031107: " );
- $wgDatabase->sourceFile( archive("patch-indexes.sql") );
+ $wgDatabase->sourceFile( archive( "patch-indexes.sql" ) );
wfOut( "ok\n" );
return true;
}
global $wgDatabase;
$meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
- if( !$meta->isMultipleKey() ) {
+ if ( !$meta->isMultipleKey() ) {
wfOut( "Updating indexes to 20050912: " );
- $wgDatabase->sourceFile( archive("patch-mimesearch-indexes.sql") );
+ $wgDatabase->sourceFile( archive( "patch-mimesearch-indexes.sql" ) );
wfOut( "ok\n" );
return true;
}
function do_image_name_unique_update() {
global $wgDatabase;
- if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
+ if ( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
wfOut( "...image primary key already set.\n" );
} else {
wfOut( "Making img_name the primary key... " );
- $wgDatabase->sourceFile( archive("patch-image_name_primary.sql") );
+ $wgDatabase->sourceFile( archive( "patch-image_name_primary.sql" ) );
wfOut( "ok\n" );
}
}
function do_logging_timestamp_index() {
global $wgDatabase;
- if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
+ if ( $wgDatabase->indexExists( 'logging', 'times' ) ) {
wfOut( "...timestamp key on logging already exists.\n" );
} else {
wfOut( "Adding timestamp key on logging table... " );
- $wgDatabase->sourceFile( archive("patch-logging-times-index.sql") );
+ $wgDatabase->sourceFile( archive( "patch-logging-times-index.sql" ) );
wfOut( "ok\n" );
}
}
function do_archive_user_index() {
global $wgDatabase;
- if( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
+ if ( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
wfOut( "...usertext,timestamp key on archive already exists.\n" );
} else {
wfOut( "Adding usertext,timestamp key on archive table... " );
- $wgDatabase->sourceFile( archive("patch-archive-user-index.sql") );
+ $wgDatabase->sourceFile( archive( "patch-archive-user-index.sql" ) );
wfOut( "ok\n" );
}
}
function do_image_user_index() {
global $wgDatabase;
- if( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
+ if ( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
wfOut( "...usertext,timestamp key on image already exists.\n" );
} else {
wfOut( "Adding usertext,timestamp key on image table... " );
- $wgDatabase->sourceFile( archive("patch-image-user-index.sql") );
+ $wgDatabase->sourceFile( archive( "patch-image-user-index.sql" ) );
wfOut( "ok\n" );
}
}
function do_oldimage_user_index() {
global $wgDatabase;
- if( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
+ if ( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
wfOut( "...usertext,timestamp key on oldimage already exists.\n" );
} else {
wfOut( "Adding usertext,timestamp key on oldimage table... " );
- $wgDatabase->sourceFile( archive("patch-oldimage-user-index.sql") );
+ $wgDatabase->sourceFile( archive( "patch-oldimage-user-index.sql" ) );
wfOut( "ok\n" );
}
}
function do_watchlist_update() {
global $wgDatabase;
$fname = 'do_watchlist_update';
- if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
+ if ( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
wfOut( "The watchlist table is already set up for email notification.\n" );
} else {
wfOut( "Adding wl_notificationtimestamp field for email notification management." );
$res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
$wgDatabase->tableName( 'user_newtalk' ) );
- $num_newtalks=$wgDatabase->numRows($res);
+ $num_newtalks = $wgDatabase->numRows( $res );
wfOut( "Now converting $num_newtalks user_newtalk entries to watchlist table entries ... \n" );
$user = new User();
for ( $i = 1; $i <= $num_newtalks; $i++ ) {
$wluser = $wgDatabase->fetchObject( $res );
- if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
- if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
+ if ( $wluser->user_id == 0 ) { # anonymous users ... have IP numbers as "names"
+ if ( $user->isIP( $wluser->user_ip ) ) { # do only if it really looks like an IP number (double checked)
$wgDatabase->replace( 'watchlist',
- array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
- array('wl_user' => 0,
+ array( array( 'wl_user', 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ) ),
+ array( 'wl_user' => 0,
'wl_namespace' => NS_USER_TALK,
'wl_title' => $wluser->user_ip,
'wl_notificationtimestamp' => '19700101000000'
);
}
} else { # normal users ... have user_ids
- $user->setID($wluser->user_id);
+ $user->setID( $wluser->user_id );
$wgDatabase->replace( 'watchlist',
- array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
- array('wl_user' => $user->getID(),
+ array( array( 'wl_user', 'wl_namespace', 'wl_title', 'wl_notificationtimestamp' ) ),
+ array( 'wl_user' => $user->getID(),
'wl_namespace' => NS_USER_TALK,
'wl_title' => $user->getName(),
'wl_notificationtimestamp' => '19700101000000'
function do_user_update() {
global $wgDatabase;
- if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
+ if ( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
wfOut( "User table contains old email authentication field. Dropping... " );
$wgDatabase->sourceFile( archive( 'patch-email-authentication.sql' ) );
wfOut( "ok\n" );
*/
function check_bin( $table, $field, $patchFile ) {
global $wgDatabase, $wgDBtype;
- if ($wgDBtype != 'mysql')
+ if ( $wgDBtype != 'mysql' )
return;
$tableName = $wgDatabase->tableName( $table );
$res = $wgDatabase->query( "SELECT $field FROM $tableName LIMIT 0" );
$flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
$wgDatabase->freeResult( $res );
- if( in_array( 'binary', $flags ) ) {
+ if ( in_array( 'binary', $flags ) ) {
wfOut( "$table table has correct $field encoding.\n" );
} else {
wfOut( "Fixing $field encoding on $table table... " );
function do_schema_restructuring() {
global $wgDatabase;
- $fname="do_schema_restructuring";
+ $fname = "do_schema_restructuring";
if ( $wgDatabase->tableExists( 'page' ) ) {
wfOut( "...page table already exists.\n" );
} else {
wfOut( wfTimestamp( TS_DB ) );
wfOut( "......checking for duplicate entries.\n" );
- list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
+ list ( $cur, $old, $page, $revision, $text ) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
$rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
$sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
$rows = $wgDatabase->query( $sql, $fname );
wfOut( wfTimestamp( TS_DB ) );
- wfOut( "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n" );
+ wfOut( "......<b>Deleted</b> " . $wgDatabase->affectedRows() . " records.\n" );
}
wfOut( wfTimestamp( TS_DB ) );
wfOut( "......Creating tables.\n" );
- $wgDatabase->query("CREATE TABLE $page (
+ $wgDatabase->query( "CREATE TABLE $page (
page_id int(8) unsigned NOT NULL auto_increment,
page_namespace int NOT NULL,
page_title varchar(255) binary NOT NULL,
INDEX (page_random),
INDEX (page_len)
) ENGINE=InnoDB", $fname );
- $wgDatabase->query("CREATE TABLE $revision (
+ $wgDatabase->query( "CREATE TABLE $revision (
rev_id int(8) unsigned NOT NULL auto_increment,
rev_page int(8) unsigned NOT NULL,
rev_comment tinyblob NOT NULL,
wfOut( wfTimestamp( TS_DB ) );
global $wgLegacySchemaConversion;
- if( $wgLegacySchemaConversion ) {
+ if ( $wgLegacySchemaConversion ) {
// Create HistoryBlobCurStub entries.
// Text will be pulled from the leftover 'cur' table at runtime.
wfOut( "......Moving metadata from cur; using blob references to text in cur table.\n" );
function do_inverse_timestamp() {
global $wgDatabase;
- if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
+ if ( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
wfOut( "Removing revision.inverse_timestamp and fixing indexes... " );
$wgDatabase->sourceFile( archive( 'patch-inverse_timestamp.sql' ) );
wfOut( "ok\n" );
function do_text_id() {
global $wgDatabase;
- if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
+ if ( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
wfOut( "...rev_text_id already in place.\n" );
} else {
wfOut( "Adding rev_text_id field... " );
'querycache' => 'qc',
'logging' => 'log',
);
- foreach( $tables as $table => $prefix ) {
+ foreach ( $tables as $table => $prefix ) {
do_namespace_size_on( $table, $prefix );
flush();
}
function do_namespace_size_on( $table, $prefix ) {
global $wgDatabase, $wgDBtype;
- if ($wgDBtype != 'mysql')
+ if ( $wgDBtype != 'mysql' )
return;
$field = $prefix . '_namespace';
$info = $wgDatabase->fetchObject( $result );
$wgDatabase->freeResult( $result );
- if( substr( $info->Type, 0, 3 ) == 'int' ) {
+ if ( substr( $info->Type, 0, 3 ) == 'int' ) {
wfOut( "...$field is already a full int ($info->Type).\n" );
} else {
wfOut( "Promoting $field from $info->Type to int... " );
function do_pagelinks_update() {
global $wgDatabase;
- if( $wgDatabase->tableExists( 'pagelinks' ) ) {
+ if ( $wgDatabase->tableExists( 'pagelinks' ) ) {
wfOut( "...already have pagelinks table.\n" );
} else {
wfOut( "Converting links and brokenlinks tables to pagelinks... " );
flush();
global $wgCanonicalNamespaceNames;
- foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
- if( $ns != 0 ) {
+ foreach ( $wgCanonicalNamespaceNames as $ns => $name ) {
+ if ( $ns != 0 ) {
do_pagelinks_namespace( $ns );
}
}
$pagelinks = $wgDatabase->tableName( 'pagelinks' );
$name = $wgContLang->getNsText( $ns );
$prefix = $wgDatabase->strencode( $name );
- $likeprefix = str_replace( '_', '\\_', $prefix);
+ $likeprefix = str_replace( '_', '\\_', $prefix );
$sql = "UPDATE $pagelinks
SET pl_namespace=$ns,
function do_drop_img_type() {
global $wgDatabase;
- if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
+ if ( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
wfOut( "Dropping unused img_type field in image table... " );
$wgDatabase->sourceFile( archive( 'patch-drop_img_type.sql' ) );
wfOut( "ok\n" );
function do_old_links_update() {
global $wgDatabase;
- if( $wgDatabase->tableExists( 'pagelinks' ) ) {
+ if ( $wgDatabase->tableExists( 'pagelinks' ) ) {
wfOut( "Already have pagelinks; skipping old links table updates.\n" );
} else {
convertLinks(); flush();
function do_user_unique_update() {
global $wgDatabase;
$duper = new UserDupes( $wgDatabase );
- if( $duper->hasUniqueIndex() ) {
+ if ( $duper->hasUniqueIndex() ) {
wfOut( "Already have unique user_name index.\n" );
} else {
- if( !$duper->clearDupes() ) {
+ if ( !$duper->clearDupes() ) {
wfOut( "WARNING: This next step will probably fail due to unfixed duplicates...\n" );
}
wfOut( "Adding unique index on user_name... " );
$fname = 'do_user_groups_update';
global $wgDatabase;
- if( $wgDatabase->tableExists( 'user_groups' ) ) {
+ if ( $wgDatabase->tableExists( 'user_groups' ) ) {
wfOut( "...user_groups table already exists.\n" );
return do_user_groups_reformat();
}
$wgDatabase->sourceFile( archive( 'patch-user_groups.sql' ) );
wfOut( "ok\n" );
- if( !$wgDatabase->tableExists( 'user_rights' ) ) {
- if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
+ if ( !$wgDatabase->tableExists( 'user_rights' ) ) {
+ if ( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
wfOut( "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion..." );
$wgDatabase->sourceFile( archive( 'patch-user_rights.sql' ) );
wfOut( "ok\n" );
array( "ur_rights != ''" ),
$fname );
- while( $row = $wgDatabase->fetchObject( $result ) ) {
+ while ( $row = $wgDatabase->fetchObject( $result ) ) {
$groups = array_unique(
array_map( 'trim',
explode( ',', $row->ur_rights ) ) );
- foreach( $groups as $group ) {
+ foreach ( $groups as $group ) {
$wgDatabase->insert( 'user_groups',
array(
'ug_user' => $row->ur_user,
global $wgDatabase;
$info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
- if( $info->type() == 'int' ) {
+ if ( $info->type() == 'int' ) {
$oldug = $wgDatabase->tableName( 'user_groups' );
$newug = $wgDatabase->tableName( 'user_groups_bogus' );
wfOut( "user_groups is in bogus intermediate format. Renaming to $newug... " );
global $wgDatabase;
$info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
- if( !$info->nullable() ) {
+ if ( !$info->nullable() ) {
wfOut( "Making wl_notificationtimestamp nullable... " );
$wgDatabase->sourceFile( archive( 'patch-watchlist-null.sql' ) );
wfOut( "ok\n" );
return;
}
wfOut( "Creating templatelinks table...\n" );
- $wgDatabase->sourceFile( archive('patch-templatelinks.sql') );
+ $wgDatabase->sourceFile( archive( 'patch-templatelinks.sql' ) );
wfOut( "Populating...\n" );
if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
// Slow, replication-friendly update
array( 'pl_namespace' => NS_TEMPLATE ), $fname );
$count = 0;
while ( $row = $wgDatabase->fetchObject( $res ) ) {
- $count = ($count + 1) % 100;
+ $count = ( $count + 1 ) % 100;
if ( $count == 0 ) {
if ( function_exists( 'wfWaitForSlaves' ) ) {
wfWaitForSlaves( 10 );
'rc_user_text' => 'patch-rc_user_text-index.sql',
);
- foreach( $indexes as $index => $patch ) {
+ foreach ( $indexes as $index => $patch ) {
$info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
- if( !$info ) {
+ if ( !$info ) {
wfOut( "...index `{$index}` not found; adding..." );
$wgDatabase->sourceFile( archive( $patch ) );
wfOut( "done.\n" );
}
}
-function index_has_field($table, $index, $field) {
+function index_has_field( $table, $index, $field ) {
global $wgDatabase;
wfOut( "Checking if $table index $index includes field $field...\n" );
$info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
- if( $info ) {
- foreach($info as $row) {
- if($row->Column_name == $field) {
+ if ( $info ) {
+ foreach ( $info as $row ) {
+ if ( $row->Column_name == $field ) {
wfOut( "...index $index on table $table seems to be ok\n" );
return true;
}
function do_backlinking_indices_update() {
global $wgDatabase;
wfOut( "Checking for backlinking indices...\n" );
- if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
- !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
- !index_has_field('imagelinks', 'il_to', 'il_from'))
+ if ( !index_has_field( 'pagelinks', 'pl_namespace', 'pl_from' ) ||
+ !index_has_field( 'templatelinks', 'tl_namespace', 'tl_from' ) ||
+ !index_has_field( 'imagelinks', 'il_to', 'il_from' ) )
{
$wgDatabase->sourceFile( archive( 'patch-backlinkindexes.sql' ) );
wfOut( "...backlinking indices updated\n" );
function do_categorylinks_indices_update() {
global $wgDatabase;
wfOut( "Checking for categorylinks indices...\n" );
- if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
+ if ( !index_has_field( 'categorylinks', 'cl_sortkey', 'cl_from' ) )
{
$wgDatabase->sourceFile( archive( 'patch-categorylinksindex.sql' ) );
wfOut( "...categorylinks indices updated\n" );
global $wgDatabase;
wfOut( "Checking site_stats row..." );
$row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
- if( $row === false ) {
+ if ( $row === false ) {
wfOut( "data is missing! rebuilding...\n" );
} elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
wfOut( "missing ss_total_pages, rebuilding...\n" );
function do_active_users_init() {
global $wgDatabase;
$activeUsers = $wgDatabase->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
- if( $activeUsers == -1 ) {
+ if ( $activeUsers == -1 ) {
$activeUsers = $wgDatabase->selectField( 'recentchanges',
'COUNT( DISTINCT rc_user_text )',
array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
);
$wgDatabase->update( 'site_stats',
- array( 'ss_active_users' => intval($activeUsers) ),
+ array( 'ss_active_users' => intval( $activeUsers ) ),
array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
);
}
function do_all_updates( $shared = false, $purge = true ) {
global $wgNewTables, $wgExtModifiedFields, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgSharedTables, $wgDatabase, $wgDBtype, $IP;
- wfRunHooks('LoadExtensionSchemaUpdates');
+ wfRunHooks( 'LoadExtensionSchemaUpdates' );
- $doUser = $shared ? $wgSharedDB && in_array('user', $wgSharedTables) : !$wgSharedDB || !in_array('user', $wgSharedTables);
+ $doUser = $shared ? $wgSharedDB && in_array( 'user', $wgSharedTables ) : !$wgSharedDB || !in_array( 'user', $wgSharedTables );
- if ($wgDBtype === 'postgres') {
+ if ( $wgDBtype === 'postgres' ) {
do_postgres_updates();
return;
}
# Run core updates in sequence...
global $wgUpdates;
if ( isset( $wgUpdates[$wgDBtype] ) ) {
- foreach( $wgUpdates[$wgDBtype] as $params ) {
+ foreach ( $wgUpdates[$wgDBtype] as $params ) {
$func = array_shift( $params );
call_user_func_array( $func, $params );
flush();
}
}
- /// @fixme clean up this mess too!
+ // / @fixme clean up this mess too!
global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
# Add missing extension tables
foreach ( $wgExtNewTables as $tableRecord ) {
}
# Add modified extension fields
foreach ( $wgExtModifiedFields as $fieldRecord ) {
- modify_field($fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true);
+ modify_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
flush();
}
wfOut( "Deleting old default messages (this may take a long time!)..." );
- if( !defined( 'MW_NO_SETUP' ) ) {
+ if ( !defined( 'MW_NO_SETUP' ) ) {
define( 'MW_NO_SETUP', true );
}
require_once 'deleteDefaultMessages.php';
do_stats_init();
- if( $purge ) {
+ if ( $purge ) {
purge_cache();
}
}
-function archive($name) {
+function archive( $name ) {
global $wgDBtype, $IP;
if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$name" ) ) {
return "$IP/maintenance/$wgDBtype/archives/$name";
wfOut( "...$name table already exists.\n" );
} else {
wfOut( "Creating $name table..." );
- $wgDatabase->sourceFile( archive($patch) );
- $wgDatabase->sourceFile( archive($patch2) );
+ $wgDatabase->sourceFile( archive( $patch ) );
+ $wgDatabase->sourceFile( archive( $patch2 ) );
wfOut( "ok\n" );
wfOut( "Migrating old restrictions to new table..." );
- $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
+ $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array( "page_restrictions!=''", "page_restrictions!='edit=:move='" ), __METHOD__ );
$count = 0;
- while ($row = $wgDatabase->fetchObject($res) ) {
- $count = ($count + 1) % 100;
+ while ( $row = $wgDatabase->fetchObject( $res ) ) {
+ $count = ( $count + 1 ) % 100;
- if ($count == 0) {
+ if ( $count == 0 ) {
if ( function_exists( 'wfWaitForSlaves' ) ) {
wfWaitForSlaves( 10 );
} else {
$flatrestrictions = explode( ':', $row->page_restrictions );
$restrictions = array ();
- foreach( $flatrestrictions as $restriction ) {
+ foreach ( $flatrestrictions as $restriction ) {
$thisrestriction = explode( '=', $restriction, 2 );
- if( count( $thisrestriction ) == 1 ) {
+ if ( count( $thisrestriction ) == 1 ) {
// Compatibility with old protections from before
// separate move protection was added.
list( $level ) = $thisrestriction;
- if( $level ) {
+ if ( $level ) {
$restrictions['edit'] = $level;
$restrictions['move'] = $level;
}
} else {
list( $type, $level ) = $thisrestriction;
- if( $level ) {
+ if ( $level ) {
$restrictions[$type] = $level;
}
}
- $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
+ $wgDatabase->update( 'page', array ( 'page_restrictions' => '' ), array( 'page_id' => $id ), __METHOD__ );
}
- foreach( $restrictions as $type => $level ) {
+ foreach ( $restrictions as $type => $level ) {
$wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
'pr_type' => $type,
'pr_level' => $level,
}
function do_category_population() {
- if( update_row_exists( 'populate category' ) ) {
+ if ( update_row_exists( 'populate category' ) ) {
wfOut( "...category table already populated.\n" );
return;
}
require_once( 'populateCategory.php' );
- wfOut( "Populating category table, printing progress markers. " ).
-"For large databases, you\n".
-"may want to hit Ctrl-C and do this manually with maintenance/\n".
+ wfOut( "Populating category table, printing progress markers. " ) .
+"For large databases, you\n" .
+"may want to hit Ctrl-C and do this manually with maintenance/\n" .
"populateCategory.php.\n";
$task = new PopulateCategory();
$task->execute();
}
function do_populate_parent_id() {
- if( update_row_exists( 'populate rev_parent_id' ) ) {
+ if ( update_row_exists( 'populate rev_parent_id' ) ) {
wfOut( "...rev_parent_id column already populated.\n" );
return;
}
}
function do_populate_rev_len() {
- if( update_row_exists( 'populate rev_len' ) ) {
+ if ( update_row_exists( 'populate rev_len' ) ) {
wfOut( "...rev_len column already populated.\n" );
return;
}
function do_unique_pl_tl_il() {
global $wgDatabase;
$info = $wgDatabase->indexInfo( 'pagelinks', 'pl_namespace' );
- if( is_array($info) && !$info[0]->Non_unique ) {
+ if ( is_array( $info ) && !$info[0]->Non_unique ) {
wfOut( "...pl_namespace, tl_namespace, il_to indices are already UNIQUE.\n" );
} else {
wfOut( "Making pl_namespace, tl_namespace and il_to indices UNIQUE... " );
function do_log_search_population() {
global $wgDatabase;
- if( update_row_exists( 'populate log_search' ) ) {
+ if ( update_row_exists( 'populate log_search' ) ) {
wfOut( "...log_search table already populated.\n" );
return;
}
function do_update_transcache_field() {
global $wgDatabase;
- if( update_row_exists( 'convert transcache field' ) ) {
+ if ( update_row_exists( 'convert transcache field' ) ) {
wfOut( "...transcache tc_time already converted.\n" );
return;
} else {
* TODO: merge with above
***********************************************************************/
-function pg_describe_table($table) {
+function pg_describe_table( $table ) {
global $wgDatabase, $wgDBmwschema;
$q = <<<END
SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
AND attrelid=pg_class.oid AND attnum > 0
AND relname=%s AND nspname=%s
END;
- $res = $wgDatabase->query(sprintf($q,
- $wgDatabase->addQuotes($table),
- $wgDatabase->addQuotes($wgDBmwschema)));
- if (!$res)
+ $res = $wgDatabase->query( sprintf( $q,
+ $wgDatabase->addQuotes( $table ),
+ $wgDatabase->addQuotes( $wgDBmwschema ) ) );
+ if ( !$res )
return null;
$cols = array();
- while ($r = $wgDatabase->fetchRow($res)) {
+ while ( $r = $wgDatabase->fetchRow( $res ) ) {
$cols[] = array(
"name" => $r[0],
"ord" => $r[1],
return $cols;
}
-function pg_describe_index($idx) {
+function pg_describe_index( $idx ) {
global $wgDatabase, $wgDBmwschema;
// first fetch the key (which is a list of columns ords) and
AND relname=%s
AND indexrelid=pg_class.oid
END;
- $res = $wgDatabase->query(sprintf($q,
- $wgDatabase->addQuotes($wgDBmwschema),
- $wgDatabase->addQuotes($idx)));
- if (!$res)
+ $res = $wgDatabase->query( sprintf( $q,
+ $wgDatabase->addQuotes( $wgDBmwschema ),
+ $wgDatabase->addQuotes( $idx ) ) );
+ if ( !$res )
return null;
- if (!($r = $wgDatabase->fetchRow($res))) {
- $wgDatabase->freeResult($res);
+ if ( !( $r = $wgDatabase->fetchRow( $res ) ) ) {
+ $wgDatabase->freeResult( $res );
return null;
}
$indkey = $r[0];
- $relid = intval($r[1]);
- $indkeys = explode(" ", $indkey);
- $wgDatabase->freeResult($res);
+ $relid = intval( $r[1] );
+ $indkeys = explode( " ", $indkey );
+ $wgDatabase->freeResult( $res );
$colnames = array();
- foreach ($indkeys as $rid) {
+ foreach ( $indkeys as $rid ) {
$query = <<<END
SELECT attname FROM pg_class, pg_attribute
WHERE attrelid=$relid
AND attnum=%d
AND attrelid=pg_class.oid
END;
- $r2 = $wgDatabase->query(sprintf($query, $rid));
- if (!$r2)
+ $r2 = $wgDatabase->query( sprintf( $query, $rid ) );
+ if ( !$r2 )
return null;
- if (!($row2 = $wgDatabase->fetchRow($r2))) {
- $wgDatabase->freeResult($r2);
+ if ( !( $row2 = $wgDatabase->fetchRow( $r2 ) ) ) {
+ $wgDatabase->freeResult( $r2 );
return null;
}
$colnames[] = $row2[0];
- $wgDatabase->freeResult($r2);
+ $wgDatabase->freeResult( $r2 );
}
return $colnames;
}
-function pg_index_exists($table, $index) {
+function pg_index_exists( $table, $index ) {
global $wgDatabase, $wgDBmwschema;
- $exists = $wgDatabase->selectField("pg_indexes", "indexname",
+ $exists = $wgDatabase->selectField( "pg_indexes", "indexname",
array( "indexname" => $index,
"tablename" => $table,
- "schemaname" => $wgDBmwschema));
+ "schemaname" => $wgDBmwschema ) );
return $exists === $index;
}
-function pg_fkey_deltype($fkey) {
+function pg_fkey_deltype( $fkey ) {
global $wgDatabase, $wgDBmwschema;
$q = <<<END
SELECT confdeltype FROM pg_constraint, pg_namespace
AND nspname=%s
AND conname=%s;
END;
- $r = $wgDatabase->query(sprintf($q,
- $wgDatabase->addQuotes($wgDBmwschema),
- $wgDatabase->addQuotes($fkey)));
- if (!($row = $wgDatabase->fetchRow($r)))
+ $r = $wgDatabase->query( sprintf( $q,
+ $wgDatabase->addQuotes( $wgDBmwschema ),
+ $wgDatabase->addQuotes( $fkey ) ) );
+ if ( !( $row = $wgDatabase->fetchRow( $r ) ) )
return null;
return $row[0];
}
-function pg_rule_def($table, $rule) {
+function pg_rule_def( $table, $rule ) {
global $wgDatabase, $wgDBmwschema;
$q = <<<END
SELECT definition FROM pg_rules
AND tablename = %s
AND rulename = %s
END;
- $r = $wgDatabase->query(sprintf($q,
- $wgDatabase->addQuotes($wgDBmwschema),
- $wgDatabase->addQuotes($table),
- $wgDatabase->addQuotes($rule)));
- $row = $wgDatabase->fetchRow($r);
- if (!$row)
+ $r = $wgDatabase->query( sprintf( $q,
+ $wgDatabase->addQuotes( $wgDBmwschema ),
+ $wgDatabase->addQuotes( $table ),
+ $wgDatabase->addQuotes( $rule ) ) );
+ $row = $wgDatabase->fetchRow( $r );
+ if ( !$row )
return null;
$d = $row[0];
- $wgDatabase->freeResult($r);
+ $wgDatabase->freeResult( $r );
return $d;
}
function do_postgres_updates() {
global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
- ## Gather version numbers in case we need them
- $version = $wgDatabase->getServerVersion(); ## long string
- $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
+ # # Gather version numbers in case we need them
+ $version = $wgDatabase->getServerVersion(); # # long string
+ $numver = $wgDatabase->numeric_version; # # X.Y e.g. 8.3
$wgShowExceptionDetails = 1;
# Just in case their LocalSettings.php does not have this:
- if ( !isset( $wgDBmwschema ))
+ if ( !isset( $wgDBmwschema ) )
$wgDBmwschema = 'mediawiki';
# Verify that this user is configured correctly
- $safeuser = $wgDatabase->addQuotes($wgDBuser);
+ $safeuser = $wgDatabase->addQuotes( $wgDBuser );
$SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
$config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
$conf = array();
- foreach( explode( '*', $config ) as $c ) {
- list( $x,$y ) = explode( '=', $c );
+ foreach ( explode( '*', $config ) as $c ) {
+ list( $x, $y ) = explode( '=', $c );
$conf[$x] = $y;
}
- if( !array_key_exists( 'search_path', $conf ) ) {
+ if ( !array_key_exists( 'search_path', $conf ) ) {
$search_path = '';
}
else {
$search_path = $conf['search_path'];
}
- if( strpos( $search_path, $wgDBmwschema ) === false ) {
+ if ( strpos( $search_path, $wgDBmwschema ) === false ) {
wfOut( "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n" );
$search_path = "$wgDBmwschema, $search_path";
}
- if( strpos( $search_path, $wgDBts2schema ) === false ) {
+ if ( strpos( $search_path, $wgDBts2schema ) === false ) {
wfOut( "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n" );
$search_path = "$search_path, $wgDBts2schema";
}
- $search_path = str_replace( ', ,', ',', $search_path);
- if( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
+ $search_path = str_replace( ', ,', ',', $search_path );
+ if ( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
$wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
$wgDatabase->doQuery( "SET search_path = $search_path" );
}
'DateStyle' => 'ISO, YMD',
'TimeZone' => 'GMT'
);
- foreach( array_keys( $goodconf ) AS $key ) {
+ foreach ( array_keys( $goodconf ) AS $key ) {
$value = $goodconf[$key];
- if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
+ if ( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
wfOut( "Setting $key to '$value' for user \"$wgDBuser\"\n" );
$wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
$wgDatabase->doQuery( "SET $key = '$value'" );
);
$newtables = array(
- array("category", "patch-category.sql"),
- array("mwuser", "patch-mwuser.sql"),
- array("pagecontent", "patch-pagecontent.sql"),
- array("querycachetwo", "patch-querycachetwo.sql"),
- array("page_props", "patch-page_props.sql"),
- array("page_restrictions", "patch-page_restrictions.sql"),
- array("profiling", "patch-profiling.sql"),
- array("protected_titles", "patch-protected_titles.sql"),
- array("redirect", "patch-redirect.sql"),
- array("updatelog", "patch-updatelog.sql"),
- array('change_tag', 'patch-change_tag.sql'),
- array('tag_summary', 'patch-change_tag.sql'),
- array('valid_tag', 'patch-change_tag.sql'),
- array('user_properties', 'patch-user_properties.sql'),
- array('log_search', 'patch-log_search.sql'),
- array('l10n_cache', 'patch-l10n_cache.sql'),
- array('iwlinks', 'patch-iwlinks.sql'),
+ array( "category", "patch-category.sql" ),
+ array( "mwuser", "patch-mwuser.sql" ),
+ array( "pagecontent", "patch-pagecontent.sql" ),
+ array( "querycachetwo", "patch-querycachetwo.sql" ),
+ array( "page_props", "patch-page_props.sql" ),
+ array( "page_restrictions", "patch-page_restrictions.sql" ),
+ array( "profiling", "patch-profiling.sql" ),
+ array( "protected_titles", "patch-protected_titles.sql" ),
+ array( "redirect", "patch-redirect.sql" ),
+ array( "updatelog", "patch-updatelog.sql" ),
+ array( 'change_tag', 'patch-change_tag.sql' ),
+ array( 'tag_summary', 'patch-change_tag.sql' ),
+ array( 'valid_tag', 'patch-change_tag.sql' ),
+ array( 'user_properties', 'patch-user_properties.sql' ),
+ array( 'log_search', 'patch-log_search.sql' ),
+ array( 'l10n_cache', 'patch-l10n_cache.sql' ),
+ array( 'iwlinks', 'patch-iwlinks.sql' ),
);
$newcols = array(
- array("archive", "ar_deleted", "SMALLINT NOT NULL DEFAULT 0"),
- array("archive", "ar_len", "INTEGER"),
- array("archive", "ar_page_id", "INTEGER"),
- array("archive", "ar_parent_id", "INTEGER"),
- array("image", "img_sha1", "TEXT NOT NULL DEFAULT ''"),
- array("ipblocks", "ipb_allow_usertalk", "SMALLINT NOT NULL DEFAULT 0"),
- array("ipblocks", "ipb_anon_only", "SMALLINT NOT NULL DEFAULT 0"),
- array("ipblocks", "ipb_by_text", "TEXT NOT NULL DEFAULT ''"),
- array("ipblocks", "ipb_block_email", "SMALLINT NOT NULL DEFAULT 0"),
- array("ipblocks", "ipb_create_account", "SMALLINT NOT NULL DEFAULT 1"),
- array("ipblocks", "ipb_deleted", "SMALLINT NOT NULL DEFAULT 0"),
- array("ipblocks", "ipb_enable_autoblock", "SMALLINT NOT NULL DEFAULT 1"),
- array("filearchive", "fa_deleted", "SMALLINT NOT NULL DEFAULT 0"),
- array("logging", "log_deleted", "SMALLINT NOT NULL DEFAULT 0"),
- array("logging", "log_id", "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('logging_log_id_seq')"),
- array("logging", "log_params", "TEXT"),
- array("mwuser", "user_editcount", "INTEGER"),
- array("mwuser", "user_hidden", "SMALLINT NOT NULL DEFAULT 0"),
- array("mwuser", "user_newpass_time", "TIMESTAMPTZ"),
- array("oldimage", "oi_deleted", "SMALLINT NOT NULL DEFAULT 0"),
- array("oldimage", "oi_major_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
- array("oldimage", "oi_media_type", "TEXT"),
- array("oldimage", "oi_metadata", "BYTEA NOT NULL DEFAULT ''"),
- array("oldimage", "oi_minor_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
- array("oldimage", "oi_sha1", "TEXT NOT NULL DEFAULT ''"),
- array("page_restrictions", "pr_id", "INTEGER NOT NULL UNIQUE DEFAULT nextval('page_restrictions_pr_id_val')"),
- array("profiling", "pf_memory", "NUMERIC(18,10) NOT NULL DEFAULT 0"),
- array("recentchanges", "rc_deleted", "SMALLINT NOT NULL DEFAULT 0"),
- array("recentchanges", "rc_log_action", "TEXT"),
- array("recentchanges", "rc_log_type", "TEXT"),
- array("recentchanges", "rc_logid", "INTEGER NOT NULL DEFAULT 0"),
- array("recentchanges", "rc_new_len", "INTEGER"),
- array("recentchanges", "rc_old_len", "INTEGER"),
- array("recentchanges", "rc_params", "TEXT"),
- array("redirect", "rd_interwiki", "TEXT NULL"),
- array("redirect", "rd_fragment", "TEXT NULL"),
- array("revision", "rev_deleted", "SMALLINT NOT NULL DEFAULT 0"),
- array("revision", "rev_len", "INTEGER"),
- array("revision", "rev_parent_id", "INTEGER DEFAULT NULL"),
- array("site_stats", "ss_active_users", "INTEGER DEFAULT '-1'"),
- array("user_newtalk", "user_last_timestamp", "TIMESTAMPTZ"),
- array("logging", "log_user_text", "TEXT NOT NULL DEFAULT ''"),
- array("logging", "log_page", "INTEGER"),
+ array( "archive", "ar_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "archive", "ar_len", "INTEGER" ),
+ array( "archive", "ar_page_id", "INTEGER" ),
+ array( "archive", "ar_parent_id", "INTEGER" ),
+ array( "image", "img_sha1", "TEXT NOT NULL DEFAULT ''" ),
+ array( "ipblocks", "ipb_allow_usertalk", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "ipblocks", "ipb_anon_only", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "ipblocks", "ipb_by_text", "TEXT NOT NULL DEFAULT ''" ),
+ array( "ipblocks", "ipb_block_email", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "ipblocks", "ipb_create_account", "SMALLINT NOT NULL DEFAULT 1" ),
+ array( "ipblocks", "ipb_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "ipblocks", "ipb_enable_autoblock", "SMALLINT NOT NULL DEFAULT 1" ),
+ array( "filearchive", "fa_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "logging", "log_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "logging", "log_id", "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('logging_log_id_seq')" ),
+ array( "logging", "log_params", "TEXT" ),
+ array( "mwuser", "user_editcount", "INTEGER" ),
+ array( "mwuser", "user_hidden", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "mwuser", "user_newpass_time", "TIMESTAMPTZ" ),
+ array( "oldimage", "oi_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "oldimage", "oi_major_mime", "TEXT NOT NULL DEFAULT 'unknown'" ),
+ array( "oldimage", "oi_media_type", "TEXT" ),
+ array( "oldimage", "oi_metadata", "BYTEA NOT NULL DEFAULT ''" ),
+ array( "oldimage", "oi_minor_mime", "TEXT NOT NULL DEFAULT 'unknown'" ),
+ array( "oldimage", "oi_sha1", "TEXT NOT NULL DEFAULT ''" ),
+ array( "page_restrictions", "pr_id", "INTEGER NOT NULL UNIQUE DEFAULT nextval('page_restrictions_pr_id_val')" ),
+ array( "profiling", "pf_memory", "NUMERIC(18,10) NOT NULL DEFAULT 0" ),
+ array( "recentchanges", "rc_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "recentchanges", "rc_log_action", "TEXT" ),
+ array( "recentchanges", "rc_log_type", "TEXT" ),
+ array( "recentchanges", "rc_logid", "INTEGER NOT NULL DEFAULT 0" ),
+ array( "recentchanges", "rc_new_len", "INTEGER" ),
+ array( "recentchanges", "rc_old_len", "INTEGER" ),
+ array( "recentchanges", "rc_params", "TEXT" ),
+ array( "redirect", "rd_interwiki", "TEXT NULL" ),
+ array( "redirect", "rd_fragment", "TEXT NULL" ),
+ array( "revision", "rev_deleted", "SMALLINT NOT NULL DEFAULT 0" ),
+ array( "revision", "rev_len", "INTEGER" ),
+ array( "revision", "rev_parent_id", "INTEGER DEFAULT NULL" ),
+ array( "site_stats", "ss_active_users", "INTEGER DEFAULT '-1'" ),
+ array( "user_newtalk", "user_last_timestamp", "TIMESTAMPTZ" ),
+ array( "logging", "log_user_text", "TEXT NOT NULL DEFAULT ''" ),
+ array( "logging", "log_page", "INTEGER" ),
);
# table, column, desired type, USING clause if needed (with new default if needed)
$typechanges = array(
- array("archive", "ar_deleted", "smallint", ""),
- array("archive", "ar_minor_edit", "smallint", "ar_minor_edit::smallint DEFAULT 0"),
- array("filearchive", "fa_deleted", "smallint", ""),
- array("filearchive", "fa_height", "integer", ""),
- array("filearchive", "fa_metadata", "bytea", "decode(fa_metadata,'escape')"),
- array("filearchive", "fa_size", "integer", ""),
- array("filearchive", "fa_width", "integer", ""),
- array("filearchive", "fa_storage_group","text", ""),
- array("filearchive", "fa_storage_key", "text", ""),
- array("image", "img_metadata", "bytea", "decode(img_metadata,'escape')"),
- array("image", "img_size", "integer", ""),
- array("image", "img_width", "integer", ""),
- array("image", "img_height", "integer", ""),
- array("interwiki", "iw_local", "smallint", "iw_local::smallint DEFAULT 0"),
- array("interwiki", "iw_trans", "smallint", "iw_trans::smallint DEFAULT 0"),
- array("ipblocks", "ipb_auto", "smallint", "ipb_auto::smallint DEFAULT 0"),
- array("ipblocks", "ipb_anon_only", "smallint", "CASE WHEN ipb_anon_only=' ' THEN 0 ELSE ipb_anon_only::smallint END DEFAULT 0"),
- array("ipblocks", "ipb_create_account", "smallint", "CASE WHEN ipb_create_account=' ' THEN 0 ELSE ipb_create_account::smallint END DEFAULT 1"),
- array("ipblocks", "ipb_enable_autoblock", "smallint", "CASE WHEN ipb_enable_autoblock=' ' THEN 0 ELSE ipb_enable_autoblock::smallint END DEFAULT 1"),
- array("ipblocks", "ipb_block_email", "smallint", "CASE WHEN ipb_block_email=' ' THEN 0 ELSE ipb_block_email::smallint END DEFAULT 0"),
- array("ipblocks", "ipb_address", "text", "ipb_address::text"),
- array("ipblocks", "ipb_deleted", "smallint", "ipb_deleted::smallint DEFAULT 0"),
- array("math", "math_inputhash", "bytea", "decode(math_inputhash,'escape')"),
- array("math", "math_outputhash", "bytea", "decode(math_outputhash,'escape')"),
- array("mwuser", "user_token", "text", ""),
- array("mwuser", "user_email_token","text", ""),
- array("objectcache", "keyname", "text", ""),
- array("oldimage", "oi_height", "integer", ""),
- array("oldimage", "oi_metadata", "bytea", "decode(img_metadata,'escape')"),
- array("oldimage", "oi_size", "integer", ""),
- array("oldimage", "oi_width", "integer", ""),
- array("page", "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
- array("page", "page_is_new", "smallint", "page_is_new::smallint DEFAULT 0"),
- array("querycache", "qc_value", "integer", ""),
- array("querycachetwo","qcc_value", "integer", ""),
- array("recentchanges","rc_bot", "smallint", "rc_bot::smallint DEFAULT 0"),
- array("recentchanges","rc_deleted", "smallint", ""),
- array("recentchanges","rc_minor", "smallint", "rc_minor::smallint DEFAULT 0"),
- array("recentchanges","rc_new", "smallint", "rc_new::smallint DEFAULT 0"),
- array("recentchanges","rc_type", "smallint", "rc_type::smallint DEFAULT 0"),
- array("recentchanges","rc_patrolled", "smallint", "rc_patrolled::smallint DEFAULT 0"),
- array("revision", "rev_deleted", "smallint", "rev_deleted::smallint DEFAULT 0"),
- array("revision", "rev_minor_edit", "smallint", "rev_minor_edit::smallint DEFAULT 0"),
- array("templatelinks","tl_namespace", "smallint", "tl_namespace::smallint"),
- array("user_newtalk", "user_ip", "text", "host(user_ip)"),
+ array( "archive", "ar_deleted", "smallint", "" ),
+ array( "archive", "ar_minor_edit", "smallint", "ar_minor_edit::smallint DEFAULT 0" ),
+ array( "filearchive", "fa_deleted", "smallint", "" ),
+ array( "filearchive", "fa_height", "integer", "" ),
+ array( "filearchive", "fa_metadata", "bytea", "decode(fa_metadata,'escape')" ),
+ array( "filearchive", "fa_size", "integer", "" ),
+ array( "filearchive", "fa_width", "integer", "" ),
+ array( "filearchive", "fa_storage_group", "text", "" ),
+ array( "filearchive", "fa_storage_key", "text", "" ),
+ array( "image", "img_metadata", "bytea", "decode(img_metadata,'escape')" ),
+ array( "image", "img_size", "integer", "" ),
+ array( "image", "img_width", "integer", "" ),
+ array( "image", "img_height", "integer", "" ),
+ array( "interwiki", "iw_local", "smallint", "iw_local::smallint DEFAULT 0" ),
+ array( "interwiki", "iw_trans", "smallint", "iw_trans::smallint DEFAULT 0" ),
+ array( "ipblocks", "ipb_auto", "smallint", "ipb_auto::smallint DEFAULT 0" ),
+ array( "ipblocks", "ipb_anon_only", "smallint", "CASE WHEN ipb_anon_only=' ' THEN 0 ELSE ipb_anon_only::smallint END DEFAULT 0" ),
+ array( "ipblocks", "ipb_create_account", "smallint", "CASE WHEN ipb_create_account=' ' THEN 0 ELSE ipb_create_account::smallint END DEFAULT 1" ),
+ array( "ipblocks", "ipb_enable_autoblock", "smallint", "CASE WHEN ipb_enable_autoblock=' ' THEN 0 ELSE ipb_enable_autoblock::smallint END DEFAULT 1" ),
+ array( "ipblocks", "ipb_block_email", "smallint", "CASE WHEN ipb_block_email=' ' THEN 0 ELSE ipb_block_email::smallint END DEFAULT 0" ),
+ array( "ipblocks", "ipb_address", "text", "ipb_address::text" ),
+ array( "ipblocks", "ipb_deleted", "smallint", "ipb_deleted::smallint DEFAULT 0" ),
+ array( "math", "math_inputhash", "bytea", "decode(math_inputhash,'escape')" ),
+ array( "math", "math_outputhash", "bytea", "decode(math_outputhash,'escape')" ),
+ array( "mwuser", "user_token", "text", "" ),
+ array( "mwuser", "user_email_token", "text", "" ),
+ array( "objectcache", "keyname", "text", "" ),
+ array( "oldimage", "oi_height", "integer", "" ),
+ array( "oldimage", "oi_metadata", "bytea", "decode(img_metadata,'escape')" ),
+ array( "oldimage", "oi_size", "integer", "" ),
+ array( "oldimage", "oi_width", "integer", "" ),
+ array( "page", "page_is_redirect", "smallint", "page_is_redirect::smallint DEFAULT 0" ),
+ array( "page", "page_is_new", "smallint", "page_is_new::smallint DEFAULT 0" ),
+ array( "querycache", "qc_value", "integer", "" ),
+ array( "querycachetwo", "qcc_value", "integer", "" ),
+ array( "recentchanges", "rc_bot", "smallint", "rc_bot::smallint DEFAULT 0" ),
+ array( "recentchanges", "rc_deleted", "smallint", "" ),
+ array( "recentchanges", "rc_minor", "smallint", "rc_minor::smallint DEFAULT 0" ),
+ array( "recentchanges", "rc_new", "smallint", "rc_new::smallint DEFAULT 0" ),
+ array( "recentchanges", "rc_type", "smallint", "rc_type::smallint DEFAULT 0" ),
+ array( "recentchanges", "rc_patrolled", "smallint", "rc_patrolled::smallint DEFAULT 0" ),
+ array( "revision", "rev_deleted", "smallint", "rev_deleted::smallint DEFAULT 0" ),
+ array( "revision", "rev_minor_edit", "smallint", "rev_minor_edit::smallint DEFAULT 0" ),
+ array( "templatelinks", "tl_namespace", "smallint", "tl_namespace::smallint" ),
+ array( "user_newtalk", "user_ip", "text", "host(user_ip)" ),
);
# table, column, nullability
$nullchanges = array(
- array("oldimage", "oi_bits", "NULL"),
- array("oldimage", "oi_timestamp", "NULL"),
- array("oldimage", "oi_major_mime", "NULL"),
- array("oldimage", "oi_minor_mime", "NULL"),
+ array( "oldimage", "oi_bits", "NULL" ),
+ array( "oldimage", "oi_timestamp", "NULL" ),
+ array( "oldimage", "oi_major_mime", "NULL" ),
+ array( "oldimage", "oi_minor_mime", "NULL" ),
);
$newindexes = array(
- array("archive", "archive_user_text", "(ar_user_text)"),
- array("image", "img_sha1", "(img_sha1)"),
- array("oldimage", "oi_sha1", "(oi_sha1)"),
- array("revision", "rev_text_id_idx", "(rev_text_id)"),
- array("recentchanges", "rc_timestamp_bot", "(rc_timestamp) WHERE rc_bot = 0"),
- array("templatelinks", "templatelinks_from", "(tl_from)"),
- array("watchlist", "wl_user", "(wl_user)"),
- array("logging", "logging_user_type_time", "(log_user, log_type, log_timestamp)"),
- array("logging", "logging_page_id_time", "(log_page,log_timestamp)"),
+ array( "archive", "archive_user_text", "(ar_user_text)" ),
+ array( "image", "img_sha1", "(img_sha1)" ),
+ array( "oldimage", "oi_sha1", "(oi_sha1)" ),
+ array( "revision", "rev_text_id_idx", "(rev_text_id)" ),
+ array( "recentchanges", "rc_timestamp_bot", "(rc_timestamp) WHERE rc_bot = 0" ),
+ array( "templatelinks", "templatelinks_from", "(tl_from)" ),
+ array( "watchlist", "wl_user", "(wl_user)" ),
+ array( "logging", "logging_user_type_time", "(log_user, log_type, log_timestamp)" ),
+ array( "logging", "logging_page_id_time", "(log_page,log_timestamp)" ),
);
$newrules = array(
);
- ## All FK columns should be deferred
+ # # All FK columns should be deferred
$deferredcols = array(
- array("archive", "ar_user", "mwuser(user_id) ON DELETE SET NULL"),
- array("categorylinks", "cl_from", "page(page_id) ON DELETE CASCADE"),
- array("externallinks", "el_from", "page(page_id) ON DELETE CASCADE"),
- array("filearchive", "fa_deleted_user", "mwuser(user_id) ON DELETE SET NULL"),
- array("filearchive", "fa_user", "mwuser(user_id) ON DELETE SET NULL"),
- array("image", "img_user", "mwuser(user_id) ON DELETE SET NULL"),
- array("imagelinks", "il_from", "page(page_id) ON DELETE CASCADE"),
- array("ipblocks", "ipb_by", "mwuser(user_id) ON DELETE CASCADE"),
- array("ipblocks", "ipb_user", "mwuser(user_id) ON DELETE SET NULL"),
- array("langlinks", "ll_from", "page(page_id) ON DELETE CASCADE"),
- array("logging", "log_user", "mwuser(user_id) ON DELETE SET NULL"),
- array("oldimage", "oi_name", "image(img_name) ON DELETE CASCADE ON UPDATE CASCADE"),
- array("oldimage", "oi_user", "mwuser(user_id) ON DELETE SET NULL"),
- array("pagelinks", "pl_from", "page(page_id) ON DELETE CASCADE"),
- array("page_props", "pp_page", "page (page_id) ON DELETE CASCADE"),
- array("page_restrictions","pr_page", "page(page_id) ON DELETE CASCADE"),
- array("protected_titles", "pt_user", "mwuser(user_id) ON DELETE SET NULL"),
- array("recentchanges", "rc_cur_id", "page(page_id) ON DELETE SET NULL"),
- array("recentchanges", "rc_user", "mwuser(user_id) ON DELETE SET NULL"),
- array("redirect", "rd_from", "page(page_id) ON DELETE CASCADE"),
- array("revision", "rev_page", "page (page_id) ON DELETE CASCADE"),
- array("revision", "rev_user", "mwuser(user_id) ON DELETE RESTRICT"),
- array("templatelinks", "tl_from", "page(page_id) ON DELETE CASCADE"),
- array("trackbacks", "tb_page", "page(page_id) ON DELETE CASCADE"),
- array("user_groups", "ug_user", "mwuser(user_id) ON DELETE CASCADE"),
- array("user_newtalk", "user_id", "mwuser(user_id) ON DELETE CASCADE"),
- array("user_properties", "up_user", "mwuser(user_id) ON DELETE CASCADE"),
- array("watchlist", "wl_user", "mwuser(user_id) ON DELETE CASCADE"),
+ array( "archive", "ar_user", "mwuser(user_id) ON DELETE SET NULL" ),
+ array( "categorylinks", "cl_from", "page(page_id) ON DELETE CASCADE" ),
+ array( "externallinks", "el_from", "page(page_id) ON DELETE CASCADE" ),
+ array( "filearchive", "fa_deleted_user", "mwuser(user_id) ON DELETE SET NULL" ),
+ array( "filearchive", "fa_user", "mwuser(user_id) ON DELETE SET NULL" ),
+ array( "image", "img_user", "mwuser(user_id) ON DELETE SET NULL" ),
+ array( "imagelinks", "il_from", "page(page_id) ON DELETE CASCADE" ),
+ array( "ipblocks", "ipb_by", "mwuser(user_id) ON DELETE CASCADE" ),
+ array( "ipblocks", "ipb_user", "mwuser(user_id) ON DELETE SET NULL" ),
+ array( "langlinks", "ll_from", "page(page_id) ON DELETE CASCADE" ),
+ array( "logging", "log_user", "mwuser(user_id) ON DELETE SET NULL" ),
+ array( "oldimage", "oi_name", "image(img_name) ON DELETE CASCADE ON UPDATE CASCADE" ),
+ array( "oldimage", "oi_user", "mwuser(user_id) ON DELETE SET NULL" ),
+ array( "pagelinks", "pl_from", "page(page_id) ON DELETE CASCADE" ),
+ array( "page_props", "pp_page", "page (page_id) ON DELETE CASCADE" ),
+ array( "page_restrictions", "pr_page", "page(page_id) ON DELETE CASCADE" ),
+ array( "protected_titles", "pt_user", "mwuser(user_id) ON DELETE SET NULL" ),
+ array( "recentchanges", "rc_cur_id", "page(page_id) ON DELETE SET NULL" ),
+ array( "recentchanges", "rc_user", "mwuser(user_id) ON DELETE SET NULL" ),
+ array( "redirect", "rd_from", "page(page_id) ON DELETE CASCADE" ),
+ array( "revision", "rev_page", "page (page_id) ON DELETE CASCADE" ),
+ array( "revision", "rev_user", "mwuser(user_id) ON DELETE RESTRICT" ),
+ array( "templatelinks", "tl_from", "page(page_id) ON DELETE CASCADE" ),
+ array( "trackbacks", "tb_page", "page(page_id) ON DELETE CASCADE" ),
+ array( "user_groups", "ug_user", "mwuser(user_id) ON DELETE CASCADE" ),
+ array( "user_newtalk", "user_id", "mwuser(user_id) ON DELETE CASCADE" ),
+ array( "user_properties", "up_user", "mwuser(user_id) ON DELETE CASCADE" ),
+ array( "watchlist", "wl_user", "mwuser(user_id) ON DELETE CASCADE" ),
);
- #Check new sequences, rename if needed
- foreach ($newsequences as $ns) {
- if( $wgDatabase->sequenceExists('pr_id_val') ) {
+ # Check new sequences, rename if needed
+ foreach ( $newsequences as $ns ) {
+ if ( $wgDatabase->sequenceExists( 'pr_id_val' ) ) {
wfOut( "Updating sequence names\n" );
- $wgDatabase->sourceFile(archive('patch-update_sequences.sql'));
+ $wgDatabase->sourceFile( archive( 'patch-update_sequences.sql' ) );
continue;
- } elseif ( $wgDatabase->sequenceExists('page_restrictions_pr_id_seq') ) {
+ } elseif ( $wgDatabase->sequenceExists( 'page_restrictions_pr_id_seq' ) ) {
wfOut( "... sequences already updated\n" );
continue;
} else {
wfOut( "Creating sequence \"$ns\"\n" );
- $wgDatabase->query("CREATE SEQUENCE $ns");
+ $wgDatabase->query( "CREATE SEQUENCE $ns" );
}
}
- foreach ($newtables as $nt) {
- if ($wgDatabase->tableExists($nt[0])) {
+ foreach ( $newtables as $nt ) {
+ if ( $wgDatabase->tableExists( $nt[0] ) ) {
wfOut( "... table \"$nt[0]\" already exists\n" );
continue;
}
wfOut( "Creating table \"$nt[0]\"\n" );
- $wgDatabase->sourceFile(archive($nt[1]));
+ $wgDatabase->sourceFile( archive( $nt[1] ) );
}
- ## Needed before newcols
- if ($wgDatabase->tableExists("archive2")) {
+ # # Needed before newcols
+ if ( $wgDatabase->tableExists( "archive2" ) ) {
wfOut( "Converting \"archive2\" back to normal archive table\n" );
- if ($wgDatabase->ruleExists("archive", "archive_insert")) {
+ if ( $wgDatabase->ruleExists( "archive", "archive_insert" ) ) {
wfOut( "Dropping rule \"archive_insert\"\n" );
- $wgDatabase->query("DROP RULE archive_insert ON archive");
+ $wgDatabase->query( "DROP RULE archive_insert ON archive" );
}
- if ($wgDatabase->ruleExists("archive", "archive_delete")) {
+ if ( $wgDatabase->ruleExists( "archive", "archive_delete" ) ) {
wfOut( "Dropping rule \"archive_delete\"\n" );
- $wgDatabase->query("DROP RULE archive_delete ON archive");
+ $wgDatabase->query( "DROP RULE archive_delete ON archive" );
}
- $wgDatabase->sourceFile(archive("patch-remove-archive2.sql"));
+ $wgDatabase->sourceFile( archive( "patch-remove-archive2.sql" ) );
}
else
wfOut( "... obsolete table \"archive2\" does not exist\n" );
- foreach ($newcols as $nc) {
- $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
- if (!is_null($fi)) {
+ foreach ( $newcols as $nc ) {
+ $fi = $wgDatabase->fieldInfo( $nc[0], $nc[1] );
+ if ( !is_null( $fi ) ) {
wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
continue;
}
wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
- $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
+ $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
}
- foreach ($typechanges as $tc) {
- $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
- if (is_null($fi)) {
+ foreach ( $typechanges as $tc ) {
+ $fi = $wgDatabase->fieldInfo( $tc[0], $tc[1] );
+ if ( is_null( $fi ) ) {
wfOut( "... error: expected column $tc[0].$tc[1] to exist\n" );
- exit(1);
+ exit( 1 );
}
- if ($fi->type() === $tc[2])
+ if ( $fi->type() === $tc[2] )
wfOut( "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n" );
else {
wfOut( "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n" );
$sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
- if (strlen($tc[3])) {
+ if ( strlen( $tc[3] ) ) {
$default = array();
- if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
+ if ( preg_match( '/DEFAULT (.+)/', $tc[3], $default ) ) {
$sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
- $wgDatabase->query($sqldef);
- $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
+ $wgDatabase->query( $sqldef );
+ $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3] );
}
$sql .= " USING $tc[3]";
}
$sql .= ";\nCOMMIT;\n";
- $wgDatabase->query($sql);
+ $wgDatabase->query( $sql );
}
}
- foreach ($nullchanges as $nc) {
- $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
- if (is_null($fi)) {
+ foreach ( $nullchanges as $nc ) {
+ $fi = $wgDatabase->fieldInfo( $nc[0], $nc[1] );
+ if ( is_null( $fi ) ) {
wfOut( "... error: expected column $nc[0].$nc[1] to exist\n" );
- exit(1);
+ exit( 1 );
}
- if ($fi->nullable()) {
- ## It's NULL - does it need to be NOT NULL?
- if ('NOT NULL' === $nc[2]) {
+ if ( $fi->nullable() ) {
+ # # It's NULL - does it need to be NOT NULL?
+ if ( 'NOT NULL' === $nc[2] ) {
wfOut( "Changing \"$nc[0].$nc[1]\" to not allow NULLs\n" );
$wgDatabase->query( "ALTER TABLE $nc[0] ALTER $nc[1] SET NOT NULL" );
}
}
}
else {
- ## It's NOT NULL - does it need to be NULL?
- if ('NULL' === $nc[2]) {
+ # # It's NOT NULL - does it need to be NULL?
+ if ( 'NULL' === $nc[2] ) {
wfOut( "Changing \"$nc[0].$nc[1]\" to allow NULLs\n" );
$wgDatabase->query( "ALTER TABLE $nc[0] ALTER $nc[1] DROP NOT NULL" );
}
}
}
- if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
+ if ( $wgDatabase->fieldInfo( 'oldimage', 'oi_deleted' )->type() !== 'smallint' ) {
wfOut( "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n" );
$wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
$wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
wfOut( "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n" );
- foreach ($newindexes as $ni) {
- if (pg_index_exists($ni[0], $ni[1])) {
+ foreach ( $newindexes as $ni ) {
+ if ( pg_index_exists( $ni[0], $ni[1] ) ) {
wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
continue;
}
$wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
}
- foreach ($newrules as $nr) {
- if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
+ foreach ( $newrules as $nr ) {
+ if ( $wgDatabase->ruleExists( $nr[0], $nr[1] ) ) {
wfOut( "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n" );
continue;
}
wfOut( "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n" );
- $wgDatabase->sourceFile(archive($nr[2]));
+ $wgDatabase->sourceFile( archive( $nr[2] ) );
}
- if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey_cascaded")) {
+ if ( $wgDatabase->hasConstraint( "oldimage_oi_name_fkey_cascaded" ) ) {
wfOut( "... table \"oldimage\" has correct cascading delete/update foreign key to image\n" );
}
else {
- if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
+ if ( $wgDatabase->hasConstraint( "oldimage_oi_name_fkey" ) ) {
$wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
}
- if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey_cascade")) {
+ if ( $wgDatabase->hasConstraint( "oldimage_oi_name_fkey_cascade" ) ) {
$wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey_cascade" );
}
wfOut( "Making foreign key on table \"oldimage\" (to image) a cascade delete/update\n" );
- $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascaded ".
+ $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascaded " .
"FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE ON UPDATE CASCADE" );
}
- if (!$wgDatabase->triggerExists("page", "page_deleted")) {
+ if ( !$wgDatabase->triggerExists( "page", "page_deleted" ) ) {
wfOut( "Adding function and trigger \"page_deleted\" to table \"page\"\n" );
- $wgDatabase->sourceFile(archive('patch-page_deleted.sql'));
+ $wgDatabase->sourceFile( archive( 'patch-page_deleted.sql' ) );
}
else
wfOut( "... table \"page\" has \"page_deleted\" trigger\n" );
- $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
- if (!$fi->nullable()) {
+ $fi = $wgDatabase->fieldInfo( "recentchanges", "rc_cur_id" );
+ if ( !$fi->nullable() ) {
wfOut( "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n" );
- $wgDatabase->sourceFile(archive('patch-rc_cur_id-not-null.sql'));
+ $wgDatabase->sourceFile( archive( 'patch-rc_cur_id-not-null.sql' ) );
}
else
wfOut( "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n" );
- $pu = pg_describe_index("pagelink_unique");
- if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
+ $pu = pg_describe_index( "pagelink_unique" );
+ if ( !is_null( $pu ) && ( $pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title" ) ) {
wfOut( "Dropping obsolete version of index \"pagelink_unique index\"\n" );
- $wgDatabase->query("DROP INDEX pagelink_unique");
+ $wgDatabase->query( "DROP INDEX pagelink_unique" );
$pu = null;
}
else
wfOut( "... obsolete version of index \"pagelink_unique index\" does not exist\n" );
- if (is_null($pu)) {
+ if ( is_null( $pu ) ) {
wfOut( "Creating index \"pagelink_unique index\"\n" );
- $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
+ $wgDatabase->query( "CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)" );
}
else
wfOut( "... index \"pagelink_unique_index\" already exists\n" );
- if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
+ if ( pg_fkey_deltype( "revision_rev_user_fkey" ) == 'r' ) {
wfOut( "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n" );
}
else {
wfOut( "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n" );
- $wgDatabase->sourceFile(archive('patch-revision_rev_user_fkey.sql'));
+ $wgDatabase->sourceFile( archive( 'patch-revision_rev_user_fkey.sql' ) );
}
# Fix ipb_address index
- if (pg_index_exists('ipblocks', 'ipb_address' )) {
+ if ( pg_index_exists( 'ipblocks', 'ipb_address' ) ) {
wfOut( "Removing deprecated index 'ipb_address'...\n" );
- $wgDatabase->query('DROP INDEX ipb_address');
+ $wgDatabase->query( 'DROP INDEX ipb_address' );
}
- if (pg_index_exists('ipblocks', 'ipb_address_unique' )) {
+ if ( pg_index_exists( 'ipblocks', 'ipb_address_unique' ) ) {
wfOut( "... have ipb_address_unique\n" );
}
else {
wfOut( "Adding ipb_address_unique index\n" );
- $wgDatabase->sourceFile(archive('patch-ipb_address_unique.sql'));
+ $wgDatabase->sourceFile( archive( 'patch-ipb_address_unique.sql' ) );
}
global $wgExtNewTables, $wgExtPGNewFields, $wgExtPGAlteredFields, $wgExtNewIndexes;
# Add missing extension tables
foreach ( $wgExtNewTables as $nt ) {
- if ($wgDatabase->tableExists($nt[0])) {
+ if ( $wgDatabase->tableExists( $nt[0] ) ) {
wfOut( "... table \"$nt[0]\" already exists\n" );
continue;
}
wfOut( "Creating table \"$nt[0]\"\n" );
- $wgDatabase->sourceFile($nt[1]);
+ $wgDatabase->sourceFile( $nt[1] );
}
# Add missing extension fields
foreach ( $wgExtPGNewFields as $nc ) {
- $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
- if (!is_null($fi)) {
+ $fi = $wgDatabase->fieldInfo( $nc[0], $nc[1] );
+ if ( !is_null( $fi ) ) {
wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
continue;
}
}
# Change altered columns
foreach ( $wgExtPGAlteredFields as $nc ) {
- $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
- if (is_null($fi)) {
+ $fi = $wgDatabase->fieldInfo( $nc[0], $nc[1] );
+ if ( is_null( $fi ) ) {
wfOut( "WARNING! Column \"$nc[0].$nc[1]\" does not exist but had an alter request! Please report this.\n" );
continue;
}
$oldtype = $fi->type();
$newtype = strtolower( $nc[2] );
- if ($oldtype === $newtype) {
+ if ( $oldtype === $newtype ) {
wfOut( "... column \"$nc[0].$nc[1]\" has correct type of \"$newtype\"\n" );
continue;
}
}
# Add missing extension indexes
foreach ( $wgExtNewIndexes as $ni ) {
- if (pg_index_exists($ni[0], $ni[1])) {
+ if ( pg_index_exists( $ni[0], $ni[1] ) ) {
wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
continue;
}
$wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
}
else {
- $wgDatabase->sourceFile($ni[2]);
+ $wgDatabase->sourceFile( $ni[2] );
}
}
foreach ( $deferredcols AS $dc ) {
- $fi = $wgDatabase->fieldInfo($dc[0], $dc[1]);
- if (is_null($fi)) {
+ $fi = $wgDatabase->fieldInfo( $dc[0], $dc[1] );
+ if ( is_null( $fi ) ) {
wfOut( "WARNING! Column \"$dc[0].$dc[1]\" does not exist but it should! Please report this.\n" );
continue;
}
# Tweak the page_title tsearch2 trigger to filter out slashes
# This is create or replace, so harmless to call if not needed
- $wgDatabase->sourceFile(archive('patch-ts2pagetitle.sql'));
+ $wgDatabase->sourceFile( archive( 'patch-ts2pagetitle.sql' ) );
- ## If the server is 8.3 or higher, rewrite the tsearch2 triggers
- ## in case they have the old 'default' versions
+ # # If the server is 8.3 or higher, rewrite the tsearch2 triggers
+ # # in case they have the old 'default' versions
if ( $numver >= 8.3 )
- $wgDatabase->sourceFile(archive('patch-tsearch2funcs.sql'));
+ $wgDatabase->sourceFile( archive( 'patch-tsearch2funcs.sql' ) );
return;
}
$options = array( 'step', 'noimages' );
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
require_once( 'FiveUpgrade.inc' );
echo "ATTENTION: This script is for upgrades from 1.4 to 1.5 (NOT 1.15) in very special cases.\n";
function hasUniqueIndex() {
$fname = 'UserDupes::hasUniqueIndex';
$info = $this->db->indexInfo( 'user', 'user_name', $fname );
- if( !$info ) {
+ if ( !$info ) {
wfOut( "WARNING: doesn't seem to have user_name index at all!\n" );
return false;
}
* @return bool
*/
function checkDupes( $doDelete = false ) {
- if( $this->hasUniqueIndex() ) {
- echo wfWikiID()." already has a unique index on its user table.\n";
+ if ( $this->hasUniqueIndex() ) {
+ echo wfWikiID() . " already has a unique index on its user table.\n";
return true;
}
$dupes = $this->getDupes();
$count = count( $dupes );
- wfOut( "Found $count accounts with duplicate records on ".wfWikiID().".\n" );
+ wfOut( "Found $count accounts with duplicate records on " . wfWikiID() . ".\n" );
$this->trimmed = 0;
$this->reassigned = 0;
$this->failed = 0;
- foreach( $dupes as $name ) {
+ foreach ( $dupes as $name ) {
$this->examine( $name, $doDelete );
}
wfOut( "\n" );
- if( $this->reassigned > 0 ) {
- if( $doDelete ) {
+ if ( $this->reassigned > 0 ) {
+ if ( $doDelete ) {
wfOut( "$this->reassigned duplicate accounts had edits reassigned to a canonical record id.\n" );
} else {
wfOut( "$this->reassigned duplicate accounts need to have edits reassigned.\n" );
}
}
- if( $this->trimmed > 0 ) {
- if( $doDelete ) {
- wfOut( "$this->trimmed duplicate user records were deleted from ".wfWikiID().".\n" );
+ if ( $this->trimmed > 0 ) {
+ if ( $doDelete ) {
+ wfOut( "$this->trimmed duplicate user records were deleted from " . wfWikiID() . ".\n" );
} else {
- wfOut( "$this->trimmed duplicate user accounts were found on ".wfWikiID()." which can be removed safely.\n" );
+ wfOut( "$this->trimmed duplicate user accounts were found on " . wfWikiID() . " which can be removed safely.\n" );
}
}
- if( $this->failed > 0 ) {
+ if ( $this->failed > 0 ) {
wfOut( "Something terribly awry; $this->failed duplicate accounts were not removed.\n" );
return false;
}
- if( $this->trimmed == 0 || $doDelete ) {
+ if ( $this->trimmed == 0 || $doDelete ) {
wfOut( "It is now safe to apply the unique index on user_name.\n" );
return true;
} else {
*/
function lock() {
$fname = 'UserDupes::lock';
- if( $this->newSchema() ) {
+ if ( $this->newSchema() ) {
$set = array( 'user', 'revision' );
} else {
$set = array( 'user', 'cur', 'old' );
HAVING n > 1", $fname );
$list = array();
- while( $row = $this->db->fetchObject( $result ) ) {
+ while ( $row = $this->db->fetchObject( $result ) ) {
$list[] = $row->user_name;
}
$this->db->freeResult( $result );
$firstId = $firstRow->user_id;
wfOut( "Record that will be used for '$name' is user_id=$firstId\n" );
- while( $row = $this->db->fetchObject( $result ) ) {
+ while ( $row = $this->db->fetchObject( $result ) ) {
$dupeId = $row->user_id;
wfOut( "... dupe id $dupeId: " );
$edits = $this->editCount( $dupeId );
- if( $edits > 0 ) {
+ if ( $edits > 0 ) {
$this->reassigned++;
wfOut( "has $edits edits! " );
- if( $doDelete ) {
+ if ( $doDelete ) {
$this->reassignEdits( $dupeId, $firstId );
$newEdits = $this->editCount( $dupeId );
- if( $newEdits == 0 ) {
+ if ( $newEdits == 0 ) {
wfOut( "confirmed cleaned. " );
} else {
$this->failed++;
wfOut( "ok, no edits. " );
}
$this->trimmed++;
- if( $doDelete ) {
+ if ( $doDelete ) {
$this->trimAccount( $dupeId );
}
wfOut( "\n" );
* @access private
*/
function editCount( $userid ) {
- if( $this->newSchema() ) {
+ if ( $this->newSchema() ) {
return $this->editCountOn( 'revision', 'rev_user', $userid );
} else {
return $this->editCountOn( 'cur', 'cur_user', $userid ) +
$set = $this->newSchema()
? array( 'revision' => 'rev_user' )
: array( 'cur' => 'cur_user', 'old' => 'old_user' );
- foreach( $set as $table => $field ) {
+ foreach ( $set as $table => $field ) {
$this->reassignEditsOn( $table, $field, $from, $to );
}
}
$options = array( 'list', 'nowarn', 'quiet', 'usage', 'dry' );
$optionsWithArgs = array( 'old', 'new' );
-require_once( dirname(__FILE__) . '/commandLine.inc' );
+require_once( dirname( __FILE__ ) . '/commandLine.inc' );
/**
* @ingroup Maintenance
/** Constructor. Will show usage and exit if script options are not correct */
function __construct( $opts, $args ) {
- if( !$this->checkOpts( $opts, $args ) ) {
+ if ( !$this->checkOpts( $opts, $args ) ) {
userOptions::showUsageAndExit();
} else {
$this->mReady = $this->initializeOpts( $opts, $args );
private function checkOpts( $opts, $args ) {
// The three possible ways to run the script:
$list = isset( $opts['list'] );
- $usage = isset( $opts['usage'] ) && (count($args) <= 1);
- $change = isset( $opts['old']) && isset($opts['new']) && (count($args) <= 1) ;
+ $usage = isset( $opts['usage'] ) && ( count( $args ) <= 1 );
+ $change = isset( $opts['old'] ) && isset( $opts['new'] ) && ( count( $args ) <= 1 ) ;
// We want only one of them
- $isValid = (($list + $usage + $change) == 1);
+ $isValid = ( ( $list + $usage + $change ) == 1 );
return $isValid;
}
$this->mDry = isset( $opts['dry'] );
// Set object properties, specially 'mMode' used by run()
- if( isset($opts['list']) ) {
+ if ( isset( $opts['list'] ) ) {
$this->mMode = 'LISTER' ;
- } elseif( isset($opts['usage']) ) {
+ } elseif ( isset( $opts['usage'] ) ) {
$this->mMode = 'USAGER' ;
- $this->mAnOption = isset($args[0]) ? $args[0] : false ;
- } elseif( isset($opts['old']) && isset($opts['new']) ) {
+ $this->mAnOption = isset( $args[0] ) ? $args[0] : false ;
+ } elseif ( isset( $opts['old'] ) && isset( $opts['new'] ) ) {
$this->mMode = 'CHANGER' ;
$this->mOldValue = $opts['old'] ;
$this->mNewValue = $opts['new'] ;
$this->mAnOption = $args[0];
} else {
- die("There is a bug in the software, this should never happen\n");
+ die( "There is a bug in the software, this should never happen\n" );
}
return true;
// Dumb stuff to run a mode.
public function run() {
- if(!$this->mReady ) {
+ if ( !$this->mReady ) {
return false;
}
- $this->{$this->mMode}( );
+ $this-> { $this->mMode } ( );
}
/** List default options and their value */
private function LISTER( ) {
$def = User::getDefaultOptions();
- ksort($def);
+ ksort( $def );
$maxOpt = 0;
- foreach( $def as $opt => $value ) {
- $maxOpt = max( $maxOpt, strlen($opt) );
+ foreach ( $def as $opt => $value ) {
+ $maxOpt = max( $maxOpt, strlen( $opt ) );
}
- foreach( $def as $opt => $value ) {
+ foreach ( $def as $opt => $value ) {
printf( "%-{$maxOpt}s: %s\n", $opt, $value );
}
}
__METHOD__
);
- while( $id = $dbr->fetchObject( $result ) ) {
+ while ( $id = $dbr->fetchObject( $result ) ) {
$user = User::newFromId( $id->user_id );
// Get the options and update stats
- if( $this->mAnOption ) {
+ if ( $this->mAnOption ) {
- if(!array_key_exists( $this->mAnOption, $defaultOptions ) ) {
+ if ( !array_key_exists( $this->mAnOption, $defaultOptions ) ) {
print "Invalid user option. Use --list to see valid choices\n";
exit;
}
$userValue = $user->getOption( $this->mAnOption );
- if( $userValue <> $defaultOptions[$this->mAnOption] ) {
+ if ( $userValue <> $defaultOptions[$this->mAnOption] ) {
@$ret[$this->mAnOption][$userValue]++;
}
} else {
- foreach( $defaultOptions as $name => $defaultValue ) {
+ foreach ( $defaultOptions as $name => $defaultValue ) {
$userValue = $user->getOption( $name );
- if( $userValue <> $defaultValue ) {
+ if ( $userValue <> $defaultValue ) {
@$ret[$name][$userValue]++;
}
}
}
}
- foreach( $ret as $optionName => $usageStats ) {
+ foreach ( $ret as $optionName => $usageStats ) {
print "Usage for <$optionName> (default: '{$defaultOptions[$optionName]}'):\n";
- foreach( $usageStats as $value => $count ) {
+ foreach ( $usageStats as $value => $count ) {
print " $count user(s): '$value'\n";
}
print "\n";
__METHOD__
);
- while( $id = $dbr->fetchObject( $result ) ) {
+ while ( $id = $dbr->fetchObject( $result ) ) {
$user = User::newFromId( $id->user_id );
$curValue = $user->getOption( $this->mAnOption );
$username = $user->getName();
- if( $curValue == $this->mOldValue ) {
+ if ( $curValue == $this->mOldValue ) {
- if(!$this->mQuiet) {
+ if ( !$this->mQuiet ) {
print "Setting {$this->mAnOption} for $username from '{$this->mOldValue}' to '{$this->mNewValue}'): ";
}
$user->setOption( $this->mAnOption, $this->mNewValue );
// Will not save the settings if run with --dry
- if(!$this->mDry) {
+ if ( !$this->mDry ) {
$user->saveSettings();
}
- if( !$this->mQuiet) { print " OK\n"; }
+ if ( !$this->mQuiet ) { print " OK\n"; }
- } elseif( !$this->mQuiet ) {
+ } elseif ( !$this->mQuiet ) {
print "Not changing '$username' using <{$this->mAnOption}> = '$curValue'\n";
}
}
public static function getDefaultOptionsNames() {
$def = User::getDefaultOptions();
$ret = array();
- foreach( $def as $optname => $defaultValue) {
+ foreach ( $def as $optname => $defaultValue ) {
array_push( $ret, $optname );
}
return $ret;
--dry : do not save user settings back to database
USAGE;
- exit(0);
+ exit( 0 );
}
/** The warning message and countdown */
public function warn() {
- if( $this->mQuick ) {
+ if ( $this->mQuick ) {
return true;
}
* @see wfWaitForSlaves()
*/
-require_once( dirname(__FILE__) . '/Maintenance.php' );
+require_once( dirname( __FILE__ ) . '/Maintenance.php' );
class WaitForSlave extends Maintenance {
public function __construct() {