* Constants for DB access type
* @see Maintenance::getDbType()
*/
- const DB_NONE = 0;
- const DB_STD = 1;
+ const DB_NONE = 0;
+ const DB_STD = 1;
const DB_ADMIN = 2;
// Const for getStdin()
return false; // last call should be to this function
}
$includeFuncs = array( 'require_once', 'require', 'include', 'include_once' );
- for( $i = 1; $i < $count; $i++ ) {
+ for ( $i = 1; $i < $count; $i++ ) {
if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
return false; // previous calls should all be "requires"
}
"server name detection may fail in command line scripts.", false, true );
# Save generic options to display them separately in help
- $this->mGenericParameters = $this->mParams ;
+ $this->mGenericParameters = $this->mParams;
# Script dependant options:
$wgCommandLineMode = true;
# Turn off output buffering if it's on
- while( ob_get_level() > 0 ) {
+ while ( ob_get_level() > 0 ) {
ob_end_flush();
}
} elseif ( substr( $arg, 0, 1 ) == '-' ) {
# Short options
for ( $p = 1; $p < strlen( $arg ); $p++ ) {
- $option = $arg { $p } ;
+ $option = $arg { $p };
if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
$option = $this->mShortParamsMap[$option];
}
* @param $force boolean Whether to force the help to show, default false
*/
protected function maybeHelp( $force = false ) {
- if( !$force && !$this->hasOption( 'help' ) ) {
+ if ( !$force && !$this->hasOption( 'help' ) ) {
return;
}
} else {
$output .= '[' . $arg['name'] . ']';
}
- if ( $k < count( $this->mArgList ) - 1 )
+ if ( $k < count( $this->mArgList ) - 1 ) {
$output .= ' ';
+ }
}
}
$this->output( "$output\n\n" );
$this->output( "\n" );
$scriptDependantParams = $this->mDependantParameters;
- if( count($scriptDependantParams) > 0 ) {
+ if ( count($scriptDependantParams) > 0 ) {
$this->output( "Script dependant parameters:\n" );
// Parameters description
foreach ( $scriptDependantParams as $par => $info ) {
$this->mGenericParameters,
$this->mDependantParameters
);
- if( count($scriptSpecificParams) > 0 ) {
+ if ( count($scriptSpecificParams) > 0 ) {
$this->output( "Script specific parameters:\n" );
// Parameters description
foreach ( $scriptSpecificParams as $par => $info ) {
}
// Print arguments
- if( count( $this->mArgList ) > 0 ) {
+ if ( count( $this->mArgList ) > 0 ) {
$this->output( "Arguments:\n" );
// Arguments description
foreach ( $this->mArgList as $info ) {
$wgCommandLineMode = true;
# Override $wgServer
- if( $this->hasOption( 'server') ) {
+ if ( $this->hasOption( 'server' ) ) {
$wgServer = $this->getOption( 'server', $wgServer );
}
if ( isset( $this->mOptions['conf'] ) ) {
$settingsFile = $this->mOptions['conf'];
- } elseif ( defined("MW_CONFIG_FILE") ) {
+ } elseif ( defined( "MW_CONFIG_FILE" ) ) {
$settingsFile = MW_CONFIG_FILE;
} else {
$settingsFile = "$IP/LocalSettings.php";
$st = fgets( STDIN, 1024 );
}
}
- if ( $st === false ) return false;
+ if ( $st === false ) {
+ return false;
+ }
$resp = trim( $st );
return $resp;
}
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( $this->history );
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();
}
$ok = fwrite( $this->spawnWrite, "$id\n" );
// $this->progress( ">> $id" );
- if ( !$ok ) return false;
+ if ( !$ok ) {
+ return false;
+ }
$ok = fflush( $this->spawnWrite );
// $this->progress( ">> [flush]" );
- if ( !$ok ) return false;
+ if ( !$ok ) {
+ return false;
+ }
// check that the text id they are sending is the one we asked for
// this avoids out of sync revision text errors we have encountered in the past
$len = fgets( $this->spawnRead );
// $this->progress( "<< " . trim( $len ) );
- if ( $len === false ) return false;
+ if ( $len === false ) {
+ return false;
+ }
$nbytes = intval( $len );
// actual error, not zero-length text
- if ( $nbytes < 0 ) return false;
+ if ( $nbytes < 0 ) {
+ return false;
+ }
$text = "";
// Subprocess may not send everything at once, we have to loop.
while ( $nbytes > strlen( $text ) ) {
$buffer = fread( $this->spawnRead, $nbytes - strlen( $text ) );
- if ( $buffer === false ) break;
+ if ( $buffer === false ) {
+ break;
+ }
$text .= $buffer;
}
function cdbShowHelp( $command ) {
$commandList = array(
'load' => 'load a cdb file for reading',
- 'get' => 'get a value for a key',
+ 'get' => 'get a value for a key',
'exit' => 'exit cdb',
'quit' => 'exit cdb',
'help' => 'help about a command',
static $fileHandle;
$line = Maintenance::readconsole();
- if ( $line === false ) exit;
+ if ( $line === false ) {
+ exit;
+ }
$args = explode( ' ', $line );
$command = array_shift( $args );
cdbShowHelp( array_shift( $args ) );
break;
case 'load':
- if( !isset( $args[0] ) ) {
+ if ( !isset( $args[0] ) ) {
print "Need a filename there buddy\n";
break;
}
$file = $args[0];
print "Loading cdb file $file...";
$fileHandle = CdbReader::open( $file );
- if( !$fileHandle ) {
+ if ( !$fileHandle ) {
print "not a cdb file or unable to read it\n";
} else {
print "ok\n";
}
break;
case 'get':
- if( !$fileHandle ) {
+ if ( !$fileHandle ) {
print "Need to load a cdb file first\n";
break;
}
- if( !isset( $args[0] ) ) {
+ if ( !isset( $args[0] ) ) {
print "Need to specify a key, Luke\n";
break;
}
private function isSuitableFile( $file ) {
$file = str_replace( '\\', '/', $file );
$ext = pathinfo( $file, PATHINFO_EXTENSION );
- if ( $ext != 'php' && $ext != 'inc' && $ext != 'php5' )
+ if ( $ext != 'php' && $ext != 'inc' && $ext != 'php5' ) {
return false;
+ }
foreach ( $this->mIgnorePaths as $regex ) {
$m = array();
- if ( preg_match( "~{$regex}~", $file, $m ) )
+ if ( preg_match( "~{$regex}~", $file, $m ) ) {
return false;
+ }
}
return true;
}
private function checkForMistakes( $file ) {
foreach ( $this->mNoStyleCheckPaths as $regex ) {
$m = array();
- if ( preg_match( "~{$regex}~", $file, $m ) )
+ if ( preg_match( "~{$regex}~", $file, $m ) ) {
return;
+ }
}
$text = file_get_contents( $file );
$tokens = token_get_all( $text );
- $this->checkEvilToken( $file, $tokens, '@', 'Error supression operator (@)');
+ $this->checkEvilToken( $file, $tokens, '@', 'Error supression operator (@)' );
$this->checkRegex( $file, $text, '/^[\s\r\n]+<\?/', 'leading whitespace' );
$this->checkRegex( $file, $text, '/\?>[\s\r\n]*$/', 'trailing ?>' );
$this->checkRegex( $file, $text, '/^[\xFF\xFE\xEF]/', 'byte-order mark' );
}
public function execute() {
- if( !$this->hasOption( 'force' ) ) {
+ if ( !$this->hasOption( 'force' ) ) {
$this->error( "This maintenance script will remove old columns and indexes.\n"
. "It is recommended to backup your database first, and ensure all your data has been migrated to newer tables\n"
. "If you want to continue, run this script again with the --force \n"
'validate', // 1.6
);
- foreach( $ancientTables as $table ) {
+ foreach ( $ancientTables as $table ) {
if ( $db->tableExists( $table, __METHOD__ ) ) {
$this->output( "Dropping table $table..." );
$db->dropTable( $table, __METHOD__ );
'user_timestamp',
'usertext_timestamp',
);
- foreach( $oldIndexes as $index ) {
+ foreach ( $oldIndexes as $index ) {
if ( $db->indexExists( 'text', $index, __METHOD__ ) ) {
$this->output( "Dropping index $index from the text table..." );
$db->query( "DROP INDEX " . $db->addIdentifierQuotes( $index )
'old_minor_edit',
'inverse_timestamp',
);
- foreach( $oldFields as $field ) {
+ foreach ( $oldFields as $field ) {
if ( $db->fieldExists( 'text', $field, __METHOD__ ) ) {
$this->output( "Dropping the $field field from the text table..." );
$db->query( "ALTER TABLE " . $db->tableName( 'text' )
$dbw = wfGetDB( DB_MASTER );
$dbw->begin( __METHOD__ );
- foreach( $wgHiddenPrefs as $item ) {
+ foreach ( $wgHiddenPrefs as $item ) {
$dbw->delete(
'user_properties',
array( 'up_property' => $item ),
$this->output( "Batch $i: $numRows rows\n" );
$i++;
wfWaitForSlaves( $maxlag );
- } while( $numRows > 0 );
+ } while ( $numRows > 0 );
$this->output( "done\n" );
$this->output( "Cleaning up msg_resource table...\n" );
$this->output( "Batch $i: $numRows rows\n" );
$i++;
wfWaitForSlaves( $maxlag );
- } while( $numRows > 0 );
+ } while ( $numRows > 0 );
$this->output( "done\n" );
$this->output( "Cleaning up msg_resource_links table...\n" );
$this->output( "Batch $i: $numRows rows\n" );
$i++;
wfWaitForSlaves( $maxlag );
- } while( $numRows > 0 );
+ } while ( $numRows > 0 );
$this->output( "done\n" );
}
}
$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 );
# Old cleanupTitles could move articles there. See bug 23147.
$ns = $row->page_namespace;
- if ( $ns < 0 ) $ns = 0;
+ if ( $ns < 0 ) {
+ $ns = 0;
+ }
$clean = 'Broken/' . $prior;
$verified = Title::makeTitleSafe( $ns, $clean );
} else {
// finish the read before starting writes.
$keys = array();
- foreach( $res as $row ) {
+ foreach ( $res as $row ) {
array_push( $keys, $row->us_key );
}
$stash = new UploadStash( $repo );
$i = 0;
- foreach( $keys as $key ) {
+ foreach ( $keys as $key ) {
$i++;
try {
$stash->getFile( $key, true );
}
// Delete all the corresponding thumbnails...
- $dir = $tempRepo->getZonePath( 'thumb' );
+ $dir = $tempRepo->getZonePath( 'thumb' );
$iterator = $tempRepo->getBackend()->getFileList( array( 'dir' => $dir ) );
$this->output( "Deleting old thumbnails...\n" );
$i = 0;
$this->output( "$i done\n" );
// Apparently lots of stash files are not registered in the DB...
- $dir = $tempRepo->getZonePath( 'public' );
+ $dir = $tempRepo->getZonePath( 'public' );
$iterator = $tempRepo->getBackend()->getFileList( array( 'dir' => $dir ) );
$this->output( "Deleting orphaned temp files...\n" );
if ( strpos( $dir, '/local-temp' ) === false ) { // sanity check
if ( !$this->dryrun && $this->hasOption( 'fix' ) ) {
$dbw = wfGetDB( DB_MASTER );
$dbw->delete( 'watchlist', array(
- 'wl_user' => $row->wl_user,
+ 'wl_user' => $row->wl_user,
'wl_namespace' => $row->wl_namespace,
- 'wl_title' => $row->wl_title ),
+ 'wl_title' => $row->wl_title ),
__METHOD__ );
$this->output( "- removed\n" );
return 1;
}
public function checkOptions() {
- if ( $this->hasOption('save-failed') ) {
- $this->saveFailed = $this->getOption('save-failed');
+ if ( $this->hasOption( 'save-failed' ) ) {
+ $this->saveFailed = $this->getOption( 'save-failed' );
}
$this->stripParametersEnabled = $this->hasOption( 'strip-parameters' );
public function conclusions() {
$this->error( "{$this->failed} failed revisions out of {$this->count}" );
- if ($this->count > 0)
+ if ( $this->count > 0 ) {
$this->output( " (" . ( $this->failed / $this->count ) . "%)\n" );
+ }
}
function stripParameters( $text ) {
list ( $cur, $links, $links_temp, $links_backup ) = $dbw->tableNamesN( 'cur', 'links', 'links_temp', 'links_backup' );
- if( $dbw->tableExists( 'pagelinks' ) ) {
+ if ( $dbw->tableExists( 'pagelinks' ) ) {
$this->output( "...have pagelinks; skipping old links table updates\n" );
return;
}
}
$dbw->query( implode( "", $sqlWrite ) );
$totalTuplesInserted += $tuplesAdded;
- if ( $reportLinksConvProgress )
+ if ( $reportLinksConvProgress ) {
$this->output( " done. Total $totalTuplesInserted tuples inserted.\n" );
- $this->performanceLog( $fh, $totalTuplesInserted . " " . ( $this->getMicroTime() - $baseTime ) . "\n" );
+ $this->performanceLog( $fh, $totalTuplesInserted . " " . ( $this->getMicroTime() - $baseTime ) . "\n" );
+ }
}
}
$this->output( "$totalTuplesInserted valid titles and $numBadLinks invalid titles were processed.\n\n" );
$group = $row->fa_storage_group;
$id = $row->fa_id;
$path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
- if( isset( $row->fa_sha1 ) ) {
+ if ( isset( $row->fa_sha1 ) ) {
$sha1 = $row->fa_sha1;
} else {
// old row, populate from key
)
);
- if( $dbr->numRows( $res ) == 0 ) {
+ if ( $dbr->numRows( $res ) == 0 ) {
# No more messages left
$this->output( "done.\n" );
return;
$total = $this->getImageCount();
foreach ( $res as $row ) {
- if ( $i % $this->report == 0 )
+ 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;
}
# Stash 'em all up for deletion (if needed)
$revisions = array();
- foreach ( $res as $row )
+ foreach ( $res as $row ) {
$revisions[] = $row->rev_id;
+ }
$count = count( $revisions );
$this->output( "found {$count}.\n" );
* @param $dbw DatabaseBase 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__ );
}
}
. $db->buildLike( $wgServer . '/', $db->anyString() ), $this->mBatchSize );
$this->output( "Deleting a batch\n" );
$db->query( $q );
- if ( !$db->affectedRows() ) return;
+ if ( !$db->affectedRows() ) {
+ return;
+ }
}
}
}
die( "This script can only be run by php's cli-server sapi." );
}
-ini_set('display_errors', 1);
-error_reporting(E_ALL);
+ini_set( 'display_errors', 1 );
+error_reporting( E_ALL );
if ( isset( $_SERVER["SCRIPT_FILENAME"] ) ) {
# Known resource, sometimes a script sometimes a file
# This way we can serve things like .svg files that the built-in
# PHP webserver doesn't understand.
# ;) Nicely enough we just happen to bundle a mime.types file
- $f = fopen($file, 'rb');
+ $f = fopen( $file, 'rb' );
if ( preg_match( '#^text/#', $mime ) ) {
# Text should have a charset=UTF-8 (php's webserver does this too)
- header("Content-Type: $mime; charset=UTF-8");
+ header( "Content-Type: $mime; charset=UTF-8" );
} else {
- header("Content-Type: $mime");
+ header( "Content-Type: $mime" );
}
- header("Content-Length: " . filesize($file));
+ header( "Content-Length: " . filesize( $file ) );
// Stream that out to the browser
- fpassthru($f);
+ fpassthru( $f );
return true;
}
// Wasn't included from the file scope, halt execution (probably wanted the class)
// If a class is using commandLine.inc (old school maintenance), they definitely
// cannot be included and will proceed with execution
-if( !Maintenance::shouldExecute() && $maintClass != 'CommandLineInc' ) {
+if ( !Maintenance::shouldExecute() && $maintClass != 'CommandLineInc' ) {
return;
}
}
if ( $maintenance->getDbType() === Maintenance::DB_NONE ) {
- if ( $wgLocalisationCacheConf['storeClass'] === false && ( $wgLocalisationCacheConf['store'] == 'db' || ( $wgLocalisationCacheConf['store'] == 'detect' && !$wgCacheDirectory ) ) )
+ if ( $wgLocalisationCacheConf['storeClass'] === false && ( $wgLocalisationCacheConf['store'] == 'db' || ( $wgLocalisationCacheConf['store'] == 'detect' && !$wgCacheDirectory ) ) ) {
$wgLocalisationCacheConf['storeClass'] = 'LCStore_Null';
+ }
}
$maintenance->finalSetup();
// Some last includes
$originalDir = getcwd();
-$optionsWithArgs = array( 'pagelist', 'start', 'end', 'revstart', 'revend');
+$optionsWithArgs = array( 'pagelist', 'start', 'end', 'revstart', 'revend' );
require_once( __DIR__ . '/commandLine.inc' );
require_once( __DIR__ . '/backup.inc' );
}
public function execute() {
- if ( !( $this->hasOption('file') ^ $this->hasOption('dump') ) ) {
- $this->error("You must provide a file or dump", true);
+ if ( !( $this->hasOption( 'file' ) ^ $this->hasOption( 'dump' ) ) ) {
+ $this->error( "You must provide a file or dump", true );
}
$this->checkOptions();
- if ( $this->hasOption('file') ) {
+ if ( $this->hasOption( 'file' ) ) {
$revision = new WikiRevision;
$revision->setText( file_get_contents( $this->getOption( 'file' ) ) );
$this->startTime = microtime( true );
- if ( $this->getOption('dump') == '-' ) {
+ if ( $this->getOption( 'dump' ) == '-' ) {
$source = new ImportStreamSource( $this->getStdin() );
} else {
- $this->error("Sorry, I don't support dump filenames yet. Use - and provide it on stdin on the meantime.", true);
+ $this->error( "Sorry, I don't support dump filenames yet. Use - and provide it on stdin on the meantime.", true );
}
$importer = new WikiImporter( $source );
$delta = microtime( true ) - $this->startTime;
$this->error( "Done {$this->count} revisions in " . round($delta, 2) . " seconds " );
- if ($delta > 0)
+ if ( $delta > 0 ) {
$this->error( round($this->count / $delta, 2) . " pages/sec" );
+ }
# Perform the memory_get_peak_usage() when all the other data has been output so there's no damage if it dies.
# It is only available since 5.2.0 (since 5.2.1 if you haven't compiled with --enable-memory-limit)
$this->count++;
if ( isset( $this->from ) ) {
- if ( $this->from != $title )
+ if ( $this->from != $title ) {
return;
+ }
$this->output( "Skipped " . ($this->count - 1) . " pages\n" );
$this->count = 1;
$link = Title::makeTitle( $row->pl_namespace, $row->pl_title );
$this->output( " " . $link->getPrefixedURL() );
}
- if ( isset( $lastPage ) )
+ if ( isset( $lastPage ) ) {
$this->output( "\n" );
+ }
}
}
$dbr->bufferResults( false );
$result = $dbr->select( 'page',
array( 'page_namespace', 'page_title' ),
- array( 'page_namespace' => NS_MAIN,
- 'page_is_redirect' => 0,
+ array(
+ 'page_namespace' => NS_MAIN,
+ 'page_is_redirect' => 0,
),
__METHOD__ );
*
* note that that the text string itself is *not* followed by newline
*/
- public function execute() {
+ public function execute() {
$db = wfGetDB( DB_SLAVE );
$stdin = $this->getStdin();
while ( !feof( $stdin ) ) {
$db = wfGetDB( $i );
/*
if ( !$db->masterPosWait( $masterFile, $masterPos, 10 ) ) {
- $this->output( "Slave is too lagged, aborting\n" );
- $dbw->commit( __METHOD__ );
- sleep(10);
- return;
+ $this->output( "Slave is too lagged, aborting\n" );
+ $dbw->commit( __METHOD__ );
+ sleep(10);
+ return;
}*/
$latest = $db->selectField( 'page', 'page_latest', array( 'page_id' => $pageID ), __METHOD__ );
$max = $db->selectField( 'revision', 'MAX(rev_id)', false, __METHOD__ );
}
$this->identifier = $this->getOption( 'identifier', wfWikiID() );
$this->compress = $this->getOption( 'compress', 'yes' ) !== 'no';
- $this->skipRedirects = $this->getOption( 'skip-redirects', false ) !== false ;
+ $this->skipRedirects = $this->getOption( 'skip-redirects', false ) !== false;
$this->dbr = wfGetDB( DB_SLAVE );
$this->generateNamespaces();
$this->timestamp = wfTimestamp( TS_ISO_8601, wfTimestampNow() );
wfMkdirParents( $fspath, null, __METHOD__ ) or die( "Can not create directory $fspath.\n" );
}
- return realpath( $fspath ) . DIRECTORY_SEPARATOR ;
+ return realpath( $fspath ) . DIRECTORY_SEPARATOR;
}
/**
)
);
- foreach ( $res as $row )
+ foreach ( $res as $row ) {
$this->namespaces[] = $row->page_namespace;
+ }
}
/**
if ( $wgContLang->hasVariants() ) {
$variants = $wgContLang->getVariants();
foreach ( $variants as $vCode ) {
- if ( $vCode == $wgContLang->getCode() ) continue; // we don't want default variant
+ if ( $vCode == $wgContLang->getCode() ) {
+ continue; // we don't want default variant
+ }
$entry = $this->fileEntry( $title->getCanonicalURL( '', $vCode ), $date, $this->priority( $namespace ) );
$length += strlen( $entry );
$this->write( $this->file, $entry );
*/
function open( $file, $flags ) {
$resource = $this->compress ? gzopen( $file, $flags ) : fopen( $file, $flags );
- if( $resource === false ) {
+ if ( $resource === false ) {
wfDebugDieBacktrace( __METHOD__ . " error opening file $file with flags $flags. Check permissions?" );
}
return $resource;
* gzwrite() / fwrite() wrapper
*/
function write( &$handle, $str ) {
- if( $handle === true || $handle === false ) {
+ if ( $handle === true || $handle === false ) {
wfDebugDieBacktrace( __METHOD__ . " was passed a boolean as a file handle.\n" );
}
- if ( $this->compress )
+ if ( $this->compress ) {
gzwrite( $handle, $str );
- else
+ } else {
fwrite( $handle, $str );
+ }
}
/**
* gzclose() / fclose() wrapper
*/
function close( &$handle ) {
- if ( $this->compress )
+ if ( $this->compress ) {
gzclose( $handle );
- else
+ } else {
fclose( $handle );
+ }
}
/**
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." );
+ . "a multi-host db server configuration." );
} else {
$lags = $lb->getLagTimes();
foreach ( $lags as $n => $lag ) {
class BackupReader extends Maintenance {
public $reportingInterval = 100;
public $pageCount = 0;
- public $revCount = 0;
- public $dryRun = false;
- public $uploads = false;
+ public $revCount = 0;
+ public $dryRun = false;
+ public $uploads = false;
public $imageBasePath = false;
- public $nsFilter = false;
+ public $nsFilter = false;
function __construct() {
parent::__construct();
- $gz = in_array('compress.zlib', stream_get_wrappers()) ? 'ok' : '(disabled; requires PHP zlib module)';
- $bz2 = in_array('compress.bzip2', stream_get_wrappers()) ? 'ok' : '(disabled; requires PHP bzip2 module)';
+ $gz = in_array( 'compress.zlib', stream_get_wrappers() ) ? 'ok' : '(disabled; requires PHP zlib module)';
+ $bz2 = in_array( 'compress.bzip2', stream_get_wrappers() ) ? 'ok' : '(disabled; requires PHP bzip2 module)';
$this->mDescription = <<<TEXT
This script reads pages from an XML file as produced from Special:Export or
}
public function execute() {
- if( wfReadOnly() ) {
+ if ( wfReadOnly() ) {
$this->error( "Wiki is in read-only mode; you'll need to disable it for import to work.", true );
}
$this->setNsfilter( explode( '|', $this->getOption( 'namespaces' ) ) );
}
- if( $this->hasArg() ) {
+ if ( $this->hasArg() ) {
$this->importFromFile( $this->getArg() );
} else {
$this->importFromStdin();
function importFromStdin() {
$file = fopen( 'php://stdin', 'rt' );
- if( self::posix_isatty( $file ) ) {
+ if ( self::posix_isatty( $file ) ) {
$this->maybeHelp( true );
}
return $this->importFromHandle( $file );
$source = new ImportStreamSource( $handle );
$importer = new WikiImporter( $source );
- if( $this->hasOption( 'debug' ) ) {
+ if ( $this->hasOption( 'debug' ) ) {
$importer->setDebug( true );
}
if ( $this->hasOption( 'no-updates' ) ) {
}
$idx = strrpos( $n, '.' );
- if ( !$idx ) break;
+ if ( !$idx ) {
+ break;
+ }
$n = substr( $n, 0, $idx );
$maxStrip -= 1;
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 )
+ if ( $real_comment === false ) {
$commentText = $comment;
- else
+ } else {
$commentText = $real_comment;
+ }
/* find user directly from source wiki, through MW's API */
$real_user = getFileUserFromSourceWiki( $options['source-wiki-url'], $base );
$cascade = false;
$restrictions = array();
- foreach( $title->getRestrictionTypes() as $type ) {
+ foreach ( $title->getRestrictionTypes() as $type ) {
$restrictions[$type] = $protectLevel;
}
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" );
+ }
}
} else {
$edits = $counter->edits();
$this->output( "{$edits}\nCounting number of articles..." );
- $good = $counter->articles();
+ $good = $counter->articles();
$this->output( "{$good}\nCounting total pages..." );
$pages = $counter->pages();
InstallerOverrides::getCliInstaller( $siteName, $adminName, $this->mOptions );
$status = $installer->doEnvironmentChecks();
- if( $status->isGood() ) {
+ if ( $status->isGood() ) {
$installer->showMessage( 'config-env-good' );
} else {
$installer->showStatusMessage( $status );
return;
}
- if( !$this->hasOption( 'env-checks' ) ) {
+ if ( !$this->hasOption( 'env-checks' ) ) {
$installer->execute();
$installer->writeConfigurationFile( $this->getOption( 'confpath', $IP ) );
}
<?php
-if ( !defined( 'MEDIAWIKI' ) ) die();
+if ( !defined( 'MEDIAWIKI' ) ) {
+ die();
+}
/**
* Statistic output classes.
*
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 'English (en) is excluded because it is the default localization';
- if( is_array( $wgDummyLanguageCodes ) ) {
+ if ( is_array( $wgDummyLanguageCodes ) ) {
$dummyCodes = array();
- foreach( $wgDummyLanguageCodes as $dummyCode => $correctCode ) {
+ foreach ( $wgDummyLanguageCodes as $dummyCode => $correctCode ) {
$dummyCodes[] = Language::fetchLanguageName( $dummyCode ) . ' (' . $dummyCode . ')';
}
echo ', as well as the following languages that are not intended for system message translations, usually because they redirect to other language codes: ' . implode( ', ', $dummyCodes );
# Weigh reverse with factor 20 so coloring takes effect more quickly as
# this option is used solely for reporting 'bad' percentages.
$v = $v * 20;
- if ( $v > 255 ) $v = 255;
+ if ( $v > 255 ) {
+ $v = 255;
+ }
$v = 255 - $v;
}
if ( $v < 128 ) {
}
include( $messagesFile );
$messageExist = isset( $messages );
- if ( $messageExist )
+ if ( $messageExist ) {
$wgMessages[$langCode] = $messages;
+ }
include( $messagesFileC );
$messageCExist = isset( $messages );
- if ( $messageCExist )
+ if ( $messageCExist ) {
$wgMessages[$langCodeC] = $messages;
+ }
$count = 0;
if ( ( $messageExist ) && ( $messageCExist ) ) {
}
}
} 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";
+ }
}
}
echo "[messages are hidden]\n";
} else {
foreach ( $messages as $key => $value ) {
- if( !in_array( $check, $this->nonMessageChecks() ) ) {
+ if ( !in_array( $check, $this->nonMessageChecks() ) ) {
$key = $this->formatKey( $key, $code );
}
if ( $this->level == 2 || empty( $value ) ) {
$problems = 0;
$detailTextForLangChecks = array();
foreach ( $results as $check => $messages ) {
- if( in_array( $check, $this->nonMessageChecks() ) ) {
+ if ( in_array( $check, $this->nonMessageChecks() ) ) {
continue;
}
$count = count( $messages );
* @return bool True if there are any results, false if not.
*/
protected function isEmpty() {
- foreach( $this->results as $results ) {
- foreach( $results as $messages ) {
- if( !empty( $messages ) ) {
+ foreach ( $this->results as $results ) {
+ foreach ( $results as $messages ) {
+ if ( !empty( $messages ) ) {
return false;
}
}
* @throws MWException
*/
protected function checkLanguage( $code ) {
- foreach( $this->extensions as $extension ) {
+ foreach ( $this->extensions as $extension ) {
$this->L = $extension;
$this->results = array();
$this->results[$code] = parent::checkLanguage( $code );
- if( !$this->isEmpty() ) {
+ if ( !$this->isEmpty() ) {
echo $extension->name() . ":\n";
- if( $this->level > 0 ) {
+ if ( $this->level > 0 ) {
switch( $this->output ) {
case 'plain':
$this->outputText();
}
public function execute() {
- if ( !function_exists( 'memory_get_usage' ) )
+ if ( !function_exists( 'memory_get_usage' ) ) {
$this->error( "You must compile PHP with --enable-memory-limit", true );
+ }
$langtool = new languages();
$memlast = $memstart = memory_get_usage();
'javascripttest-pagetext-noframework',
'javascripttest-pagetext-unknownframework',
'javascripttest-pagetext-frameworks',
- 'javascripttest-pagetext-skins' ,
+ 'javascripttest-pagetext-skins',
'javascripttest-qunit-name',
'javascripttest-qunit-intro',
'javascripttest-qunit-heading',
'exif-lightsource-255',
),
'exif-flash' => array(
- 'exif-flash-fired-0' ,
- 'exif-flash-fired-1' ,
- 'exif-flash-return-0' ,
- 'exif-flash-return-2' ,
- 'exif-flash-return-3' ,
- 'exif-flash-mode-1' ,
- 'exif-flash-mode-2' ,
- 'exif-flash-mode-3' ,
- 'exif-flash-function-1' ,
- 'exif-flash-redeye-1' ,
+ 'exif-flash-fired-0',
+ 'exif-flash-fired-1',
+ 'exif-flash-return-0',
+ 'exif-flash-return-2',
+ 'exif-flash-return-3',
+ 'exif-flash-mode-1',
+ 'exif-flash-mode-2',
+ 'exif-flash-mode-3',
+ 'exif-flash-function-1',
+ 'exif-flash-redeye-1',
),
'exif-focalplaneresolutionunit' => array(
'exif-focalplaneresolutionunit-2',
$sortedMessages = $messages[1];
# Write to the file
- if ( $messagesFolder )
+ if ( $messagesFolder ) {
$filename = Language::getFileName( "$messagesFolder/Messages", $code );
- else
+ } else {
$filename = Language::getMessagesFileName( $code );
+ }
- if ( file_exists( $filename ) )
+ if ( file_exists( $filename ) ) {
$contents = file_get_contents( $filename );
- else
+ } else {
$contents = '<?php
$messages = array(
);
';
+ }
- if( strpos( $contents, '$messages' ) !== false ) {
+ if ( strpos( $contents, '$messages' ) !== false ) {
$contents = explode( '$messages', $contents );
- if( $messagesText == '$messages' . $contents[1] ) {
+ if ( $messagesText == '$messages' . $contents[1] ) {
echo "Generated messages for language $code. Same as the current file.\n";
} else {
- if( $write ) {
+ if ( $write ) {
$new = $contents[0];
$new .= $messagesText;
file_put_contents( $filename, $new );
echo "Generated messages for language $code. Please run the script again (without the parameter \"dry-run\") to write the array to the file.\n";
}
}
- if( $listUnknown && isset( $sortedMessages['unknown'] ) && !empty( $sortedMessages['unknown'] ) ) {
- if ( $removeUnknown )
+ if ( $listUnknown && isset( $sortedMessages['unknown'] ) && !empty( $sortedMessages['unknown'] ) ) {
+ if ( $removeUnknown ) {
echo "\nThe following " . count( $sortedMessages['unknown'] ) . " unknown messages have been removed:\n";
- else
+ } else {
echo "\nThere are " . count( $sortedMessages['unknown'] ) . " unknown messages, please check them:\n";
- foreach( $sortedMessages['unknown'] as $key => $value ) {
+ }
+ foreach ( $sortedMessages['unknown'] as $key => $value ) {
echo "* " . $key . "\n";
}
}
# Sort messages to blocks
$sortedMessages['unknown'] = $messages;
- foreach( self::$messageStructure as $blockName => $block ) {
+ foreach ( self::$messageStructure as $blockName => $block ) {
/**
* @var $block array
*/
- foreach( $block as $key ) {
- if( array_key_exists( $key, $sortedMessages['unknown'] ) ) {
+ foreach ( $block as $key ) {
+ if ( array_key_exists( $key, $sortedMessages['unknown'] ) ) {
$sortedMessages[$blockName][$key] = $sortedMessages['unknown'][$key];
unset( $sortedMessages['unknown'][$key] );
}
# Write all the messages
$messagesText = "\$messages = array(
";
- foreach( $sortedMessages as $block => $messages ) {
+ foreach ( $sortedMessages as $block => $messages ) {
# Skip if it's the block of unknown messages - handle that in the end of file
- if( $block == 'unknown' ) {
+ if ( $block == 'unknown' ) {
continue;
}
- if( $ignoredComments ) {
+ if ( $ignoredComments ) {
$ignored = self::$ignoredMessages;
$optional = self::$optionalMessages;
} else {
$commentArray = array();
# List of keys only
- foreach( $messages as $key ) {
- if( in_array( $key, $ignored ) ) {
+ foreach ( $messages as $key ) {
+ if ( in_array( $key, $ignored ) ) {
$commentArray[$key] = ' # ' . self::$ignoredComment;
- } elseif( in_array( $key, $optional ) ) {
+ } elseif ( in_array( $key, $optional ) ) {
$commentArray[$key] = ' # ' . self::$optionalComment;
}
}
$blockText = '';
# Skip the block if it includes no messages
- if( empty( $messages ) ) {
+ if ( empty( $messages ) ) {
return '';
}
# Format the block comment (if exists); check for multiple lines comments
- if( !empty( $blockComment ) ) {
- if( strpos( $blockComment, "\n" ) === false ) {
+ if ( !empty( $blockComment ) ) {
+ if ( strpos( $blockComment, "\n" ) === false ) {
$blockText .= "$prefix# $blockComment
";
} else {
$maxKeyLength = max( array_map( 'strlen', array_keys( $messages ) ) );
# Format the messages
- foreach( $messages as $key => $value ) {
+ foreach ( $messages as $key => $value ) {
# Add the key name
$blockText .= "$prefix'$key'";
$single = "'";
$double = '"';
- if( strpos( $value, $single ) === false ) {
+ if ( strpos( $value, $single ) === false ) {
# Nothing ugly, just use '
$blockText .= $single . $value . $single;
- } elseif( strpos( $value, $double ) === false && !preg_match('/\$[a-zA-Z_\x7f-\xff]/', $value) ) {
+ } elseif ( strpos( $value, $double ) === false && !preg_match( '/\$[a-zA-Z_\x7f-\xff]/', $value ) ) {
# No "-quotes, no variables that need quoting, use "
$blockText .= $double . $value . $double;
} else {
# Something needs quoting, pick the quote which causes less quoting
$quote = substr_count( $value, $double ) + substr_count( $value, '$' ) >= substr_count( $value, $single ) ? $single : $double;
- if( $quote === $double ) {
+ if ( $quote === $double ) {
$extra = '$';
} else {
$extra = '';
$blockText .= ',';
# Add comments, if there is any
- if( array_key_exists( $key, $messageComments ) ) {
+ if ( array_key_exists( $key, $messageComments ) ) {
$blockText .= $messageComments[$key];
}
$servers = $wgObjectCaches[$cache]['servers'];
} elseif ( $wgMainCacheType === CACHE_MEMCACHED ) {
$mcc->set_servers( $wgMemCachedServers );
-} elseif( isset( $wgObjectCaches[$wgMainCacheType]['servers'] ) ) {
+} elseif ( isset( $wgObjectCaches[$wgMainCacheType]['servers'] ) ) {
$mcc->set_servers( $wgObjectCaches[$wgMainCacheType]['servers'] );
} else {
print "MediaWiki isn't configured for Memcached usage\n";
$quit = false;
$line = Maintenance::readconsole();
- if ( $line === false ) exit;
+ if ( $line === false ) {
+ exit;
+ }
$args = explode( ' ', $line );
$command = array_shift( $args );
public function __construct() {
parent::__construct();
$this->mDescription = "Makes several 'set', 'incr' and 'get' requests on every"
- . " memcached server and shows a report";
+ . " memcached server and shows a report";
$this->addOption( 'i', 'Number of iterations', false, true );
$this->addOption( 'cache', 'Use servers from this $wgObjectCaches store', false, true );
$this->addArg( 'server[:port]', 'Memcached server to test, with optional port', false );
$servers = array( $this->getArg() );
} elseif ( $wgMainCacheType === CACHE_MEMCACHED ) {
global $wgMemCachedServers;
- $servers = $wgMemCachedServers ;
+ $servers = $wgMemCachedServers;
} elseif ( isset( $wgObjectCaches[$wgMainCacheType]['servers'] ) ) {
$servers = $wgObjectCaches[$wgMainCacheType]['servers'];
} else {
if ( $this->hasOption( 'extensions-dir' ) ) {
$extdir = $this->getOption( 'extensions-dir' );
$entries = scandir( $extdir );
- foreach( $entries as $extname ) {
+ foreach ( $entries as $extname ) {
if ( $extname == '.' || $extname == '..' || !is_dir( "$extdir/$extname" ) ) {
continue;
}
$doxygenInputFilter = "php {$mwPath}maintenance/mwdoc-filter.php";
/** where Phpdoc should output documentation */
-$doxyOutput = $mwPath . 'docs' . DIRECTORY_SEPARATOR ;
+$doxyOutput = $mwPath . 'docs' . DIRECTORY_SEPARATOR;
$doxyVersion = 'master';
// Replace template placeholders by correct values.
$replacements = array(
'{{OUTPUT_DIRECTORY}}' => $outputDirectory,
- '{{STRIP_FROM_PATH}}' => $stripFromPath,
- '{{CURRENT_VERSION}}' => $currentVersion,
- '{{INPUT}}' => $input,
- '{{EXCLUDE}}' => $exclude,
+ '{{STRIP_FROM_PATH}}' => $stripFromPath,
+ '{{CURRENT_VERSION}}' => $currentVersion,
+ '{{INPUT}}' => $input,
+ '{{EXCLUDE}}' => $exclude,
'{{EXCLUDE_PATTERNS}}' => $excludePatterns,
- '{{HAVE_DOT}}' => `which dot` ? 'YES' : 'NO',
- '{{GENERATE_MAN}}' => $doxyGenerateMan ? 'YES' : 'NO',
- '{{INPUT_FILTER}}' => $doxygenInputFilter,
+ '{{HAVE_DOT}}' => `which dot` ? 'YES' : 'NO',
+ '{{GENERATE_MAN}}' => $doxyGenerateMan ? 'YES' : 'NO',
+ '{{INPUT_FILTER}}' => $doxygenInputFilter,
);
$tmpCfg = str_replace( array_keys( $replacements ), array_values( $replacements ), $template );
$tmpFileName = tempnam( wfTempDir(), 'mwdocgen-' );
if ( is_array( $argv ) ) {
for ($i = 0; $i < count($argv); $i++ ) {
switch( $argv[$i] ) {
- case '--all': $input = 0; break;
- case '--includes': $input = 1; break;
- case '--languages': $input = 2; break;
- case '--maintenance': $input = 3; break;
- case '--skins': $input = 4; break;
+ case '--all':
+ $input = 0;
+ break;
+ case '--includes':
+ $input = 1;
+ break;
+ case '--languages':
+ $input = 2;
+ break;
+ case '--maintenance':
+ $input = 3;
+ break;
+ case '--skins':
+ $input = 4;
+ break;
case '--file':
$input = 5;
$i++;
$file = $argv[$i];
}
break;
- case '--no-extensions': $input = 6; break;
+ case '--no-extensions':
+ $input = 6;
+ break;
case '--output':
$i++;
if ( isset( $argv[$i] ) ) {
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 == '' ) {
$input = 0;
}
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 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 ) ) {
$file = readaline( "Enter file name $mwPath" );
* @return array
*/
private function getConflicts( $ns, $name ) {
- $page = 'page';
+ $page = 'page';
$table = $this->db->tableName( $page );
- $prefix = $this->db->strencode( $name );
+ $prefix = $this->db->strencode( $name );
$encNamespace = $this->db->addQuotes( $ns );
$titleSql = "TRIM(LEADING '$prefix:' FROM {$page}_title)";
$this->db->update( $table,
array(
"{$prefix}_namespace" => $newTitle->getNamespace(),
- "{$prefix}_title" => $newTitle->getDBkey(),
+ "{$prefix}_title" => $newTitle->getDBkey(),
),
array(
// "{$prefix}_namespace" => 0,
- // "{$prefix}_title" => $row->oldtitle,
- "{$prefix}_id" => $row->id,
+ // "{$prefix}_title" => $row->oldtitle,
+ "{$prefix}_id" => $row->id,
),
__METHOD__ );
$this->output( "ok.\n" );
foreach ( $res as $row ) {
// echo "$ns_name:".$row->page_title, "\n";
$title = Title::makeTitle( $ns, $row->page_title );
- $id = $title->getArticleID();
+ $id = $title->getArticleID();
// Get corresponding revisions
$res2 = $dbw->query( "SELECT rev_id FROM $tbl_rev WHERE rev_page = $id" );
$n_deleted ++;
}
} else {
- $this->output( "skip: " . $title->getPrefixedText() . "\n" );
+ $this->output( "skip: " . $title->getPrefixedText() . "\n" );
}
}
$dbw->commit( __METHOD__ );
$this->output( "Searching for \"$name\"..." );
$title = Title::newFromText( $name );
if ( $title ) {
- $id = $title->getArticleID();
+ $id = $title->getArticleID();
$real = $title->getPrefixedText();
$isGoodArticle = $title->isContentPage();
$this->output( "found \"$real\" with ID $id.\n" );
if ( $wgSharedPrefix != null ) {
$ltable = preg_replace( "/^$wgSharedPrefix(.*)/i", "$wgDBprefix\\1", $stable );
} else {
- $ltable = "{$wgDBprefix}{$stable}" ;
+ $ltable = "{$wgDBprefix}{$stable}";
}
$result = $dbw->query( "SELECT uc.constraint_name, uc.table_name, ucc.column_name, uccpk.table_name pk_table_name, uccpk.column_name pk_column_name, uc.delete_rule, uc.deferrable, uc.deferred
*/
private function checkSeparation( $fix ) {
$dbw = wfGetDB( DB_MASTER );
- $page = $dbw->tableName( 'page' );
+ $page = $dbw->tableName( 'page' );
$revision = $dbw->tableName( 'revision' );
if ( $fix ) {
'revision',
'rev_id',
array(
- 'rev_page' => $row->page_id,
+ 'rev_page' => $row->page_id,
'rev_timestamp' => $row2->max_timestamp ) );
$this->output( "... updating to revision $maxId\n" );
$maxRev = Revision::newFromId( $maxId );
*/
protected function Wikitext() {
- $php_stdin = 'php://stdin';
+ $php_stdin = 'php://stdin';
$input_file = $this->getArg( 0, $php_stdin );
- if( $input_file === $php_stdin ) {
+ if ( $input_file === $php_stdin ) {
$ctrl = wfIsWindows() ? 'CTRL+Z' : 'CTRL+D';
$this->error( basename(__FILE__) . ": warning: reading wikitext from STDIN. Press $ctrl to parse.\n" );
}
$title =
$this->getOption( 'title' )
? $this->getOption( 'title' )
- : 'CLIParser' ;
+ : 'CLIParser';
return Title::newFromText( $title );
}
}
$done += $i;
- if( $i !== $batchSize ) {
+ if ( $i !== $batchSize ) {
break;
}
$this->output( sprintf(
"id %d done (up to %d), %5.3f%% \r", $lastId, $endId, $lastId / $endId * 100 ) );
wfWaitForSlaves();
- } while( true );
+ } while ( true );
$processingTime = microtime( true ) - $startTime;
$this->output( sprintf( "\nDone %d files in %.1f seconds\n", $done, $processingTime ) );
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?
+ 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 ) {
$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] ) )
+ if ( !isset( self::$tableMap[$prefix] ) ) {
continue; // bad row?
+ }
$table = self::$tableMap[$prefix];
$userField = $prefix . '_user';
$userTextField = $prefix . '_user_text';
array( $field => $items )
);
foreach ( $sres as $srow ) {
- if ( $srow->$userField > 0 )
+ if ( $srow->$userField > 0 ) {
$userIds[] = intval( $srow->$userField );
- elseif ( $srow->$userTextField != '' )
+ } elseif ( $srow->$userTextField != '' ) {
$userIPs[] = $srow->$userTextField;
+ }
}
// Add item author relations...
$log->addRelations( 'target_author_id', $userIds, $row->log_id );
} elseif ( 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...
array( 'log_id' => $items )
);
foreach ( $sres as $srow ) {
- if ( $srow->log_user > 0 )
+ if ( $srow->log_user > 0 ) {
$userIds[] = intval( $srow->log_user );
- elseif ( IP::isIPAddress( $srow->log_user_text ) )
+ } elseif ( IP::isIPAddress( $srow->log_user_text ) ) {
$userIPs[] = $srow->log_user_text;
+ }
}
$log->addRelations( 'target_author_id', $userIds, $row->log_id );
$log->addRelations( 'target_author_ip', $userIPs, $row->log_id );
}
}
$previousID = intval( $previousID );
- if ( $previousID != $row->rev_parent_id )
+ if ( $previousID != $row->rev_parent_id ) {
$changed++;
+ }
# Update the row...
$db->update( 'revision',
array( 'rev_parent_id' => $previousID ),
$fields = Revision::selectFields();
while ( $blockStart <= $end ) {
$this->output( "...doing rev_id from $blockStart to $blockEnd\n" );
- $res = $db->select( 'revision',
- $fields,
- array( "rev_id >= $blockStart",
- "rev_id <= $blockEnd",
- "rev_len IS NULL" ),
- __METHOD__ );
+ $res = $db->select(
+ 'revision',
+ $fields,
+ array(
+ "rev_id >= $blockStart",
+ "rev_id <= $blockEnd",
+ "rev_len IS NULL"
+ ),
+ __METHOD__
+ );
# Go through and update rev_len from these rows.
foreach ( $res as $row ) {
$rev = new Revision( $row );
try {
$this->mPreprocessor->preprocessToObj( strval( $content->getNativeData() ), 0 );
- }
- catch(Exception $e) {
- $this->error("Caught exception " . $e->getMessage() . " in " . $rev->getTitle()->getPrefixedText() );
+ } catch ( Exception $e ) {
+ $this->error( "Caught exception " . $e->getMessage() . " in " . $rev->getTitle()->getPrefixedText() );
}
}
}
public $hairs = array(
'[[', ']]', '{{', '{{', '}}', '}}', '{{{', '}}}',
'<', '>', '<nowiki', '<gallery', '</nowiki>', '</gallery>', '<nOwIkI>', '</NoWiKi>',
- '<!--' , '-->',
+ '<!--', '-->',
"\n==", "==\n",
'|', '=', "\n", ' ', "\t", "\x7f",
'~~', '~~~', '~~~~', 'subst:',
}
$restrictions = array();
- foreach( $t->getRestrictionTypes() as $type ) {
+ foreach ( $t->getRestrictionTypes() as $type ) {
$restrictions[$type] = $protection;
}
* @ingroup Maintenance
*/
-if( PHP_SAPI != 'cli' ) {
+if ( PHP_SAPI != 'cli' ) {
die( 1 );
}
$ip = $argv[1];
$port = $argv[2];
$url = $argv[3];
- $host = trim(`hostname`);
+ $host = trim( `hostname` );
$output = "Connecting to $ip:$port, target $url, this hostname $host\n";
# Open socket
$conds = array(
'log_namespace' => NS_FILE,
- 'log_type' => $logType,
- 'log_action' => array( 'delete', 'revision' )
+ 'log_type' => $logType,
+ 'log_action' => array( 'delete', 'revision' )
);
$start = $this->getOption( 'starttime' );
if ( $start ) {
if ( $this->hasOption( 'all' ) ) {
$this->purgeNamespace( false );
} elseif ( $this->hasOption( 'namespace' ) ) {
- $this->purgeNamespace( intval( $this->getOption( 'namespace') ) );
+ $this->purgeNamespace( intval( $this->getOption( 'namespace' ) ) );
} else {
$this->doPurge();
}
}
} else {
if ( $this->hasOption( 'verbose' ) ) {
- $this->output( implode( "\n", $urls ) . "\n" );
+ $this->output( implode( "\n", $urls ) . "\n" );
}
$u = new SquidUpdate( $urls );
$u->doUpdate();
if ( $this->hasArg( 0 ) && $this->hasArg( 1 ) ) {
# Set up the users involved
$from = $this->initialiseUser( $this->getArg( 0 ) );
- $to = $this->initialiseUser( $this->getArg( 1 ) );
+ $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' ) ) {
$this->output( "Done!\n" );
// Remove these to be safe
- if ( isset( $wgTitle ) )
+ if ( isset( $wgTitle ) ) {
unset( $wgTitle );
+ }
}
}
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" );
}
}
# Fill in the rc_last_oldid field, which points to the previous edit
$sql = "SELECT rc_cur_id,rc_this_oldid,rc_timestamp FROM $recentchanges " .
- "ORDER BY rc_cur_id,rc_timestamp";
+ "ORDER BY rc_cur_id,rc_timestamp";
$res = $dbw->query( $sql, DB_MASTER );
$lastCurId = 0;
$dbw->update( 'recentchanges',
array(
'rc_last_oldid' => $lastOldId,
- 'rc_new' => $new,
- 'rc_type' => $new,
- 'rc_old_len' => $lastSize,
- 'rc_new_len' => $size,
+ 'rc_new' => $new,
+ 'rc_type' => $new,
+ 'rc_old_len' => $lastSize,
+ 'rc_new_len' => $size,
), array(
- 'rc_cur_id' => $lastCurId,
+ 'rc_cur_id' => $lastCurId,
'rc_this_oldid' => $obj->rc_this_oldid,
),
__METHOD__
$searchindex = $this->db->tableName( 'searchindex' );
$this->output( "\nRebuild the index...\n" );
$sql = "ALTER TABLE $searchindex ADD FULLTEXT si_title (si_title), " .
- "ADD FULLTEXT si_text (si_text)";
+ "ADD FULLTEXT si_text (si_text)";
$this->db->query( $sql, __METHOD__ );
}
}
$conds2 = array( 'img_name > ' . $dbw->addQuotes( $row->img_name ) );
wfWaitForSlaves();
- } while( $res->numRows() === $this->mBatchSize );
+ } while ( $res->numRows() === $this->mBatchSize );
$total = $upgraded + $leftAlone;
if ( $force ) {
$like = $this->getOption( 'metadata-contains', false );
if ( $end !== false ) {
- $conds[] = 'img_name <= ' . $dbw->addQuotes( $end ) ;
+ $conds[] = 'img_name <= ' . $dbw->addQuotes( $end );
}
if ( $mime !== false ) {
list( $major, $minor ) = File::splitMime( $mime );
$this->output( "Retrieving illegal entries from $table... " );
// 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 ),
- __METHOD__,
- 'DISTINCT',
- array( 'page' => array( 'LEFT JOIN', "$field=page_id" ) )
+ $results = $dbr->select(
+ array( $table, 'page' ),
+ $field,
+ array( 'page_id' => null ),
+ __METHOD__,
+ 'DISTINCT',
+ array( 'page' => array( 'LEFT JOIN', "$field=page_id" ) )
);
$counter = 0;
$delta = microtime( true ) - $this->startTime;
$this->error( "Rendered {$this->count} pages in " . round($delta, 2) . " seconds " );
- if ($delta > 0)
+ if ( $delta > 0 ) {
$this->error( round($this->count / $delta, 2) . " pages/sec" );
+ }
$this->error( "\n" );
}
}
public function execute() {
- if ( !$this->hasArg() )
+ if ( !$this->hasArg() ) {
$this->error( "No query specified. Specify the query as a command line parameter.", true );
+ }
$query = $this->getArg();
$n = 1;
$group = JobQueueGroup::singleton();
if ( $this->hasOption( 'group' ) ) {
foreach ( $group->getQueueTypes() as $type ) {
- $queue = $group->get( $type );
+ $queue = $group->get( $type );
$pending = $queue->getSize();
$claimed = $queue->getAcquiredCount();
$abandoned = $queue->getAbandonedCount();
$max_length_value = $max_length_desc = 0;
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
$wholeLine = '';
$newPrompt = '> ';
- $prompt = $newPrompt;
+ $prompt = $newPrompt;
while ( ( $line = Maintenance::readconsole( $prompt ) ) !== false ) {
- if( !$line ) {
+ if ( !$line ) {
# User simply pressed return key
continue;
}
try{
$res = $dbw->query( $wholeLine );
$this->sqlPrintResult( $res, $dbw );
- $prompt = $newPrompt;
+ $prompt = $newPrompt;
$wholeLine = '';
- } catch (DBQueryError $e) {
+ } catch ( DBQueryError $e ) {
$doDie = ! Maintenance::posix_isatty( 0 );
$this->error( $e, $doDie );
}
$tables = $db->query( "SELECT name FROM sqlite_master WHERE type='table'", __METHOD__ );
foreach ( $tables as $table ) {
- if ( strpos( $table->name, 'sqlite_' ) === 0 ) continue;
+ if ( strpos( $table->name, 'sqlite_' ) === 0 ) {
+ continue;
+ }
$columns = $db->query( "PRAGMA table_info({$table->name})", __METHOD__ );
foreach ( $columns as $col ) {
$db->close();
return true;
}
- };
+};
'fixable' => array(),
);
- for ( $chunkStart = 1 ; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
+ for ( $chunkStart = 1; $chunkStart < $maxRevId; $chunkStart += $chunkSize ) {
$chunkEnd = $chunkStart + $chunkSize - 1;
// print "$chunkStart of $maxRevId\n";
do {
$res = $dbw->select( 'text', array( 'old_id', 'old_flags', 'old_text' ),
"old_id>=$start", __METHOD__, array( 'ORDER BY' => 'old_id', 'LIMIT' => $chunksize, 'FOR UPDATE' ) );
- if( $res->numRows() == 0 ) {
+ if ( $res->numRows() == 0 ) {
break;
}
$last = $start;
}
$start = $last + 1; # Deletion may leave long empty stretches
$this->output( "$start...\n" );
- } while( true );
+ } while ( true );
}
/**
# Move blob objects to External Storage
$stored = $storeObj->store( $extdb, serialize( $chunk ));
if ($stored === false) {
- $this->error( "Unable to store object" );
+ $this->error( "Unable to store object" );
return false;
}
# Store External Storage URLs instead of Stub placeholders
foreach ($stubs as $stub) {
- if ( $stub === false )
+ if ( $stub === false ) {
continue;
+ }
# $stored should provide base path to a BLOB
$url = $stored . "/" . $stub->getHash();
$dbw->update( 'text',
$this->error( "Row not found", true );
}
- $flags = explode( ',', $row->old_flags );
+ $flags = explode( ',', $row->old_flags );
$text = $row->old_text;
if ( in_array( 'external', $flags ) ) {
$this->output( "External $text\n" );
*/
function dispatchToSlave( $slaveId, $args ) {
$args = (array)$args;
- $cmd = implode( ' ', $args );
+ $cmd = implode( ' ', $args );
fwrite( $this->slavePipes[$slaveId], "$cmd\n" );
}
# We can safely delete the file when we're done though.
$start = file_get_contents( 'searchUpdate.pos' );
unlink( 'searchUpdate.pos' );
- } elseif( is_readable( $posFile ) ) {
+ } elseif ( is_readable( $posFile ) ) {
$start = file_get_contents( $posFile );
} else {
$start = wfTimestamp( TS_MW, time() - 86400 );
$page = $dbw->tableName( 'page' );
$sql = "SELECT rc_cur_id FROM $recentchanges
- JOIN $page ON rc_cur_id=page_id AND rc_this_oldid=page_latest
- WHERE rc_type != " . RC_LOG . " AND rc_timestamp BETWEEN '$start' AND '$end'
- ";
+ JOIN $page ON rc_cur_id=page_id AND rc_this_oldid=page_latest
+ WHERE rc_type != " . RC_LOG . " AND rc_timestamp BETWEEN '$start' AND '$end'";
$res = $dbw->query( $sql, __METHOD__ );
$this->updateSearchIndex( $maxLockTime, array( $this, 'searchIndexUpdateCallback' ), $dbw, $res );
}
if ( !$this->hasOption( 'only' ) || $this->getOption( 'only' ) == $queryPage->getName() ) {
- $this->output( sprintf( '%-30s ', $special ) );
+ $this->output( sprintf( '%-30s ', $special ) );
if ( $queryPage->isExpensive() ) {
$t1 = explode( ' ', microtime() );
# Do the query
$count = count( $dupes );
$this->out( "Found $count accounts with duplicate records on " . wfWikiID() . ".\n" );
- $this->trimmed = 0;
+ $this->trimmed = 0;
$this->reassigned = 0;
- $this->failed = 0;
+ $this->failed = 0;
foreach ( $dupes as $name ) {
$this->examine( $name, $doDelete );
}
__METHOD__ );
$firstRow = $this->db->fetchObject( $result );
- $firstId = $firstRow->user_id;
+ $firstId = $firstRow->user_id;
$this->out( "Record that will be used for '$name' is user_id=$firstId\n" );
foreach ( $result as $row ) {
public $mOldValue;
public $mNewValue;
- private $mMode, $mReady ;
+ private $mMode, $mReady;
/** Constructor. Will show usage and exit if script options are not correct */
function __construct( $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 ) ;
+ $list = isset( $opts['list'] );
+ $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 );
$this->mQuick = isset( $opts['nowarn'] );
$this->mQuiet = isset( $opts['quiet'] );
- $this->mDry = isset( $opts['dry'] );
+ $this->mDry = isset( $opts['dry'] );
// Set object properties, specially 'mMode' used by run()
if ( isset( $opts['list'] ) ) {
- $this->mMode = 'LISTER' ;
+ $this->mMode = 'LISTER';
} elseif ( isset( $opts['usage'] ) ) {
- $this->mMode = 'USAGER' ;
- $this->mAnOption = isset( $args[0] ) ? $args[0] : false ;
+ $this->mMode = 'USAGER';
+ $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->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" );
if ( !$this->mDry ) {
$user->saveSettings();
}
- if ( !$this->mQuiet ) { print " OK\n"; }
+ if ( !$this->mQuiet ) {
+ print " OK\n";
+ }
} elseif ( !$this->mQuiet ) {
print "Not changing '$username' using <{$this->mAnOption}> = '$curValue'\n";