25require_once __DIR__ .
'/../includes/PHPVersionCheck.php';
36define(
'RUN_MAINTENANCE_IF_MAIN', __DIR__ .
'/doMaintenance.php' );
176 $IP = strval( getenv(
'MW_INSTALL_PATH' ) ) !==
''
177 ? getenv(
'MW_INSTALL_PATH' )
178 : realpath( __DIR__ .
'/..' );
181 register_shutdown_function( [ $this,
'outputChanneled' ],
false );
194 if ( !function_exists(
'debug_backtrace' ) ) {
199 $bt = debug_backtrace();
200 $count = count( $bt );
204 if ( $bt[0][
'class'] !== self::class || $bt[0][
'function'] !==
'shouldExecute' ) {
207 $includeFuncs = [
'require_once',
'require',
'include',
'include_once' ];
208 for ( $i = 1; $i < $count; $i++ ) {
209 if ( !in_array( $bt[$i][
'function'], $includeFuncs ) ) {
234 return isset( $this->mParams[
$name] );
248 protected function addOption( $name, $description, $required =
false,
249 $withArg =
false, $shortName =
false, $multiOccurrence =
false
251 $this->mParams[
$name] = [
252 'desc' => $description,
253 'require' => $required,
254 'withArg' => $withArg,
255 'shortName' => $shortName,
256 'multiOccurrence' => $multiOccurrence
259 if ( $shortName !==
false ) {
260 $this->mShortParamsMap[$shortName] =
$name;
270 return isset( $this->mOptions[
$name] );
283 protected function getOption( $name, $default =
null ) {
285 return $this->mOptions[
$name];
288 $this->mOptions[
$name] = $default;
290 return $this->mOptions[
$name];
300 protected function addArg( $arg, $description, $required =
true ) {
301 $this->mArgList[] = [
303 'desc' => $description,
304 'require' => $required
313 unset( $this->mParams[
$name] );
322 $this->mAllowUnregisteredOptions = $allow;
330 $this->mDescription = $text;
338 protected function hasArg( $argId = 0 ) {
339 if ( func_num_args() === 0 ) {
340 wfDeprecated( __METHOD__ .
' without an $argId',
'1.33' );
343 return isset( $this->mArgs[$argId] );
352 protected function getArg( $argId = 0, $default =
null ) {
353 if ( func_num_args() === 0 ) {
354 wfDeprecated( __METHOD__ .
' without an $argId',
'1.33' );
357 return $this->
hasArg( $argId ) ? $this->mArgs[$argId] : $default;
376 $this->mBatchSize =
$s;
383 if ( $this->mBatchSize ) {
384 $this->
addOption(
'batch-size',
'Run this many operations ' .
385 'per batch, default: ' . $this->mBatchSize,
false,
true );
386 if ( isset( $this->mParams[
'batch-size'] ) ) {
388 $this->mDependantParameters[
'batch-size'] = $this->mParams[
'batch-size'];
408 if ( $len == self::STDIN_ALL ) {
409 return file_get_contents(
'php://stdin' );
411 $f = fopen(
'php://stdin',
'rt' );
436 if ( class_exists( MediaWikiServices::class ) ) {
438 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
439 if ( $stats->getDataCount() > 1000 ) {
440 MediaWiki::emitBufferedStatsdData( $stats, $this->
getConfig() );
444 if ( $this->mQuiet ) {
447 if ( $channel ===
null ) {
451 $out = preg_replace(
'/\n\z/',
'',
$out );
462 protected function error( $err, $die = 0 ) {
463 if ( intval( $die ) !== 0 ) {
469 ( PHP_SAPI ==
'cli' || PHP_SAPI ==
'phpdbg' ) &&
470 !defined(
'MW_PHPUNIT_TEST' )
472 fwrite( STDERR, $err .
"\n" );
486 $this->
error( $msg );
497 if ( !$this->atLineStart ) {
499 $this->atLineStart =
true;
512 if ( $msg ===
false ) {
519 if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
525 $this->atLineStart =
false;
526 if ( $channel ===
null ) {
529 $this->atLineStart =
true;
531 $this->lastChannel = $channel;
552 # Generic (non script dependant) options:
554 $this->
addOption(
'help',
'Display this help message',
false,
false,
'h' );
555 $this->
addOption(
'quiet',
'Whether to suppress non-error output',
false,
false,
'q' );
556 $this->
addOption(
'conf',
'Location of LocalSettings.php, if not default',
false,
true );
557 $this->
addOption(
'wiki',
'For specifying the wiki ID',
false,
true );
558 $this->
addOption(
'globals',
'Output globals at the end of processing for debugging' );
561 'Set a specific memory limit for the script, '
562 .
'"max" for no limit or "default" to avoid changing it',
566 $this->
addOption(
'server',
"The protocol and server name to use in URLs, e.g. " .
567 "http://en.wikipedia.org. This is sometimes necessary because " .
568 "server name detection may fail in command line scripts.",
false,
true );
569 $this->
addOption(
'profiler',
'Profiler output format (usually "text")',
false,
true );
571 $this->
addOption(
'mwdebug',
'Enable built-in MediaWiki development settings',
false,
true );
573 # Save generic options to display them separately in help
576 # Script dependant options:
580 $this->
addOption(
'dbuser',
'The DB user to use for this script',
false,
true );
581 $this->
addOption(
'dbpass',
'The password to use for this script',
false,
true );
582 $this->
addOption(
'dbgroupdefault',
'The default DB group to use.',
false,
true );
585 # Save additional script dependant options to display
586 # Â them separately in help
587 $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
595 if ( $this->config ===
null ) {
596 $this->config = MediaWikiServices::getInstance()->getMainConfig();
620 $this->requiredExtensions[] =
$name;
631 foreach ( $this->requiredExtensions
as $name ) {
632 if ( !$registry->isLoaded(
$name ) ) {
638 $joined = implode(
', ', $missing );
639 $msg =
"The following extensions are required to be installed "
640 .
"for this script to run: $joined. Please enable them and then try again.";
650 if ( function_exists(
'posix_getpwuid' ) ) {
651 $agent = posix_getpwuid( posix_geteuid() )[
'name'];
657 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
659 $lbFactory->setAgentName(
660 mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) .
'...' : $agent
671 $services = MediaWikiServices::getInstance();
672 $stats =
$services->getStatsdDataFactory();
674 $lbFactory =
$services->getDBLoadBalancerFactory();
675 $lbFactory->setWaitForReplicationListener(
680 DeferredUpdates::tryOpportunisticExecute(
'run' );
683 MediaWiki::emitBufferedStatsdData( $stats,
$config );
688 $lbFactory->getMainLB()->setTransactionListener(
690 function ( $trigger )
use ( $stats,
$config ) {
692 if (
$config->
get(
'CommandLineMode' ) && $trigger === IDatabase::TRIGGER_COMMIT ) {
693 DeferredUpdates::tryOpportunisticExecute(
'run' );
696 MediaWiki::emitBufferedStatsdData( $stats,
$config );
712 require_once $classFile;
715 $this->
error(
"Cannot spawn child: $maintClass" );
723 $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
724 if ( !is_null( $this->mDb ) ) {
725 $child->setDB( $this->mDb );
737 # Abort if called from a web server
738 # wfIsCLI() is not available yet
739 if ( PHP_SAPI !==
'cli' && PHP_SAPI !==
'phpdbg' ) {
740 $this->
fatalError(
'This script must be run from the command line' );
743 if ( $IP ===
null ) {
744 $this->
fatalError(
"\$IP not set, aborting!\n" .
745 '(Did you forget to call parent::__construct() in your maintenance script?)' );
748 # Make sure we can handle script parameters
749 if ( !defined(
'HPHP_VERSION' ) && !ini_get(
'register_argc_argv' ) ) {
750 $this->
fatalError(
'Cannot get command line arguments, register_argc_argv is set to false' );
756 if ( ini_get(
'display_errors' ) ) {
757 ini_set(
'display_errors',
'stderr' );
762 # Set the memory limit
763 # Note we need to set it again later in cache LocalSettings changed it
766 # Set max execution time to 0 (no limit). PHP.net says that
767 # "When running PHP from the command line the default setting is 0."
768 # But sometimes this doesn't seem to be the case.
769 ini_set(
'max_execution_time', 0 );
771 # Define us as being in MediaWiki
772 define(
'MEDIAWIKI',
true );
776 # Turn off output buffering if it's on
777 while ( ob_get_level() > 0 ) {
792 $limit = $this->
getOption(
'memory-limit',
'max' );
793 $limit = trim( $limit,
"\" '" );
802 if ( $limit ==
'max' ) {
805 if ( $limit !=
'default' ) {
806 ini_set(
'memory_limit', $limit );
824 $profiler =
new $class(
825 [
'sampling' => 1,
'output' => [
$output ] ]
829 $profiler->setTemplated(
true );
830 Profiler::replaceStubInstance( $profiler );
833 $trxProfiler = Profiler::instance()->getTransactionProfiler();
834 $trxProfiler->setLogger( LoggerFactory::getInstance(
'DBPerformance' ) );
842 $this->mOptions = [];
844 $this->mInputLoaded =
false;
857 $this->orderedOptions = [];
860 for ( $arg = reset( $argv ); $arg !==
false; $arg = next( $argv ) ) {
861 if ( $arg ==
'--' ) {
862 # End of options, remainder should be considered arguments
863 $arg = next( $argv );
864 while ( $arg !==
false ) {
866 $arg = next( $argv );
869 } elseif ( substr( $arg, 0, 2 ) ==
'--' ) {
871 $option = substr( $arg, 2 );
872 if ( isset( $this->mParams[$option] ) && $this->mParams[$option][
'withArg'] ) {
873 $param = next( $argv );
874 if ( $param ===
false ) {
875 $this->
error(
"\nERROR: $option parameter needs a value after it\n" );
881 $bits = explode(
'=', $option, 2 );
884 } elseif ( $arg ==
'-' ) {
885 # Lonely "-", often used to indicate stdin or stdout.
887 } elseif ( substr( $arg, 0, 1 ) ==
'-' ) {
889 $argLength = strlen( $arg );
890 for ( $p = 1; $p < $argLength; $p++ ) {
892 if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
893 $option = $this->mShortParamsMap[$option];
896 if ( isset( $this->mParams[$option][
'withArg'] ) && $this->mParams[$option][
'withArg'] ) {
897 $param = next( $argv );
898 if ( $param ===
false ) {
899 $this->
error(
"\nERROR: $option parameter needs a value after it\n" );
913 $this->mArgs =
$args;
915 $this->mInputLoaded =
true;
931 $this->orderedOptions[] = [ $option,
$value ];
933 if ( isset( $this->mParams[$option] ) ) {
934 $multi = $this->mParams[$option][
'multiOccurrence'];
938 $exists = array_key_exists( $option,
$options );
939 if ( $multi && $exists ) {
941 } elseif ( $multi ) {
943 } elseif ( !$exists ) {
946 $this->
error(
"\nERROR: $option parameter given twice\n" );
961 # If we were given opts or args, set those and return early
963 $this->mSelf =
$self;
964 $this->mInputLoaded =
true;
967 $this->mOptions = $opts;
968 $this->mInputLoaded =
true;
971 $this->mArgs =
$args;
972 $this->mInputLoaded =
true;
975 # If we've already loaded input (either by user values or from $argv)
976 # skip on loading it again. The array_shift() will corrupt values if
977 # it's run again and again
978 if ( $this->mInputLoaded ) {
985 $this->mSelf = $argv[0];
994 # Check to make sure we've got all the required options
995 foreach ( $this->mParams
as $opt => $info ) {
997 $this->
error(
"Param $opt required!" );
1001 # Check arg list too
1002 foreach ( $this->mArgList
as $k => $info ) {
1003 if ( $info[
'require'] && !$this->
hasArg( $k ) ) {
1004 $this->
error(
'Argument <' . $info[
'name'] .
'> required!' );
1008 if ( !$this->mAllowUnregisteredOptions ) {
1009 # Check for unexpected options
1010 foreach ( $this->mOptions
as $opt => $val ) {
1012 $this->
error(
"Unexpected option $opt!" );
1026 $this->mDbUser = $this->
getOption(
'dbuser' );
1029 $this->mDbPass = $this->
getOption(
'dbpass' );
1032 $this->mQuiet =
true;
1034 if ( $this->
hasOption(
'batch-size' ) ) {
1035 $this->mBatchSize = intval( $this->
getOption(
'batch-size' ) );
1044 if ( !$force && !$this->
hasOption(
'help' ) ) {
1050 $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1052 ksort( $this->mParams );
1053 $this->mQuiet =
false;
1056 if ( $this->mDescription ) {
1057 $this->
output(
"\n" . wordwrap( $this->mDescription, $screenWidth ) .
"\n" );
1059 $output =
"\nUsage: php " . basename( $this->mSelf );
1062 if ( $this->mParams ) {
1063 $output .=
" [--" . implode(
"|--", array_keys( $this->mParams ) ) .
"]";
1067 if ( $this->mArgList ) {
1069 foreach ( $this->mArgList
as $k => $arg ) {
1070 if ( $arg[
'require'] ) {
1071 $output .=
'<' . $arg[
'name'] .
'>';
1073 $output .=
'[' . $arg[
'name'] .
']';
1075 if ( $k < count( $this->mArgList ) - 1 ) {
1080 $this->
output(
"$output\n\n" );
1082 # TODO abstract some repetitive code below
1085 $this->
output(
"Generic maintenance parameters:\n" );
1086 foreach ( $this->mGenericParameters
as $par => $info ) {
1087 if ( $info[
'shortName'] !==
false ) {
1088 $par .=
" (-{$info['shortName']})";
1091 wordwrap(
"$tab--$par: " . $info[
'desc'], $descWidth,
1092 "\n$tab$tab" ) .
"\n"
1098 if ( count( $scriptDependantParams ) > 0 ) {
1099 $this->
output(
"Script dependant parameters:\n" );
1101 foreach ( $scriptDependantParams
as $par => $info ) {
1102 if ( $info[
'shortName'] !==
false ) {
1103 $par .=
" (-{$info['shortName']})";
1106 wordwrap(
"$tab--$par: " . $info[
'desc'], $descWidth,
1107 "\n$tab$tab" ) .
"\n"
1115 $scriptSpecificParams = array_diff_key(
1116 # all script parameters:
1118 # remove the Maintenance default parameters:
1122 if ( count( $scriptSpecificParams ) > 0 ) {
1123 $this->
output(
"Script specific parameters:\n" );
1125 foreach ( $scriptSpecificParams
as $par => $info ) {
1126 if ( $info[
'shortName'] !==
false ) {
1127 $par .=
" (-{$info['shortName']})";
1130 wordwrap(
"$tab--$par: " . $info[
'desc'], $descWidth,
1131 "\n$tab$tab" ) .
"\n"
1138 if ( count( $this->mArgList ) > 0 ) {
1139 $this->
output(
"Arguments:\n" );
1141 foreach ( $this->mArgList
as $info ) {
1142 $openChar = $info[
'require'] ?
'<' :
'[';
1143 $closeChar = $info[
'require'] ?
'>' :
']';
1145 wordwrap(
"$tab$openChar" . $info[
'name'] .
"$closeChar: " .
1146 $info[
'desc'], $descWidth,
"\n$tab$tab" ) .
"\n"
1163 # Turn off output buffering again, it might have been turned on in the settings files
1164 if ( ob_get_level() ) {
1170 # Override $wgServer
1172 $wgServer = $this->
getOption(
'server', $wgServer );
1175 # If these were passed, use them
1176 if ( $this->mDbUser ) {
1179 if ( $this->mDbPass ) {
1182 if ( $this->
hasOption(
'dbgroupdefault' ) ) {
1183 $wgDBDefaultGroup = $this->
getOption(
'dbgroupdefault',
null );
1185 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1205 MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1208 # Apply debug settings
1210 require __DIR__ .
'/../includes/DevelopmentSettings.php';
1218 $wgShowExceptionDetails =
true;
1221 Wikimedia\suppressWarnings();
1222 set_time_limit( 0 );
1223 Wikimedia\restoreWarnings();
1232 if ( defined(
'MW_CMDLINE_CALLBACK' ) ) {
1233 call_user_func( MW_CMDLINE_CALLBACK );
1254 if ( isset( $this->mOptions[
'conf'] ) ) {
1255 $settingsFile = $this->mOptions[
'conf'];
1256 } elseif ( defined(
"MW_CONFIG_FILE" ) ) {
1257 $settingsFile = MW_CONFIG_FILE;
1259 $settingsFile =
"$IP/LocalSettings.php";
1261 if ( isset( $this->mOptions[
'wiki'] ) ) {
1262 $bits = explode(
'-', $this->mOptions[
'wiki'], 2 );
1263 define(
'MW_DB', $bits[0] );
1264 define(
'MW_PREFIX', $bits[1] ??
'' );
1265 } elseif ( isset( $this->mOptions[
'server'] ) ) {
1270 $_SERVER[
'SERVER_NAME'] = $this->mOptions[
'server'];
1273 if ( !is_readable( $settingsFile ) ) {
1274 $this->
fatalError(
"A copy of your installation's LocalSettings.php\n" .
1275 "must exist and be readable in the source directory.\n" .
1276 "Use --conf to specify it." );
1278 $wgCommandLineMode =
true;
1280 return $settingsFile;
1291 # Data should come off the master, wrapped in a transaction
1296 # Get "active" text records from the revisions table
1298 $this->
output(
'Searching for active text records in revisions table...' );
1299 $res = $dbw->select(
'revision',
'rev_text_id', [], __METHOD__, [
'DISTINCT' ] );
1300 foreach (
$res as $row ) {
1301 $cur[] = $row->rev_text_id;
1303 $this->
output(
"done.\n" );
1305 # Get "active" text records from the archive table
1306 $this->
output(
'Searching for active text records in archive table...' );
1307 $res = $dbw->select(
'archive',
'ar_text_id', [], __METHOD__, [
'DISTINCT' ] );
1308 foreach (
$res as $row ) {
1309 # old pre-MW 1.5 records can have null ar_text_id's.
1310 if ( $row->ar_text_id !==
null ) {
1311 $cur[] = $row->ar_text_id;
1314 $this->
output(
"done.\n" );
1316 # Get "active" text records via the content table
1318 $this->
output(
'Searching for active text records via contents table...' );
1319 $res = $dbw->select(
'content',
'content_address', [], __METHOD__, [
'DISTINCT' ] );
1320 $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1321 foreach (
$res as $row ) {
1322 $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1327 $this->
output(
"done.\n" );
1329 $this->
output(
"done.\n" );
1331 # Get the IDs of all text records not in these sets
1332 $this->
output(
'Searching for inactive text records...' );
1333 $cond =
'old_id NOT IN ( ' . $dbw->makeList( $cur ) .
' )';
1334 $res = $dbw->select(
'text',
'old_id', [ $cond ], __METHOD__, [
'DISTINCT' ] );
1336 foreach (
$res as $row ) {
1337 $old[] = $row->old_id;
1339 $this->
output(
"done.\n" );
1341 # Inform the user of what we're going to do
1342 $count = count( $old );
1343 $this->
output(
"$count inactive items found.\n" );
1345 # Delete as appropriate
1346 if ( $delete && $count ) {
1347 $this->
output(
'Deleting...' );
1348 $dbw->delete(
'text', [
'old_id' => $old ], __METHOD__ );
1349 $this->
output(
"done.\n" );
1373 protected function getDB( $db, $groups = [], $wiki =
false ) {
1374 if ( $this->mDb ===
null ) {
1375 return wfGetDB( $db, $groups, $wiki );
1416 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1417 $waitSucceeded = $lbFactory->waitForReplication(
1418 [
'timeout' => 30,
'ifWritesSince' => $this->lastReplicationWait ]
1420 $this->lastReplicationWait = microtime(
true );
1421 return $waitSucceeded;
1443 $write = [
'searchindex' ];
1453 $db->lockTables( $read, $write, __CLASS__ .
'-searchIndexLock' );
1461 $db->unlockTables( __CLASS__ .
'-searchIndexLock' );
1485 if ( $maxLockTime ) {
1486 $this->
output(
" --- Waiting for lock ---" );
1492 # Loop through the results and do a search update
1493 foreach ( $results
as $row ) {
1494 # Allow reads to be processed
1495 if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1496 $this->
output(
" --- Relocking ---" );
1501 call_user_func( $callback, $dbw, $row );
1504 # Unlock searchindex
1505 if ( $maxLockTime ) {
1506 $this->
output(
" --- Unlocking --" );
1523 $titleObj =
$rev->getTitle();
1524 $title = $titleObj->getPrefixedDBkey();
1525 $this->
output(
"$title..." );
1526 # Update searchindex
1527 $u =
new SearchUpdate( $pageId, $titleObj->getText(),
$rev->getContent() );
1549 for ( $i = $seconds; $i >= 0; $i-- ) {
1550 if ( $i != $seconds ) {
1551 $this->
output( str_repeat(
"\x08", strlen( $i + 1 ) ) );
1570 if ( !function_exists(
'posix_isatty' ) ) {
1583 static $isatty =
null;
1584 if ( is_null( $isatty ) ) {
1588 if ( $isatty && function_exists(
'readline' ) ) {
1589 return readline( $prompt );
1594 if ( feof( STDIN ) ) {
1597 $st = fgets( STDIN, 1024 );
1600 if ( $st ===
false ) {
1603 $resp = trim( $st );
1615 $bash = ExecutableFinder::findInDefaultPaths(
'bash' );
1618 $encPrompt = Shell::escape( $prompt );
1619 $command =
"read -er -p $encPrompt && echo \"\$REPLY\"";
1620 $encCommand = Shell::escape(
$command );
1621 $line = Shell::escape(
"$bash -c $encCommand", $retval, [], [
'walltime' => 0 ] );
1623 if ( $retval == 0 ) {
1625 } elseif ( $retval == 127 ) {
1636 if ( feof( STDIN ) ) {
1641 return fgets( STDIN, 1024 );
1652 $default = [ 80, 50 ];
1656 if ( Shell::isDisabled() ) {
1666 $result = Shell::command(
'stty',
'size' )
1668 if (
$result->getExitCode() !== 0 ) {
1671 if ( !preg_match(
'/^(\d+) (\d+)$/',
$result->getStdout(), $m ) ) {
1674 return [ intval( $m[2] ), intval( $m[1] ) ];
1682 require_once __DIR__ .
'/../tests/common/TestsAutoLoader.php';
1702 parent::__construct();
1703 $this->
addOption(
'force',
'Run the update even if it was completed already' );
1712 && $db->selectRow(
'updatelog',
'1', [
'ul_key' => $key ], __METHOD__ )
1723 $db->insert(
'updatelog', [
'ul_key' => $key ], __METHOD__,
'IGNORE' );
1735 return "Update '{$key}' already logged as completed.";
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgDBuser
Database username.
int $wgMultiContentRevisionSchemaMigrationStage
RevisionStore table schema migration stage (content, slots, content_models & slot_roles tables).
$wgDBadminuser
Separate username for maintenance tasks.
$wgTrxProfilerLimits
Performance expectations for DB usage.
$wgDBservers
Database load balancer This is a two-dimensional array, an array of server info structures Fields are...
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.
$wgProfileLimit
Only record profiling info for pages that took longer than this.
$wgDBDefaultGroup
Default group to use when getting database connections.
$wgDBadminpassword
Separate password for maintenance tasks.
$wgProfiler
Profiler configuration.
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
$wgServer
URL of the server.
$wgLBFactoryConf
Load balancer factory configuration To set up a multi-master wiki farm, set the class here to somethi...
$wgDBpassword
Database user's password.
global $wgCommandLineMode
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfHostname()
Fetch server name for use in error reporting etc.
wfIsWindows()
Check if the operating system is Windows.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
const RUN_MAINTENANCE_IF_MAIN
wfEntryPointCheck( $format='text', $scriptPath='/')
Check PHP version and that external dependencies are installed, and display an informative error if e...
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Fake maintenance wrapper, mostly used for the web installer/updater.
execute()
Do the actual work.
Class for scripts that perform database maintenance and want to log the update in updatelog so we can...
__construct()
Default constructor.
doDBUpdates()
Do the actual work.
updateSkippedMessage()
Message to show that the update was done already and was just skipped.
getUpdateKey()
Get the update key name to go in the update log table.
execute()
Do the actual work.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
setup()
Do some sanity checking and basic setup.
__construct()
Default constructor.
error( $err, $die=0)
Throw an error to the user.
getName()
Get the script's name.
addArg( $arg, $description, $required=true)
Add some args that are needed.
requireExtension( $name)
Indicate that the specified extension must be loaded before the script can run.
relockSearchindex( $db)
Unlock and lock again Since the lock is low-priority, queued reads will be able to complete.
int $mBatchSize
Batch size.
setAgentAndTriggers()
Set triggers like when to try to run deferred updates.
$mAllowUnregisteredOptions
setAllowUnregisteredOptions( $allow)
Sets whether to allow unregistered options, which are options passed to a script that do not match an...
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
static getTermSize()
Get the terminal size as a two-element array where the first element is the width (number of columns)...
clearParamsAndArgs()
Clear all params and arguments.
static setLBFactoryTriggers(LBFactory $LBFactory, Config $config)
array $requiredExtensions
setParam(&$options, $option, $value)
Helper function used solely by loadParamsAndArgs to prevent code duplication.
const DB_NONE
Constants for DB access type.
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
output( $out, $channel=null)
Throw some output to the user.
supportsOption( $name)
Checks to see if a particular option in supported.
getStdin( $len=null)
Return input from stdin.
cleanupChanneled()
Clean up channeled output.
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
afterFinalSetup()
Execute a callback function at the end of initialisation.
hasArg( $argId=0)
Does a given argument exist?
getDir()
Get the maintenance directory.
addDefaultParams()
Add the default parameters to the scripts.
deleteOption( $name)
Remove an option.
static readlineEmulation( $prompt)
Emulate readline()
static requireTestsAutoloader()
Call this to set up the autoloader to allow classes to be used from the tests directory.
loadParamsAndArgs( $self=null, $opts=null, $args=null)
Process command line arguments $mOptions becomes an array with keys set to the option names $mArgs be...
outputChanneled( $msg, $channel=null)
Message outputter with channeled message support.
finalSetup()
Handle some last-minute setup here.
loadSpecialVars()
Handle the special variables that are global to all scripts.
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
float $lastReplicationWait
UNIX timestamp.
array $orderedOptions
Used to read the options in the order they were passed.
loadSettings()
Generic setup for most installs.
setDB(IDatabase $db)
Sets database object to be returned by getDB().
hasOption( $name)
Checks to see if a particular option exists.
purgeRedundantText( $delete=true)
Support function for cleaning up redundant text records.
countDown( $seconds)
Count down from $seconds to zero on the terminal, with a one-second pause between showing each number...
runChild( $maintClass, $classFile=null)
Run a child maintenance script.
IMaintainableDatabase $mDb
Used by getDB() / setDB()
execute()
Do the actual work.
static readconsole( $prompt='> ')
Prompt the console for input.
static posix_isatty( $fd)
Wrapper for posix_isatty() We default as considering stdin a tty (for nice readline methods) but trea...
adjustMemoryLimit()
Adjusts PHP's memory limit to better suit our needs, if needed.
validateParamsAndArgs()
Run some validation checks on the params, etc.
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
getBatchSize()
Returns batch size.
unlockSearchindex( $db)
Unlock the tables.
getArg( $argId=0, $default=null)
Get an argument.
addDescription( $text)
Set the description text.
activateProfiler()
Activate the profiler (assuming $wgProfiler is set)
maybeHelp( $force=false)
Maybe show the help.
updateSearchIndexForPage( $dbw, $pageId)
Update the searchindex table for a given pageid.
resource $fileHandle
Used when creating separate schema files.
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
static shouldExecute()
Should we execute the maintenance script, or just allow it to be included as a standalone class?...
getOption( $name, $default=null)
Get an option, or return the default.
Config $config
Accessible via getConfig()
lockSearchindex( $db)
Lock the search index.
checkRequiredExtensions()
Verify that the required extensions are installed.
rollbackTransaction(IDatabase $dbw, $fname)
Rollback the transcation on a DB handle.
updateSearchIndex( $maxLockTime, $callback, $dbw, $results)
Perform a search index update with locking.
globals()
Potentially debug globals.
setConfig(Config $config)
setBatchSize( $s=0)
Set the batch size.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
static loadFromPageId( $db, $pageid, $id=0)
Load either the current, or a specified, revision that's attached to a given page.
Database independant search index updater.
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
while(( $__line=Maintenance::readconsole()) !==false) print
const SCHEMA_COMPAT_READ_OLD
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
namespace and then decline to actually register it file or subcat img or subcat $title
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Allows to change the fields on the form that will be generated $name
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
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
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
Interface for configuration instances.
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
Advanced database interface for IDatabase handles that include maintenance methods.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
if(is_array($mode)) switch( $mode) $input