25 require_once __DIR__ .
'/../includes/PHPVersionCheck.php';
34 define(
'RUN_MAINTENANCE_IF_MAIN', __DIR__ .
'/doMaintenance.php' );
153 $IP = strval( getenv(
'MW_INSTALL_PATH' ) ) !==
''
154 ? getenv(
'MW_INSTALL_PATH' )
155 : realpath( __DIR__ .
'/..' );
158 register_shutdown_function( [ $this,
'outputChanneled' ],
false );
171 if ( !function_exists(
'debug_backtrace' ) ) {
176 $bt = debug_backtrace();
181 if ( $bt[0][
'class'] !==
'Maintenance' || $bt[0][
'function'] !==
'shouldExecute' ) {
184 $includeFuncs = [
'require_once',
'require',
'include',
'include_once' ];
185 for ( $i = 1; $i <
$count; $i++ ) {
186 if ( !in_array( $bt[$i][
'function'], $includeFuncs ) ) {
197 abstract public function execute();
211 $withArg =
false, $shortName =
false, $multiOccurrence =
false
213 $this->mParams[
$name] = [
214 'desc' => $description,
215 'require' => $required,
216 'withArg' => $withArg,
217 'shortName' => $shortName,
218 'multiOccurrence' => $multiOccurrence
221 if ( $shortName !==
false ) {
222 $this->mShortParamsMap[$shortName] =
$name;
232 return isset( $this->mOptions[
$name] );
247 return $this->mOptions[
$name];
250 $this->mOptions[
$name] = $default;
252 return $this->mOptions[
$name];
262 protected function addArg( $arg, $description, $required =
true ) {
263 $this->mArgList[] = [
265 'desc' => $description,
266 'require' => $required
275 unset( $this->mParams[
$name] );
283 $this->mDescription = $text;
291 protected function hasArg( $argId = 0 ) {
292 return isset( $this->mArgs[$argId] );
301 protected function getArg( $argId = 0, $default = null ) {
302 return $this->
hasArg( $argId ) ? $this->mArgs[$argId] : $default;
310 $this->mBatchSize =
$s;
317 if ( $this->mBatchSize ) {
318 $this->
addOption(
'batch-size',
'Run this many operations ' .
319 'per batch, default: ' . $this->mBatchSize,
false,
true );
320 if ( isset( $this->mParams[
'batch-size'] ) ) {
322 $this->mDependantParameters[
'batch-size'] = $this->mParams[
'batch-size'];
343 return file_get_contents(
'php://stdin' );
345 $f = fopen(
'php://stdin',
'rt' );
349 $input = fgets( $f, $len );
352 return rtrim( $input );
369 if ( $this->mQuiet ) {
372 if ( $channel === null ) {
376 $out = preg_replace(
'/\n\z/',
'',
$out );
387 protected function error( $err, $die = 0 ) {
389 if ( PHP_SAPI ==
'cli' ) {
390 fwrite( STDERR, $err .
"\n" );
394 $die = intval( $die );
407 if ( !$this->atLineStart ) {
409 $this->atLineStart =
true;
422 if ( $msg ===
false ) {
429 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
435 $this->atLineStart =
false;
436 if ( $channel === null ) {
439 $this->atLineStart =
true;
441 $this->lastChannel = $channel;
463 # Generic (non script dependant) options:
465 $this->
addOption(
'help',
'Display this help message',
false,
false,
'h' );
466 $this->
addOption(
'quiet',
'Whether to supress non-error output',
false,
false,
'q' );
467 $this->
addOption(
'conf',
'Location of LocalSettings.php, if not default',
false,
true );
468 $this->
addOption(
'wiki',
'For specifying the wiki ID',
false,
true );
469 $this->
addOption(
'globals',
'Output globals at the end of processing for debugging' );
472 'Set a specific memory limit for the script, '
473 .
'"max" for no limit or "default" to avoid changing it'
475 $this->
addOption(
'server',
"The protocol and server name to use in URLs, e.g. " .
476 "http://en.wikipedia.org. This is sometimes necessary because " .
477 "server name detection may fail in command line scripts.",
false,
true );
478 $this->
addOption(
'profiler',
'Profiler output format (usually "text")',
false,
true );
480 # Save generic options to display them separately in help
483 # Script dependant options:
487 $this->
addOption(
'dbuser',
'The DB user to use for this script',
false,
true );
488 $this->
addOption(
'dbpass',
'The password to use for this script',
false,
true );
491 # Save additional script dependant options to display
492 # them separately in help
493 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
501 if ( $this->config === null ) {
526 $this->requiredExtensions[] =
$name;
537 foreach ( $this->requiredExtensions
as $name ) {
538 if ( !$registry->isLoaded( $name ) ) {
544 $joined = implode(
', ', $missing );
545 $msg =
"The following extensions are required to be installed "
546 .
"for this script to run: $joined. Please enable them and then try again.";
547 $this->
error( $msg, 1 );
557 if ( function_exists(
'posix_getpwuid' ) ) {
558 $agent = posix_getpwuid( posix_geteuid() )[
'name'];
564 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
567 mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) .
'...' : $agent
578 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
584 if ( $wgCommandLineMode ) {
591 $lbFactory->getMainLB()->setTransactionListener(
593 function ( $trigger ) {
596 if ( $wgCommandLineMode && $trigger === IDatabase::TRIGGER_COMMIT ) {
614 require_once $classFile;
617 $this->
error(
"Cannot spawn child: $maintClass" );
625 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
626 if ( !is_null( $this->mDb ) ) {
627 $child->setDB( $this->mDb );
639 # Abort if called from a web server
640 if ( isset( $_SERVER ) && isset( $_SERVER[
'REQUEST_METHOD'] ) ) {
641 $this->
error(
'This script must be run from the command line',
true );
644 if ( $IP === null ) {
645 $this->
error(
"\$IP not set, aborting!\n" .
646 '(Did you forget to call parent::__construct() in your maintenance script?)', 1 );
649 # Make sure we can handle script parameters
650 if ( !defined(
'HPHP_VERSION' ) && !ini_get(
'register_argc_argv' ) ) {
651 $this->
error(
'Cannot get command line arguments, register_argc_argv is set to false',
true );
657 if ( ini_get(
'display_errors' ) ) {
658 ini_set(
'display_errors',
'stderr' );
664 # Set the memory limit
665 # Note we need to set it again later in cache LocalSettings changed it
668 # Set max execution time to 0 (no limit). PHP.net says that
669 # "When running PHP from the command line the default setting is 0."
670 # But sometimes this doesn't seem to be the case.
671 ini_set(
'max_execution_time', 0 );
673 $wgRequestTime = microtime(
true );
675 # Define us as being in MediaWiki
676 define(
'MEDIAWIKI',
true );
678 $wgCommandLineMode =
true;
680 # Turn off output buffering if it's on
681 while ( ob_get_level() > 0 ) {
711 if (
$limit !=
'default' ) {
712 ini_set(
'memory_limit',
$limit );
727 if ( is_array( $wgProfiler ) && isset( $wgProfiler[
'class'] ) ) {
728 $class = $wgProfiler[
'class'];
730 $profiler =
new $class(
731 [
'sampling' => 1,
'output' => [
$output ] ]
733 + [
'threshold' => $wgProfileLimit ]
735 $profiler->setTemplated(
true );
740 $trxProfiler->setLogger( LoggerFactory::getInstance(
'DBPerformance' ) );
741 $trxProfiler->setExpectations( $wgTrxProfilerLimits[
'Maintenance'], __METHOD__ );
748 $this->mOptions = [];
750 $this->mInputLoaded =
false;
763 $this->orderedOptions = [];
766 for ( $arg = reset( $argv ); $arg !==
false; $arg = next( $argv ) ) {
767 if ( $arg ==
'--' ) {
768 # End of options, remainder should be considered arguments
769 $arg = next( $argv );
770 while ( $arg !==
false ) {
772 $arg = next( $argv );
775 } elseif ( substr( $arg, 0, 2 ) ==
'--' ) {
777 $option = substr( $arg, 2 );
778 if ( isset( $this->mParams[$option] ) && $this->mParams[$option][
'withArg'] ) {
779 $param = next( $argv );
780 if ( $param ===
false ) {
781 $this->
error(
"\nERROR: $option parameter needs a value after it\n" );
787 $bits = explode(
'=', $option, 2 );
788 if ( count( $bits ) > 1 ) {
797 } elseif ( $arg ==
'-' ) {
798 # Lonely "-", often used to indicate stdin or stdout.
800 } elseif ( substr( $arg, 0, 1 ) ==
'-' ) {
802 $argLength = strlen( $arg );
803 for ( $p = 1; $p < $argLength; $p++ ) {
805 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
806 $option = $this->mShortParamsMap[$option];
809 if ( isset( $this->mParams[$option][
'withArg'] ) && $this->mParams[$option][
'withArg'] ) {
810 $param = next( $argv );
811 if ( $param ===
false ) {
812 $this->
error(
"\nERROR: $option parameter needs a value after it\n" );
826 $this->mArgs =
$args;
828 $this->mInputLoaded =
true;
844 $this->orderedOptions[] = [ $option,
$value ];
846 if ( isset( $this->mParams[$option] ) ) {
847 $multi = $this->mParams[$option][
'multiOccurrence'];
851 $exists = array_key_exists( $option,
$options );
852 if ( $multi && $exists ) {
854 } elseif ( $multi ) {
856 } elseif ( !$exists ) {
859 $this->
error(
"\nERROR: $option parameter given twice\n" );
874 # If we were given opts or args, set those and return early
876 $this->mSelf =
$self;
877 $this->mInputLoaded =
true;
880 $this->mOptions = $opts;
881 $this->mInputLoaded =
true;
884 $this->mArgs =
$args;
885 $this->mInputLoaded =
true;
888 # If we've already loaded input (either by user values or from $argv)
889 # skip on loading it again. The array_shift() will corrupt values if
890 # it's run again and again
891 if ( $this->mInputLoaded ) {
898 $this->mSelf = $argv[0];
907 # Check to make sure we've got all the required options
908 foreach ( $this->mParams
as $opt => $info ) {
909 if ( $info[
'require'] && !$this->
hasOption( $opt ) ) {
910 $this->
error(
"Param $opt required!" );
915 foreach ( $this->mArgList
as $k => $info ) {
916 if ( $info[
'require'] && !$this->
hasArg( $k ) ) {
917 $this->
error(
'Argument <' . $info[
'name'] .
'> required!' );
932 $this->mDbUser = $this->
getOption(
'dbuser' );
935 $this->mDbPass = $this->
getOption(
'dbpass' );
938 $this->mQuiet =
true;
940 if ( $this->
hasOption(
'batch-size' ) ) {
941 $this->mBatchSize = intval( $this->
getOption(
'batch-size' ) );
950 if ( !$force && !$this->
hasOption(
'help' ) ) {
956 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
958 ksort( $this->mParams );
959 $this->mQuiet =
false;
962 if ( $this->mDescription ) {
963 $this->
output(
"\n" . wordwrap( $this->mDescription, $screenWidth ) .
"\n" );
965 $output =
"\nUsage: php " . basename( $this->mSelf );
968 if ( $this->mParams ) {
969 $output .=
" [--" . implode( array_keys( $this->mParams ),
"|--" ) .
"]";
973 if ( $this->mArgList ) {
975 foreach ( $this->mArgList
as $k => $arg ) {
976 if ( $arg[
'require'] ) {
977 $output .=
'<' . $arg[
'name'] .
'>';
979 $output .=
'[' . $arg[
'name'] .
']';
981 if ( $k < count( $this->mArgList ) - 1 ) {
986 $this->
output(
"$output\n\n" );
988 # TODO abstract some repetitive code below
991 $this->
output(
"Generic maintenance parameters:\n" );
992 foreach ( $this->mGenericParameters
as $par => $info ) {
993 if ( $info[
'shortName'] !==
false ) {
994 $par .=
" (-{$info['shortName']})";
997 wordwrap(
"$tab--$par: " . $info[
'desc'], $descWidth,
998 "\n$tab$tab" ) .
"\n"
1004 if ( count( $scriptDependantParams ) > 0 ) {
1005 $this->
output(
"Script dependant parameters:\n" );
1007 foreach ( $scriptDependantParams
as $par => $info ) {
1008 if ( $info[
'shortName'] !==
false ) {
1009 $par .=
" (-{$info['shortName']})";
1012 wordwrap(
"$tab--$par: " . $info[
'desc'], $descWidth,
1013 "\n$tab$tab" ) .
"\n"
1021 $scriptSpecificParams = array_diff_key(
1022 # all script parameters:
1025 $this->mGenericParameters,
1026 $this->mDependantParameters
1028 if ( count( $scriptSpecificParams ) > 0 ) {
1029 $this->
output(
"Script specific parameters:\n" );
1031 foreach ( $scriptSpecificParams
as $par => $info ) {
1032 if ( $info[
'shortName'] !==
false ) {
1033 $par .=
" (-{$info['shortName']})";
1036 wordwrap(
"$tab--$par: " . $info[
'desc'], $descWidth,
1037 "\n$tab$tab" ) .
"\n"
1044 if ( count( $this->mArgList ) > 0 ) {
1045 $this->
output(
"Arguments:\n" );
1047 foreach ( $this->mArgList
as $info ) {
1048 $openChar = $info[
'require'] ?
'<' :
'[';
1049 $closeChar = $info[
'require'] ?
'>' :
']';
1051 wordwrap(
"$tab$openChar" . $info[
'name'] .
"$closeChar: " .
1052 $info[
'desc'], $descWidth,
"\n$tab$tab" ) .
"\n"
1069 # Turn off output buffering again, it might have been turned on in the settings files
1070 if ( ob_get_level() ) {
1074 $wgCommandLineMode =
true;
1076 # Override $wgServer
1078 $wgServer = $this->
getOption(
'server', $wgServer );
1081 # If these were passed, use them
1082 if ( $this->mDbUser ) {
1085 if ( $this->mDbPass ) {
1089 if ( $this->
getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1093 if ( $wgDBservers ) {
1097 foreach ( $wgDBservers
as $i => $server ) {
1102 if ( isset( $wgLBFactoryConf[
'serverTemplate'] ) ) {
1103 $wgLBFactoryConf[
'serverTemplate'][
'user'] =
$wgDBuser;
1104 $wgLBFactoryConf[
'serverTemplate'][
'password'] =
$wgDBpassword;
1106 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1114 $wgShowSQLErrors =
true;
1116 MediaWiki\suppressWarnings();
1117 set_time_limit( 0 );
1118 MediaWiki\restoreWarnings();
1127 if ( defined(
'MW_CMDLINE_CALLBACK' ) ) {
1128 call_user_func( MW_CMDLINE_CALLBACK );
1149 if ( isset( $this->mOptions[
'conf'] ) ) {
1150 $settingsFile = $this->mOptions[
'conf'];
1151 } elseif ( defined(
"MW_CONFIG_FILE" ) ) {
1152 $settingsFile = MW_CONFIG_FILE;
1154 $settingsFile =
"$IP/LocalSettings.php";
1156 if ( isset( $this->mOptions[
'wiki'] ) ) {
1157 $bits = explode(
'-', $this->mOptions[
'wiki'] );
1158 if ( count( $bits ) == 1 ) {
1161 define(
'MW_DB', $bits[0] );
1162 define(
'MW_PREFIX', $bits[1] );
1165 if ( !is_readable( $settingsFile ) ) {
1166 $this->
error(
"A copy of your installation's LocalSettings.php\n" .
1167 "must exist and be readable in the source directory.\n" .
1168 "Use --conf to specify it.",
true );
1170 $wgCommandLineMode =
true;
1172 return $settingsFile;
1181 # Data should come off the master, wrapped in a transaction
1185 # Get "active" text records from the revisions table
1187 $this->
output(
'Searching for active text records in revisions table...' );
1188 $res = $dbw->select(
'revision',
'rev_text_id', [], __METHOD__, [
'DISTINCT' ] );
1189 foreach (
$res as $row ) {
1190 $cur[] = $row->rev_text_id;
1192 $this->
output(
"done.\n" );
1194 # Get "active" text records from the archive table
1195 $this->
output(
'Searching for active text records in archive table...' );
1196 $res = $dbw->select(
'archive',
'ar_text_id', [], __METHOD__, [
'DISTINCT' ] );
1197 foreach (
$res as $row ) {
1198 # old pre-MW 1.5 records can have null ar_text_id's.
1199 if ( $row->ar_text_id !== null ) {
1200 $cur[] = $row->ar_text_id;
1203 $this->
output(
"done.\n" );
1205 # Get the IDs of all text records not in these sets
1206 $this->
output(
'Searching for inactive text records...' );
1207 $cond =
'old_id NOT IN ( ' . $dbw->makeList( $cur ) .
' )';
1208 $res = $dbw->select(
'text',
'old_id', [ $cond ], __METHOD__, [
'DISTINCT' ] );
1210 foreach (
$res as $row ) {
1211 $old[] = $row->old_id;
1213 $this->
output(
"done.\n" );
1215 # Inform the user of what we're going to do
1217 $this->
output(
"$count inactive items found.\n" );
1219 # Delete as appropriate
1220 if ( $delete &&
$count ) {
1221 $this->
output(
'Deleting...' );
1222 $dbw->delete(
'text', [
'old_id' => $old ], __METHOD__ );
1223 $this->
output(
"done.\n" );
1248 protected function getDB( $db, $groups = [], $wiki =
false ) {
1249 if ( is_null( $this->mDb ) ) {
1250 return wfGetDB( $db, $groups, $wiki );
1293 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1295 [
'timeout' => 30,
'ifWritesSince' => $this->lastReplicationWait ]
1297 $this->lastReplicationWait = microtime(
true );
1324 $write = [
'searchindex' ];
1334 $db->lockTables( $read, $write, __CLASS__ .
'::' . __METHOD__ );
1342 $db->unlockTables( __CLASS__ .
'::' . __METHOD__ );
1366 if ( $maxLockTime ) {
1367 $this->
output(
" --- Waiting for lock ---" );
1373 # Loop through the results and do a search update
1374 foreach ( $results
as $row ) {
1375 # Allow reads to be processed
1376 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1377 $this->
output(
" --- Relocking ---" );
1382 call_user_func( $callback, $dbw, $row );
1385 # Unlock searchindex
1386 if ( $maxLockTime ) {
1387 $this->
output(
" --- Unlocking --" );
1404 $titleObj =
$rev->getTitle();
1405 $title = $titleObj->getPrefixedDBkey();
1406 $this->
output(
"$title..." );
1407 # Update searchindex
1408 $u =
new SearchUpdate( $pageId, $titleObj->getText(),
$rev->getContent() );
1425 if ( !function_exists(
'posix_isatty' ) ) {
1438 static $isatty = null;
1439 if ( is_null( $isatty ) ) {
1440 $isatty = self::posix_isatty( 0 );
1443 if ( $isatty && function_exists(
'readline' ) ) {
1444 $resp = readline( $prompt );
1445 if ( $resp === null ) {
1453 $st = self::readlineEmulation( $prompt );
1455 if ( feof( STDIN ) ) {
1458 $st = fgets( STDIN, 1024 );
1461 if ( $st ===
false ) {
1464 $resp = trim( $st );
1480 $command =
"read -er -p $encPrompt && echo \"\$REPLY\"";
1497 if ( feof( STDIN ) ) {
1502 return fgets( STDIN, 1024 );
1510 require_once __DIR__ .
'/../tests/common/TestsAutoLoader.php';
1531 parent::__construct();
1532 $this->
addOption(
'force',
'Run the update even if it was completed already' );
1541 && $db->selectRow(
'updatelog',
'1', [
'ul_key' => $key ], __METHOD__ )
1552 if ( $db->insert(
'updatelog', [
'ul_key' => $key ], __METHOD__,
'IGNORE' ) ) {
1568 return "Update '{$key}' already logged as completed.";
1578 return "Unable to log update '{$key}' as completed.";
#define the
table suitable for use with IDatabase::select()
unlockSearchindex($db)
Unlock the tables.
loadParamsAndArgs($self=null, $opts=null, $args=null)
Process command line arguments $mOptions becomes an array with keys set to the option names $mArgs be...
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
const DB_NONE
Constants for DB access type.
const RUN_MAINTENANCE_IF_MAIN
checkRequiredExtensions()
Verify that the required extensions are installed.
static setLBFactoryTriggers(LBFactory $LBFactory)
setParam(&$options, $option, $value)
Helper function used solely by loadParamsAndArgs to prevent code duplication.
$wgDBadminpassword
Separate password for maintenance tasks.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
addArg($arg, $description, $required=true)
Add some args that are needed.
getDir()
Get the maintenance directory.
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
array $orderedOptions
Used to read the options in the order they were passed.
static instance()
Singleton.
$wgDBpassword
Database user's password.
wfHostname()
Fetch server name for use in error reporting etc.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
getName()
Get the script's name.
doUpdate()
Perform actual update for the entry.
addDefaultParams()
Add the default parameters to the scripts.
finalSetup()
Handle some last-minute setup here.
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
lockSearchindex($db)
Lock the search index.
afterFinalSetup()
Execute a callback function at the end of initialisation.
Database $mDb
Used by getDB() / setDB()
setConfig(Config $config)
getDB($db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
hasOption($name)
Checks to see if a particular param exists.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
$wgDBuser
Database username.
static locateExecutableInDefaultPaths($names, $versionInfo=false)
Same as locateExecutable(), but checks in getPossibleBinPaths() by default.
loadSpecialVars()
Handle the special variables that are global to all scripts.
wfShellExec($cmd, &$retval=null, $environ=[], $limits=[], $options=[])
Execute a shell command, with time and memory limits mirrored from the PHP configuration if supported...
static tryOpportunisticExecute($mode= 'run')
Run all deferred updates immediately if there are no DB writes active.
when a variable name is used in a it is silently declared as a new local masking the global
wfIsWindows()
Check if the operating system is Windows.
static posix_isatty($fd)
Wrapper for posix_isatty() We default as considering stdin a tty (for nice readline methods) but trea...
array $requiredExtensions
getStdin($len=null)
Return input from stdin.
cleanupChanneled()
Clean up channeled output.
static replaceStubInstance(Profiler $profiler)
Replace the current profiler with $profiler if no non-stub profiler is set.
Database independant search index updater.
updatelogFailedMessage()
Message to show that the update log was unable to log the completion of this update.
Fake maintenance wrapper, mostly used for the web installer/updater.
activateProfiler()
Activate the profiler (assuming $wgProfiler is set)
addOption($name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
global $wgCommandLineMode
static requireTestsAutoloader()
Call this to set up the autoloader to allow classes to be used from the tests directory.
Exception class for replica DB wait timeouts.
deleteOption($name)
Remove an option.
doDBUpdates()
Do the actual work.
updateSearchIndex($maxLockTime, $callback, $dbw, $results)
Perform a search index update with locking.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
relockSearchindex($db)
Unlock and lock again Since the lock is low-priority, queued reads will be able to complete...
float $lastReplicationWait
UNIX timestamp.
setup()
Do some sanity checking and basic setup.
setDB(IDatabase $db)
Sets database object to be returned by getDB().
clearParamsAndArgs()
Clear all params and arguments.
hasArg($argId=0)
Does a given argument exist?
$wgDBservers
Database load balancer This is a two-dimensional array, an array of server info structures Fields are...
globals()
Potentially debug globals.
namespace and then decline to actually register it file or subcat img or subcat $title
adjustMemoryLimit()
Adjusts PHP's memory limit to better suit our needs, if needed.
getUpdateKey()
Get the update key name to go in the update log table.
requireExtension($name)
Indicate that the specified extension must be loaded before the script can run.
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
resource $fileHandle
Used when creating separate schema files.
addDescription($text)
Set the description text.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
getOption($name, $default=null)
Get an option, or return the default.
static shouldExecute()
Should we execute the maintenance script, or just allow it to be included as a standalone class...
output($out, $channel=null)
Throw some output to the user.
purgeRedundantText($delete=true)
Support function for cleaning up redundant text records.
begin($fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
static getDefaultInstance()
commit($fname=__METHOD__, $flush= '')
Commits a transaction previously started using begin().
loadWithArgv($argv)
Load params and arguments from a given array of command-line arguments.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
maybeHelp($force=false)
Maybe show the help.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined...
Class for scripts that perform database maintenance and want to log the update in updatelog so we can...
$wgDBadminuser
Separate username for maintenance tasks.
static readconsole($prompt= '> ')
Prompt the console for input.
static readlineEmulation($prompt)
Emulate readline()
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
int $mBatchSize
Batch size.
setAgentAndTriggers()
Set triggers like when to try to run deferred updates.
error($err, $die=0)
Throw an error to the user.
static loadFromPageId($db, $pageid, $id=0)
Load either the current, or a specified, revision that's attached to a given page.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object to manipulate or replace but no entry for that model exists in $wgContentHandlers if desired whether it is OK to use $contentModel on $title Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok inclusive $limit
wfEntryPointCheck($entryPoint)
Check php version and that external dependencies are installed, and display an informative error if e...
updateSearchIndexForPage($dbw, $pageId)
Update the searchindex table for a given pageid.
updateSkippedMessage()
Message to show that the update was done already and was just skipped.
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method.MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances.The"Spi"in MediaWiki\Logger\Spi stands for"service provider interface".An SPI is an API intended to be implemented or extended by a third party.This software design pattern is intended to enable framework extension and replaceable components.It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki.The service provider interface allows the backend logging library to be implemented in multiple ways.The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime.This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance.Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
wfEscapeShellArg()
Version of escapeshellarg() that works better on Windows.
$wgServer
URL of the server.
getArg($argId=0, $default=null)
Get an argument.
$wgLBFactoryConf
Load balancer factory configuration To set up a multi-master wiki farm, set the class here to somethi...
loadSettings()
Generic setup for most installs.
rollback($fname=__METHOD__, $flush= '')
Rollback a transaction previously started using begin().
setBatchSize($s=0)
Set the batch size.
float $wgRequestTime
Request start time as fractional seconds since epoch.
validateParamsAndArgs()
Run some validation checks on the params, etc.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Config $config
Accessible via getConfig()
runChild($maintClass, $classFile=null)
Run a child maintenance script.
outputChanneled($msg, $channel=null)
Message outputter with channeled message support.
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
public function execute()
Basic database interface for live and lazy-loaded relation database handles.
__construct()
Default constructor.
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
Allows to change the fields on the form that will be generated $name