MediaWiki  master
Maintenance.php
Go to the documentation of this file.
1 <?php
23 // Bail on old versions of PHP, or if composer has not been run yet to install
24 // dependencies.
25 require_once __DIR__ . '/../includes/PHPVersionCheck.php';
26 wfEntryPointCheck( 'text' );
27 
30 
36 // Define this so scripts can easily find doMaintenance.php
37 define( 'RUN_MAINTENANCE_IF_MAIN', __DIR__ . '/doMaintenance.php' );
38 
42 define( 'DO_MAINTENANCE', RUN_MAINTENANCE_IF_MAIN ); // original name, harmless
43 
44 $maintClass = false;
45 
46 // Some extensions rely on MW_INSTALL_PATH to find core files to include. Setting it here helps them
47 // if they're included by a core script (like DatabaseUpdater) after Maintenance.php has already
48 // been run.
49 if ( strval( getenv( 'MW_INSTALL_PATH' ) ) === '' ) {
50  putenv( 'MW_INSTALL_PATH=' . realpath( __DIR__ . '/..' ) );
51 }
52 
58 
80 abstract class Maintenance {
85  const DB_NONE = 0;
86  const DB_STD = 1;
87  const DB_ADMIN = 2;
88 
89  // Const for getStdin()
90  const STDIN_ALL = 'all';
91 
92  // Array of desired/allowed params
93  protected $mParams = [];
94 
95  // Array of mapping short parameters to long ones
96  protected $mShortParamsMap = [];
97 
98  // Array of desired/allowed args
99  protected $mArgList = [];
100 
101  // This is the list of options that were actually passed
102  protected $mOptions = [];
103 
104  // This is the list of arguments that were actually passed
105  protected $mArgs = [];
106 
107  // Allow arbitrary options to be passed, or only specified ones?
108  protected $mAllowUnregisteredOptions = false;
109 
110  // Name of the script currently running
111  protected $mSelf;
112 
113  // Special vars for params that are always used
114  protected $mQuiet = false;
115  protected $mDbUser, $mDbPass;
116 
117  // A description of the script, children should change this via addDescription()
118  protected $mDescription = '';
119 
120  // Have we already loaded our user input?
121  protected $mInputLoaded = false;
122 
129  protected $mBatchSize = null;
130 
131  // Generic options added by addDefaultParams()
132  private $mGenericParameters = [];
133  // Generic options which might or not be supported by the script
134  private $mDependantParameters = [];
135 
140  private $mDb = null;
141 
143  private $lastReplicationWait = 0.0;
144 
149  public $fileHandle;
150 
156  private $config;
157 
162  private $requiredExtensions = [];
163 
175  public $orderedOptions = [];
176 
181  public function __construct() {
182  global $IP;
183  $IP = getenv( 'MW_INSTALL_PATH' );
184 
185  $this->addDefaultParams();
186  register_shutdown_function( [ $this, 'outputChanneled' ], false );
187  }
188 
196  public static function shouldExecute() {
197  global $wgCommandLineMode;
198 
199  if ( !function_exists( 'debug_backtrace' ) ) {
200  // If someone has a better idea...
201  return $wgCommandLineMode;
202  }
203 
204  $bt = debug_backtrace();
205  $count = count( $bt );
206  if ( $count < 2 ) {
207  return false; // sanity
208  }
209  if ( $bt[0]['class'] !== self::class || $bt[0]['function'] !== 'shouldExecute' ) {
210  return false; // last call should be to this function
211  }
212  $includeFuncs = [ 'require_once', 'require', 'include', 'include_once' ];
213  for ( $i = 1; $i < $count; $i++ ) {
214  if ( !in_array( $bt[$i]['function'], $includeFuncs ) ) {
215  return false; // previous calls should all be "requires"
216  }
217  }
218 
219  return true;
220  }
221 
230  abstract public function execute();
231 
238  protected function supportsOption( $name ) {
239  return isset( $this->mParams[$name] );
240  }
241 
253  protected function addOption( $name, $description, $required = false,
254  $withArg = false, $shortName = false, $multiOccurrence = false
255  ) {
256  $this->mParams[$name] = [
257  'desc' => $description,
258  'require' => $required,
259  'withArg' => $withArg,
260  'shortName' => $shortName,
261  'multiOccurrence' => $multiOccurrence
262  ];
263 
264  if ( $shortName !== false ) {
265  $this->mShortParamsMap[$shortName] = $name;
266  }
267  }
268 
274  protected function hasOption( $name ) {
275  return isset( $this->mOptions[$name] );
276  }
277 
288  protected function getOption( $name, $default = null ) {
289  if ( $this->hasOption( $name ) ) {
290  return $this->mOptions[$name];
291  } else {
292  // Set it so we don't have to provide the default again
293  $this->mOptions[$name] = $default;
294 
295  return $this->mOptions[$name];
296  }
297  }
298 
305  protected function addArg( $arg, $description, $required = true ) {
306  $this->mArgList[] = [
307  'name' => $arg,
308  'desc' => $description,
309  'require' => $required
310  ];
311  }
312 
317  protected function deleteOption( $name ) {
318  unset( $this->mParams[$name] );
319  }
320 
326  protected function setAllowUnregisteredOptions( $allow ) {
327  $this->mAllowUnregisteredOptions = $allow;
328  }
329 
334  protected function addDescription( $text ) {
335  $this->mDescription = $text;
336  }
337 
343  protected function hasArg( $argId = 0 ) {
344  if ( func_num_args() === 0 ) {
345  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
346  }
347 
348  return isset( $this->mArgs[$argId] );
349  }
350 
357  protected function getArg( $argId = 0, $default = null ) {
358  if ( func_num_args() === 0 ) {
359  wfDeprecated( __METHOD__ . ' without an $argId', '1.33' );
360  }
361 
362  return $this->mArgs[$argId] ?? $default;
363  }
364 
372  protected function getBatchSize() {
373  return $this->mBatchSize;
374  }
375 
380  protected function setBatchSize( $s = 0 ) {
381  $this->mBatchSize = $s;
382 
383  // If we support $mBatchSize, show the option.
384  // Used to be in addDefaultParams, but in order for that to
385  // work, subclasses would have to call this function in the constructor
386  // before they called parent::__construct which is just weird
387  // (and really wasn't done).
388  if ( $this->mBatchSize ) {
389  $this->addOption( 'batch-size', 'Run this many operations ' .
390  'per batch, default: ' . $this->mBatchSize, false, true );
391  if ( isset( $this->mParams['batch-size'] ) ) {
392  // This seems a little ugly...
393  $this->mDependantParameters['batch-size'] = $this->mParams['batch-size'];
394  }
395  }
396  }
397 
402  public function getName() {
403  return $this->mSelf;
404  }
405 
412  protected function getStdin( $len = null ) {
413  if ( $len == self::STDIN_ALL ) {
414  return file_get_contents( 'php://stdin' );
415  }
416  $f = fopen( 'php://stdin', 'rt' );
417  if ( !$len ) {
418  return $f;
419  }
420  $input = fgets( $f, $len );
421  fclose( $f );
422 
423  return rtrim( $input );
424  }
425 
429  public function isQuiet() {
430  return $this->mQuiet;
431  }
432 
439  protected function output( $out, $channel = null ) {
440  // This is sometimes called very early, before Setup.php is included.
441  if ( class_exists( MediaWikiServices::class ) ) {
442  // Try to periodically flush buffered metrics to avoid OOMs
443  $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
444  if ( $stats->getDataCount() > 1000 ) {
445  MediaWiki::emitBufferedStatsdData( $stats, $this->getConfig() );
446  }
447  }
448 
449  if ( $this->mQuiet ) {
450  return;
451  }
452  if ( $channel === null ) {
453  $this->cleanupChanneled();
454  print $out;
455  } else {
456  $out = preg_replace( '/\n\z/', '', $out );
457  $this->outputChanneled( $out, $channel );
458  }
459  }
460 
467  protected function error( $err, $die = 0 ) {
468  if ( intval( $die ) !== 0 ) {
469  wfDeprecated( __METHOD__ . '( $err, $die )', '1.31' );
470  $this->fatalError( $err, intval( $die ) );
471  }
472  $this->outputChanneled( false );
473  if (
474  ( PHP_SAPI == 'cli' || PHP_SAPI == 'phpdbg' ) &&
475  !defined( 'MW_PHPUNIT_TEST' )
476  ) {
477  fwrite( STDERR, $err . "\n" );
478  } else {
479  print $err;
480  }
481  }
482 
490  protected function fatalError( $msg, $exitCode = 1 ) {
491  $this->error( $msg );
492  exit( $exitCode );
493  }
494 
495  private $atLineStart = true;
496  private $lastChannel = null;
497 
501  public function cleanupChanneled() {
502  if ( !$this->atLineStart ) {
503  print "\n";
504  $this->atLineStart = true;
505  }
506  }
507 
516  public function outputChanneled( $msg, $channel = null ) {
517  if ( $msg === false ) {
518  $this->cleanupChanneled();
519 
520  return;
521  }
522 
523  // End the current line if necessary
524  if ( !$this->atLineStart && $channel !== $this->lastChannel ) {
525  print "\n";
526  }
527 
528  print $msg;
529 
530  $this->atLineStart = false;
531  if ( $channel === null ) {
532  // For unchanneled messages, output trailing newline immediately
533  print "\n";
534  $this->atLineStart = true;
535  }
536  $this->lastChannel = $channel;
537  }
538 
549  public function getDbType() {
550  return self::DB_STD;
551  }
552 
556  protected function addDefaultParams() {
557  # Generic (non script dependant) options:
558 
559  $this->addOption( 'help', 'Display this help message', false, false, 'h' );
560  $this->addOption( 'quiet', 'Whether to suppress non-error output', false, false, 'q' );
561  $this->addOption( 'conf', 'Location of LocalSettings.php, if not default', false, true );
562  $this->addOption( 'wiki', 'For specifying the wiki ID', false, true );
563  $this->addOption( 'globals', 'Output globals at the end of processing for debugging' );
564  $this->addOption(
565  'memory-limit',
566  'Set a specific memory limit for the script, '
567  . '"max" for no limit or "default" to avoid changing it',
568  false,
569  true
570  );
571  $this->addOption( 'server', "The protocol and server name to use in URLs, e.g. " .
572  "http://en.wikipedia.org. This is sometimes necessary because " .
573  "server name detection may fail in command line scripts.", false, true );
574  $this->addOption( 'profiler', 'Profiler output format (usually "text")', false, true );
575  // This is named --mwdebug, because --debug would conflict in the phpunit.php CLI script.
576  $this->addOption( 'mwdebug', 'Enable built-in MediaWiki development settings', false, true );
577 
578  # Save generic options to display them separately in help
579  $this->mGenericParameters = $this->mParams;
580 
581  # Script dependant options:
582 
583  // If we support a DB, show the options
584  if ( $this->getDbType() > 0 ) {
585  $this->addOption( 'dbuser', 'The DB user to use for this script', false, true );
586  $this->addOption( 'dbpass', 'The password to use for this script', false, true );
587  $this->addOption( 'dbgroupdefault', 'The default DB group to use.', false, true );
588  }
589 
590  # Save additional script dependant options to display
591  # ┬áthem separately in help
592  $this->mDependantParameters = array_diff_key( $this->mParams, $this->mGenericParameters );
593  }
594 
599  public function getConfig() {
600  if ( $this->config === null ) {
601  $this->config = MediaWikiServices::getInstance()->getMainConfig();
602  }
603 
604  return $this->config;
605  }
606 
611  public function setConfig( Config $config ) {
612  $this->config = $config;
613  }
614 
624  protected function requireExtension( $name ) {
625  $this->requiredExtensions[] = $name;
626  }
627 
633  public function checkRequiredExtensions() {
634  $registry = ExtensionRegistry::getInstance();
635  $missing = [];
636  foreach ( $this->requiredExtensions as $name ) {
637  if ( !$registry->isLoaded( $name ) ) {
638  $missing[] = $name;
639  }
640  }
641 
642  if ( $missing ) {
643  $joined = implode( ', ', $missing );
644  $msg = "The following extensions are required to be installed "
645  . "for this script to run: $joined. Please enable them and then try again.";
646  $this->fatalError( $msg );
647  }
648  }
649 
654  public function setAgentAndTriggers() {
655  if ( function_exists( 'posix_getpwuid' ) ) {
656  $agent = posix_getpwuid( posix_geteuid() )['name'];
657  } else {
658  $agent = 'sysadmin';
659  }
660  $agent .= '@' . wfHostname();
661 
662  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
663  // Add a comment for easy SHOW PROCESSLIST interpretation
664  $lbFactory->setAgentName(
665  mb_strlen( $agent ) > 15 ? mb_substr( $agent, 0, 15 ) . '...' : $agent
666  );
667  self::setLBFactoryTriggers( $lbFactory, $this->getConfig() );
668  }
669 
675  public static function setLBFactoryTriggers( LBFactory $LBFactory, Config $config ) {
676  $services = MediaWikiServices::getInstance();
677  $stats = $services->getStatsdDataFactory();
678  // Hook into period lag checks which often happen in long-running scripts
679  $lbFactory = $services->getDBLoadBalancerFactory();
680  $lbFactory->setWaitForReplicationListener(
681  __METHOD__,
682  function () use ( $stats, $config ) {
683  // Check config in case of JobRunner and unit tests
684  if ( $config->get( 'CommandLineMode' ) ) {
686  }
687  // Try to periodically flush buffered metrics to avoid OOMs
688  MediaWiki::emitBufferedStatsdData( $stats, $config );
689  }
690  );
691  // Check for other windows to run them. A script may read or do a few writes
692  // to the master but mostly be writing to something else, like a file store.
693  $lbFactory->getMainLB()->setTransactionListener(
694  __METHOD__,
695  function ( $trigger ) use ( $stats, $config ) {
696  // Check config in case of JobRunner and unit tests
697  if ( $config->get( 'CommandLineMode' ) && $trigger === IDatabase::TRIGGER_COMMIT ) {
699  }
700  // Try to periodically flush buffered metrics to avoid OOMs
701  MediaWiki::emitBufferedStatsdData( $stats, $config );
702  }
703  );
704  }
705 
713  public function runChild( $maintClass, $classFile = null ) {
714  // Make sure the class is loaded first
715  if ( !class_exists( $maintClass ) ) {
716  if ( $classFile ) {
717  require_once $classFile;
718  }
719  if ( !class_exists( $maintClass ) ) {
720  $this->error( "Cannot spawn child: $maintClass" );
721  }
722  }
723 
727  $child = new $maintClass();
728  $child->loadParamsAndArgs( $this->mSelf, $this->mOptions, $this->mArgs );
729  if ( !is_null( $this->mDb ) ) {
730  $child->setDB( $this->mDb );
731  }
732 
733  return $child;
734  }
735 
739  public function setup() {
740  global $IP, $wgCommandLineMode;
741 
742  # Abort if called from a web server
743  # wfIsCLI() is not available yet
744  if ( PHP_SAPI !== 'cli' && PHP_SAPI !== 'phpdbg' ) {
745  $this->fatalError( 'This script must be run from the command line' );
746  }
747 
748  if ( $IP === null ) {
749  $this->fatalError( "\$IP not set, aborting!\n" .
750  '(Did you forget to call parent::__construct() in your maintenance script?)' );
751  }
752 
753  # Make sure we can handle script parameters
754  if ( !defined( 'HPHP_VERSION' ) && !ini_get( 'register_argc_argv' ) ) {
755  $this->fatalError( 'Cannot get command line arguments, register_argc_argv is set to false' );
756  }
757 
758  // Send PHP warnings and errors to stderr instead of stdout.
759  // This aids in diagnosing problems, while keeping messages
760  // out of redirected output.
761  if ( ini_get( 'display_errors' ) ) {
762  ini_set( 'display_errors', 'stderr' );
763  }
764 
765  $this->loadParamsAndArgs();
766 
767  # Set the memory limit
768  # Note we need to set it again later in cache LocalSettings changed it
769  $this->adjustMemoryLimit();
770 
771  # Set max execution time to 0 (no limit). PHP.net says that
772  # "When running PHP from the command line the default setting is 0."
773  # But sometimes this doesn't seem to be the case.
774  ini_set( 'max_execution_time', 0 );
775 
776  # Define us as being in MediaWiki
777  define( 'MEDIAWIKI', true );
778 
779  $wgCommandLineMode = true;
780 
781  # Turn off output buffering if it's on
782  while ( ob_get_level() > 0 ) {
783  ob_end_flush();
784  }
785  }
786 
796  public function memoryLimit() {
797  $limit = $this->getOption( 'memory-limit', 'max' );
798  $limit = trim( $limit, "\" '" ); // trim quotes in case someone misunderstood
799  return $limit;
800  }
801 
805  protected function adjustMemoryLimit() {
806  $limit = $this->memoryLimit();
807  if ( $limit == 'max' ) {
808  $limit = -1; // no memory limit
809  }
810  if ( $limit != 'default' ) {
811  ini_set( 'memory_limit', $limit );
812  }
813  }
814 
818  protected function activateProfiler() {
820 
821  $output = $this->getOption( 'profiler' );
822  if ( !$output ) {
823  return;
824  }
825 
826  if ( is_array( $wgProfiler ) && isset( $wgProfiler['class'] ) ) {
827  $class = $wgProfiler['class'];
829  $profiler = new $class(
830  [ 'sampling' => 1, 'output' => [ $output ] ]
831  + $wgProfiler
832  + [ 'threshold' => $wgProfileLimit ]
833  );
834  $profiler->setTemplated( true );
835  Profiler::replaceStubInstance( $profiler );
836  }
837 
838  $trxProfiler = Profiler::instance()->getTransactionProfiler();
839  $trxProfiler->setLogger( LoggerFactory::getInstance( 'DBPerformance' ) );
840  $trxProfiler->setExpectations( $wgTrxProfilerLimits['Maintenance'], __METHOD__ );
841  }
842 
846  public function clearParamsAndArgs() {
847  $this->mOptions = [];
848  $this->mArgs = [];
849  $this->mInputLoaded = false;
850  }
851 
859  public function loadWithArgv( $argv ) {
860  $options = [];
861  $args = [];
862  $this->orderedOptions = [];
863 
864  # Parse arguments
865  for ( $arg = reset( $argv ); $arg !== false; $arg = next( $argv ) ) {
866  if ( $arg == '--' ) {
867  # End of options, remainder should be considered arguments
868  $arg = next( $argv );
869  while ( $arg !== false ) {
870  $args[] = $arg;
871  $arg = next( $argv );
872  }
873  break;
874  } elseif ( substr( $arg, 0, 2 ) == '--' ) {
875  # Long options
876  $option = substr( $arg, 2 );
877  if ( isset( $this->mParams[$option] ) && $this->mParams[$option]['withArg'] ) {
878  $param = next( $argv );
879  if ( $param === false ) {
880  $this->error( "\nERROR: $option parameter needs a value after it\n" );
881  $this->maybeHelp( true );
882  }
883 
884  $this->setParam( $options, $option, $param );
885  } else {
886  $bits = explode( '=', $option, 2 );
887  $this->setParam( $options, $bits[0], $bits[1] ?? 1 );
888  }
889  } elseif ( $arg == '-' ) {
890  # Lonely "-", often used to indicate stdin or stdout.
891  $args[] = $arg;
892  } elseif ( substr( $arg, 0, 1 ) == '-' ) {
893  # Short options
894  $argLength = strlen( $arg );
895  for ( $p = 1; $p < $argLength; $p++ ) {
896  $option = $arg[$p];
897  if ( !isset( $this->mParams[$option] ) && isset( $this->mShortParamsMap[$option] ) ) {
898  $option = $this->mShortParamsMap[$option];
899  }
900 
901  if ( isset( $this->mParams[$option]['withArg'] ) && $this->mParams[$option]['withArg'] ) {
902  $param = next( $argv );
903  if ( $param === false ) {
904  $this->error( "\nERROR: $option parameter needs a value after it\n" );
905  $this->maybeHelp( true );
906  }
907  $this->setParam( $options, $option, $param );
908  } else {
909  $this->setParam( $options, $option, 1 );
910  }
911  }
912  } else {
913  $args[] = $arg;
914  }
915  }
916 
917  $this->mOptions = $options;
918  $this->mArgs = $args;
919  $this->loadSpecialVars();
920  $this->mInputLoaded = true;
921  }
922 
935  private function setParam( &$options, $option, $value ) {
936  $this->orderedOptions[] = [ $option, $value ];
937 
938  if ( isset( $this->mParams[$option] ) ) {
939  $multi = $this->mParams[$option]['multiOccurrence'];
940  } else {
941  $multi = false;
942  }
943  $exists = array_key_exists( $option, $options );
944  if ( $multi && $exists ) {
945  $options[$option][] = $value;
946  } elseif ( $multi ) {
947  $options[$option] = [ $value ];
948  } elseif ( !$exists ) {
949  $options[$option] = $value;
950  } else {
951  $this->error( "\nERROR: $option parameter given twice\n" );
952  $this->maybeHelp( true );
953  }
954  }
955 
965  public function loadParamsAndArgs( $self = null, $opts = null, $args = null ) {
966  # If we were given opts or args, set those and return early
967  if ( $self ) {
968  $this->mSelf = $self;
969  $this->mInputLoaded = true;
970  }
971  if ( $opts ) {
972  $this->mOptions = $opts;
973  $this->mInputLoaded = true;
974  }
975  if ( $args ) {
976  $this->mArgs = $args;
977  $this->mInputLoaded = true;
978  }
979 
980  # If we've already loaded input (either by user values or from $argv)
981  # skip on loading it again. The array_shift() will corrupt values if
982  # it's run again and again
983  if ( $this->mInputLoaded ) {
984  $this->loadSpecialVars();
985 
986  return;
987  }
988 
989  global $argv;
990  $this->mSelf = $argv[0];
991  $this->loadWithArgv( array_slice( $argv, 1 ) );
992  }
993 
997  public function validateParamsAndArgs() {
998  $die = false;
999  # Check to make sure we've got all the required options
1000  foreach ( $this->mParams as $opt => $info ) {
1001  if ( $info['require'] && !$this->hasOption( $opt ) ) {
1002  $this->error( "Param $opt required!" );
1003  $die = true;
1004  }
1005  }
1006  # Check arg list too
1007  foreach ( $this->mArgList as $k => $info ) {
1008  if ( $info['require'] && !$this->hasArg( $k ) ) {
1009  $this->error( 'Argument <' . $info['name'] . '> required!' );
1010  $die = true;
1011  }
1012  }
1013  if ( !$this->mAllowUnregisteredOptions ) {
1014  # Check for unexpected options
1015  foreach ( $this->mOptions as $opt => $val ) {
1016  if ( !$this->supportsOption( $opt ) ) {
1017  $this->error( "Unexpected option $opt!" );
1018  $die = true;
1019  }
1020  }
1021  }
1022 
1023  $this->maybeHelp( $die );
1024  }
1025 
1029  protected function loadSpecialVars() {
1030  if ( $this->hasOption( 'dbuser' ) ) {
1031  $this->mDbUser = $this->getOption( 'dbuser' );
1032  }
1033  if ( $this->hasOption( 'dbpass' ) ) {
1034  $this->mDbPass = $this->getOption( 'dbpass' );
1035  }
1036  if ( $this->hasOption( 'quiet' ) ) {
1037  $this->mQuiet = true;
1038  }
1039  if ( $this->hasOption( 'batch-size' ) ) {
1040  $this->mBatchSize = intval( $this->getOption( 'batch-size' ) );
1041  }
1042  }
1043 
1048  protected function maybeHelp( $force = false ) {
1049  if ( !$force && !$this->hasOption( 'help' ) ) {
1050  return;
1051  }
1052 
1053  $screenWidth = 80; // TODO: Calculate this!
1054  $tab = " ";
1055  $descWidth = $screenWidth - ( 2 * strlen( $tab ) );
1056 
1057  ksort( $this->mParams );
1058  $this->mQuiet = false;
1059 
1060  // Description ...
1061  if ( $this->mDescription ) {
1062  $this->output( "\n" . wordwrap( $this->mDescription, $screenWidth ) . "\n" );
1063  }
1064  $output = "\nUsage: php " . basename( $this->mSelf );
1065 
1066  // ... append parameters ...
1067  if ( $this->mParams ) {
1068  $output .= " [--" . implode( "|--", array_keys( $this->mParams ) ) . "]";
1069  }
1070 
1071  // ... and append arguments.
1072  if ( $this->mArgList ) {
1073  $output .= ' ';
1074  foreach ( $this->mArgList as $k => $arg ) {
1075  if ( $arg['require'] ) {
1076  $output .= '<' . $arg['name'] . '>';
1077  } else {
1078  $output .= '[' . $arg['name'] . ']';
1079  }
1080  if ( $k < count( $this->mArgList ) - 1 ) {
1081  $output .= ' ';
1082  }
1083  }
1084  }
1085  $this->output( "$output\n\n" );
1086 
1087  # TODO abstract some repetitive code below
1088 
1089  // Generic parameters
1090  $this->output( "Generic maintenance parameters:\n" );
1091  foreach ( $this->mGenericParameters as $par => $info ) {
1092  if ( $info['shortName'] !== false ) {
1093  $par .= " (-{$info['shortName']})";
1094  }
1095  $this->output(
1096  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1097  "\n$tab$tab" ) . "\n"
1098  );
1099  }
1100  $this->output( "\n" );
1101 
1102  $scriptDependantParams = $this->mDependantParameters;
1103  if ( count( $scriptDependantParams ) > 0 ) {
1104  $this->output( "Script dependant parameters:\n" );
1105  // Parameters description
1106  foreach ( $scriptDependantParams as $par => $info ) {
1107  if ( $info['shortName'] !== false ) {
1108  $par .= " (-{$info['shortName']})";
1109  }
1110  $this->output(
1111  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1112  "\n$tab$tab" ) . "\n"
1113  );
1114  }
1115  $this->output( "\n" );
1116  }
1117 
1118  // Script specific parameters not defined on construction by
1119  // Maintenance::addDefaultParams()
1120  $scriptSpecificParams = array_diff_key(
1121  # all script parameters:
1122  $this->mParams,
1123  # remove the Maintenance default parameters:
1124  $this->mGenericParameters,
1125  $this->mDependantParameters
1126  );
1127  if ( count( $scriptSpecificParams ) > 0 ) {
1128  $this->output( "Script specific parameters:\n" );
1129  // Parameters description
1130  foreach ( $scriptSpecificParams as $par => $info ) {
1131  if ( $info['shortName'] !== false ) {
1132  $par .= " (-{$info['shortName']})";
1133  }
1134  $this->output(
1135  wordwrap( "$tab--$par: " . $info['desc'], $descWidth,
1136  "\n$tab$tab" ) . "\n"
1137  );
1138  }
1139  $this->output( "\n" );
1140  }
1141 
1142  // Print arguments
1143  if ( count( $this->mArgList ) > 0 ) {
1144  $this->output( "Arguments:\n" );
1145  // Arguments description
1146  foreach ( $this->mArgList as $info ) {
1147  $openChar = $info['require'] ? '<' : '[';
1148  $closeChar = $info['require'] ? '>' : ']';
1149  $this->output(
1150  wordwrap( "$tab$openChar" . $info['name'] . "$closeChar: " .
1151  $info['desc'], $descWidth, "\n$tab$tab" ) . "\n"
1152  );
1153  }
1154  $this->output( "\n" );
1155  }
1156 
1157  die( 1 );
1158  }
1159 
1163  public function finalSetup() {
1167 
1168  # Turn off output buffering again, it might have been turned on in the settings files
1169  if ( ob_get_level() ) {
1170  ob_end_flush();
1171  }
1172  # Same with these
1173  $wgCommandLineMode = true;
1174 
1175  # Override $wgServer
1176  if ( $this->hasOption( 'server' ) ) {
1177  $wgServer = $this->getOption( 'server', $wgServer );
1178  }
1179 
1180  # If these were passed, use them
1181  if ( $this->mDbUser ) {
1182  $wgDBadminuser = $this->mDbUser;
1183  }
1184  if ( $this->mDbPass ) {
1185  $wgDBadminpassword = $this->mDbPass;
1186  }
1187  if ( $this->hasOption( 'dbgroupdefault' ) ) {
1188  $wgDBDefaultGroup = $this->getOption( 'dbgroupdefault', null );
1189 
1190  MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1191  }
1192 
1193  if ( $this->getDbType() == self::DB_ADMIN && isset( $wgDBadminuser ) ) {
1194  $wgDBuser = $wgDBadminuser;
1195  $wgDBpassword = $wgDBadminpassword;
1196 
1197  if ( $wgDBservers ) {
1201  foreach ( $wgDBservers as $i => $server ) {
1202  $wgDBservers[$i]['user'] = $wgDBuser;
1203  $wgDBservers[$i]['password'] = $wgDBpassword;
1204  }
1205  }
1206  if ( isset( $wgLBFactoryConf['serverTemplate'] ) ) {
1207  $wgLBFactoryConf['serverTemplate']['user'] = $wgDBuser;
1208  $wgLBFactoryConf['serverTemplate']['password'] = $wgDBpassword;
1209  }
1210  MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->destroy();
1211  }
1212 
1213  # Apply debug settings
1214  if ( $this->hasOption( 'mwdebug' ) ) {
1215  require __DIR__ . '/../includes/DevelopmentSettings.php';
1216  }
1217 
1218  // Per-script profiling; useful for debugging
1219  $this->activateProfiler();
1220 
1221  $this->afterFinalSetup();
1222 
1223  $wgShowExceptionDetails = true;
1224  $wgShowHostnames = true;
1225 
1226  Wikimedia\suppressWarnings();
1227  set_time_limit( 0 );
1228  Wikimedia\restoreWarnings();
1229 
1230  $this->adjustMemoryLimit();
1231  }
1232 
1236  protected function afterFinalSetup() {
1237  if ( defined( 'MW_CMDLINE_CALLBACK' ) ) {
1238  call_user_func( MW_CMDLINE_CALLBACK );
1239  }
1240  }
1241 
1246  public function globals() {
1247  if ( $this->hasOption( 'globals' ) ) {
1248  print_r( $GLOBALS );
1249  }
1250  }
1251 
1256  public function loadSettings() {
1257  global $wgCommandLineMode, $IP;
1258 
1259  if ( isset( $this->mOptions['conf'] ) ) {
1260  $settingsFile = $this->mOptions['conf'];
1261  } elseif ( defined( "MW_CONFIG_FILE" ) ) {
1262  $settingsFile = MW_CONFIG_FILE;
1263  } else {
1264  $settingsFile = "$IP/LocalSettings.php";
1265  }
1266  if ( isset( $this->mOptions['wiki'] ) ) {
1267  $bits = explode( '-', $this->mOptions['wiki'], 2 );
1268  define( 'MW_DB', $bits[0] );
1269  define( 'MW_PREFIX', $bits[1] ?? '' );
1270  } elseif ( isset( $this->mOptions['server'] ) ) {
1271  // Provide the option for site admins to detect and configure
1272  // multiple wikis based on server names. This offers --server
1273  // as alternative to --wiki.
1274  // See https://www.mediawiki.org/wiki/Manual:Wiki_family
1275  $_SERVER['SERVER_NAME'] = $this->mOptions['server'];
1276  }
1277 
1278  if ( !is_readable( $settingsFile ) ) {
1279  $this->fatalError( "A copy of your installation's LocalSettings.php\n" .
1280  "must exist and be readable in the source directory.\n" .
1281  "Use --conf to specify it." );
1282  }
1283  $wgCommandLineMode = true;
1284 
1285  return $settingsFile;
1286  }
1287 
1293  public function purgeRedundantText( $delete = true ) {
1295 
1296  # Data should come off the master, wrapped in a transaction
1297  $dbw = $this->getDB( DB_MASTER );
1298  $this->beginTransaction( $dbw, __METHOD__ );
1299 
1300  if ( $wgMultiContentRevisionSchemaMigrationStage & SCHEMA_COMPAT_READ_OLD ) {
1301  # Get "active" text records from the revisions table
1302  $cur = [];
1303  $this->output( 'Searching for active text records in revisions table...' );
1304  $res = $dbw->select( 'revision', 'rev_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1305  foreach ( $res as $row ) {
1306  $cur[] = $row->rev_text_id;
1307  }
1308  $this->output( "done.\n" );
1309 
1310  # Get "active" text records from the archive table
1311  $this->output( 'Searching for active text records in archive table...' );
1312  $res = $dbw->select( 'archive', 'ar_text_id', [], __METHOD__, [ 'DISTINCT' ] );
1313  foreach ( $res as $row ) {
1314  # old pre-MW 1.5 records can have null ar_text_id's.
1315  if ( $row->ar_text_id !== null ) {
1316  $cur[] = $row->ar_text_id;
1317  }
1318  }
1319  $this->output( "done.\n" );
1320  } else {
1321  # Get "active" text records via the content table
1322  $cur = [];
1323  $this->output( 'Searching for active text records via contents table...' );
1324  $res = $dbw->select( 'content', 'content_address', [], __METHOD__, [ 'DISTINCT' ] );
1325  $blobStore = MediaWikiServices::getInstance()->getBlobStore();
1326  foreach ( $res as $row ) {
1327  $textId = $blobStore->getTextIdFromAddress( $row->content_address );
1328  if ( $textId ) {
1329  $cur[] = $textId;
1330  }
1331  }
1332  $this->output( "done.\n" );
1333  }
1334  $this->output( "done.\n" );
1335 
1336  # Get the IDs of all text records not in these sets
1337  $this->output( 'Searching for inactive text records...' );
1338  $cond = 'old_id NOT IN ( ' . $dbw->makeList( $cur ) . ' )';
1339  $res = $dbw->select( 'text', 'old_id', [ $cond ], __METHOD__, [ 'DISTINCT' ] );
1340  $old = [];
1341  foreach ( $res as $row ) {
1342  $old[] = $row->old_id;
1343  }
1344  $this->output( "done.\n" );
1345 
1346  # Inform the user of what we're going to do
1347  $count = count( $old );
1348  $this->output( "$count inactive items found.\n" );
1349 
1350  # Delete as appropriate
1351  if ( $delete && $count ) {
1352  $this->output( 'Deleting...' );
1353  $dbw->delete( 'text', [ 'old_id' => $old ], __METHOD__ );
1354  $this->output( "done.\n" );
1355  }
1356 
1357  $this->commitTransaction( $dbw, __METHOD__ );
1358  }
1359 
1364  protected function getDir() {
1365  return __DIR__;
1366  }
1367 
1378  protected function getDB( $db, $groups = [], $wiki = false ) {
1379  if ( $this->mDb === null ) {
1380  return wfGetDB( $db, $groups, $wiki );
1381  }
1382  return $this->mDb;
1383  }
1384 
1390  public function setDB( IDatabase $db ) {
1391  $this->mDb = $db;
1392  }
1393 
1404  protected function beginTransaction( IDatabase $dbw, $fname ) {
1405  $dbw->begin( $fname );
1406  }
1407 
1419  protected function commitTransaction( IDatabase $dbw, $fname ) {
1420  $dbw->commit( $fname );
1421  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
1422  $waitSucceeded = $lbFactory->waitForReplication(
1423  [ 'timeout' => 30, 'ifWritesSince' => $this->lastReplicationWait ]
1424  );
1425  $this->lastReplicationWait = microtime( true );
1426  return $waitSucceeded;
1427  }
1428 
1439  protected function rollbackTransaction( IDatabase $dbw, $fname ) {
1440  $dbw->rollback( $fname );
1441  }
1442 
1447  private function lockSearchindex( $db ) {
1448  $write = [ 'searchindex' ];
1449  $read = [
1450  'page',
1451  'revision',
1452  'text',
1453  'interwiki',
1454  'l10n_cache',
1455  'user',
1456  'page_restrictions'
1457  ];
1458  $db->lockTables( $read, $write, __CLASS__ . '-searchIndexLock' );
1459  }
1460 
1465  private function unlockSearchindex( $db ) {
1466  $db->unlockTables( __CLASS__ . '-searchIndexLock' );
1467  }
1468 
1474  private function relockSearchindex( $db ) {
1475  $this->unlockSearchindex( $db );
1476  $this->lockSearchindex( $db );
1477  }
1478 
1486  public function updateSearchIndex( $maxLockTime, $callback, $dbw, $results ) {
1487  $lockTime = time();
1488 
1489  # Lock searchindex
1490  if ( $maxLockTime ) {
1491  $this->output( " --- Waiting for lock ---" );
1492  $this->lockSearchindex( $dbw );
1493  $lockTime = time();
1494  $this->output( "\n" );
1495  }
1496 
1497  # Loop through the results and do a search update
1498  foreach ( $results as $row ) {
1499  # Allow reads to be processed
1500  if ( $maxLockTime && time() > $lockTime + $maxLockTime ) {
1501  $this->output( " --- Relocking ---" );
1502  $this->relockSearchindex( $dbw );
1503  $lockTime = time();
1504  $this->output( "\n" );
1505  }
1506  call_user_func( $callback, $dbw, $row );
1507  }
1508 
1509  # Unlock searchindex
1510  if ( $maxLockTime ) {
1511  $this->output( " --- Unlocking --" );
1512  $this->unlockSearchindex( $dbw );
1513  $this->output( "\n" );
1514  }
1515  }
1516 
1523  public function updateSearchIndexForPage( $dbw, $pageId ) {
1524  // Get current revision
1525  $rev = Revision::loadFromPageId( $dbw, $pageId );
1526  $title = null;
1527  if ( $rev ) {
1528  $titleObj = $rev->getTitle();
1529  $title = $titleObj->getPrefixedDBkey();
1530  $this->output( "$title..." );
1531  # Update searchindex
1532  $u = new SearchUpdate( $pageId, $titleObj->getText(), $rev->getContent() );
1533  $u->doUpdate();
1534  $this->output( "\n" );
1535  }
1536 
1537  return $title;
1538  }
1539 
1550  protected function countDown( $seconds ) {
1551  if ( $this->isQuiet() ) {
1552  return;
1553  }
1554  for ( $i = $seconds; $i >= 0; $i-- ) {
1555  if ( $i != $seconds ) {
1556  $this->output( str_repeat( "\x08", strlen( $i + 1 ) ) );
1557  }
1558  $this->output( $i );
1559  if ( $i ) {
1560  sleep( 1 );
1561  }
1562  }
1563  $this->output( "\n" );
1564  }
1565 
1574  public static function posix_isatty( $fd ) {
1575  if ( !function_exists( 'posix_isatty' ) ) {
1576  return !$fd;
1577  } else {
1578  return posix_isatty( $fd );
1579  }
1580  }
1581 
1587  public static function readconsole( $prompt = '> ' ) {
1588  static $isatty = null;
1589  if ( is_null( $isatty ) ) {
1590  $isatty = self::posix_isatty( 0 /*STDIN*/ );
1591  }
1592 
1593  if ( $isatty && function_exists( 'readline' ) ) {
1594  return readline( $prompt );
1595  } else {
1596  if ( $isatty ) {
1597  $st = self::readlineEmulation( $prompt );
1598  } else {
1599  if ( feof( STDIN ) ) {
1600  $st = false;
1601  } else {
1602  $st = fgets( STDIN, 1024 );
1603  }
1604  }
1605  if ( $st === false ) {
1606  return false;
1607  }
1608  $resp = trim( $st );
1609 
1610  return $resp;
1611  }
1612  }
1613 
1619  private static function readlineEmulation( $prompt ) {
1620  $bash = ExecutableFinder::findInDefaultPaths( 'bash' );
1621  if ( !wfIsWindows() && $bash ) {
1622  $retval = false;
1623  $encPrompt = Shell::escape( $prompt );
1624  $command = "read -er -p $encPrompt && echo \"\$REPLY\"";
1625  $encCommand = Shell::escape( $command );
1626  $line = Shell::escape( "$bash -c $encCommand", $retval, [], [ 'walltime' => 0 ] );
1627 
1628  if ( $retval == 0 ) {
1629  return $line;
1630  } elseif ( $retval == 127 ) {
1631  // Couldn't execute bash even though we thought we saw it.
1632  // Shell probably spit out an error message, sorry :(
1633  // Fall through to fgets()...
1634  } else {
1635  // EOF/ctrl+D
1636  return false;
1637  }
1638  }
1639 
1640  // Fallback... we'll have no editing controls, EWWW
1641  if ( feof( STDIN ) ) {
1642  return false;
1643  }
1644  print $prompt;
1645 
1646  return fgets( STDIN, 1024 );
1647  }
1648 
1656  public static function getTermSize() {
1657  $default = [ 80, 50 ];
1658  if ( wfIsWindows() ) {
1659  return $default;
1660  }
1661  if ( Shell::isDisabled() ) {
1662  return $default;
1663  }
1664  // It's possible to get the screen size with VT-100 terminal escapes,
1665  // but reading the responses is not possible without setting raw mode
1666  // (unless you want to require the user to press enter), and that
1667  // requires an ioctl(), which we can't do. So we have to shell out to
1668  // something that can do the relevant syscalls. There are a few
1669  // options. Linux and Mac OS X both have "stty size" which does the
1670  // job directly.
1671  $result = Shell::command( 'stty', 'size' )
1672  ->execute();
1673  if ( $result->getExitCode() !== 0 ) {
1674  return $default;
1675  }
1676  if ( !preg_match( '/^(\d+) (\d+)$/', $result->getStdout(), $m ) ) {
1677  return $default;
1678  }
1679  return [ intval( $m[2] ), intval( $m[1] ) ];
1680  }
1681 
1686  public static function requireTestsAutoloader() {
1687  require_once __DIR__ . '/../tests/common/TestsAutoLoader.php';
1688  }
1689 }
1690 
1695  protected $mSelf = "FakeMaintenanceScript";
1696 
1697  public function execute() {
1698  }
1699 }
1700 
1705 abstract class LoggedUpdateMaintenance extends Maintenance {
1706  public function __construct() {
1707  parent::__construct();
1708  $this->addOption( 'force', 'Run the update even if it was completed already' );
1709  $this->setBatchSize( 200 );
1710  }
1711 
1712  public function execute() {
1713  $db = $this->getDB( DB_MASTER );
1714  $key = $this->getUpdateKey();
1715 
1716  if ( !$this->hasOption( 'force' )
1717  && $db->selectRow( 'updatelog', '1', [ 'ul_key' => $key ], __METHOD__ )
1718  ) {
1719  $this->output( "..." . $this->updateSkippedMessage() . "\n" );
1720 
1721  return true;
1722  }
1723 
1724  if ( !$this->doDBUpdates() ) {
1725  return false;
1726  }
1727 
1728  $db->insert( 'updatelog', [ 'ul_key' => $key ], __METHOD__, [ 'IGNORE' ] );
1729 
1730  return true;
1731  }
1732 
1737  protected function updateSkippedMessage() {
1738  $key = $this->getUpdateKey();
1739 
1740  return "Update '{$key}' already logged as completed.";
1741  }
1742 
1748  abstract protected function doDBUpdates();
1749 
1754  abstract protected function getUpdateKey();
1755 }
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
const STDIN_ALL
Definition: Maintenance.php:90
getArg( $argId=0, $default=null)
Get an argument.
const DB_NONE
Constants for DB access type.
Definition: Maintenance.php:85
const RUN_MAINTENANCE_IF_MAIN
Definition: Maintenance.php:37
maybeHelp( $force=false)
Maybe show the help.
checkRequiredExtensions()
Verify that the required extensions are installed.
if(is_array( $mode)) switch( $mode) $input
$wgDBDefaultGroup
Default group to use when getting database connections.
setParam(&$options, $option, $value)
Helper function used solely by loadParamsAndArgs to prevent code duplication.
error( $err, $die=0)
Throw an error to the user.
runChild( $maintClass, $classFile=null)
Run a child maintenance script.
static setLBFactoryTriggers(LBFactory $LBFactory, Config $config)
$IP
Definition: WebStart.php:41
An interface for generating database load balancers.
Definition: LBFactory.php:40
int $wgMultiContentRevisionSchemaMigrationStage
RevisionStore table schema migration stage (content, slots, content_models & slot_roles tables)...
$wgDBadminpassword
Separate password for maintenance tasks.
lockSearchindex( $db)
Lock the search index.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
getOption( $name, $default=null)
Get an option, or return the default.
getDir()
Get the maintenance directory.
array $orderedOptions
Used to read the options in the order they were passed.
$command
Definition: cdb.php:65
static instance()
Singleton.
Definition: Profiler.php:62
$wgDBpassword
Database user&#39;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...
Definition: maintenance.txt:39
getName()
Get the script&#39;s name.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
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.
afterFinalSetup()
Execute a callback function at the end of initialisation.
$value
static readconsole( $prompt='> ')
Prompt the console for input.
requireExtension( $name)
Indicate that the specified extension must be loaded before the script can run.
setConfig(Config $config)
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
Definition: injection.txt:23
updateSearchIndex( $maxLockTime, $callback, $dbw, $results)
Perform a search index update with locking.
static loadFromPageId( $db, $pageid, $id=0)
Load either the current, or a specified, revision that&#39;s attached to a given page.
Definition: Revision.php:260
setBatchSize( $s=0)
Set the batch size.
$wgDBuser
Database username.
loadSpecialVars()
Handle the special variables that are global to all scripts.
$wgShowExceptionDetails
If set to true, uncaught exceptions will print the exception message and a complete stack trace to ou...
wfEntryPointCheck( $format='text', $scriptPath='/')
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.
hasOption( $name)
Checks to see if a particular option exists.
relockSearchindex( $db)
Unlock and lock again Since the lock is low-priority, queued reads will be able to complete...
loadWithArgv( $argv)
Load params and arguments from a given array of command-line arguments.
wfIsWindows()
Check if the operating system is Windows.
outputChanneled( $msg, $channel=null)
Message outputter with channeled message support.
const DB_MASTER
Definition: defines.php:26
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
array $requiredExtensions
rollback( $fname=__METHOD__, $flush='')
Rollback a transaction previously started using begin().
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
Definition: hooks.txt:2217
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. '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
Definition: hooks.txt:1980
$maintClass
Definition: Maintenance.php:44
if( $line===false) $args
Definition: cdb.php:64
cleanupChanneled()
Clean up channeled output.
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
static replaceStubInstance(Profiler $profiler)
Replace the current profiler with $profiler if no non-stub profiler is set.
Definition: Profiler.php:98
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
Definition: hooks.txt:780
supportsOption( $name)
Checks to see if a particular option in supported.
Fake maintenance wrapper, mostly used for the web installer/updater.
activateProfiler()
Activate the profiler (assuming $wgProfiler is set)
static requireTestsAutoloader()
Call this to set up the autoloader to allow classes to be used from the tests directory.
hasArg( $argId=0)
Does a given argument exist?
$wgTrxProfilerLimits
Performance expectations for DB usage.
Interface for configuration instances.
Definition: Config.php:28
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
Definition: hooks.txt:2217
$mAllowUnregisteredOptions
$self
$res
Definition: database.txt:21
float $lastReplicationWait
UNIX timestamp.
addDescription( $text)
Set the description text.
const DB_ADMIN
Definition: Maintenance.php:87
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.
deleteOption( $name)
Remove an option.
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
Definition: hooks.txt:1982
$wgDBservers
Database load balancer This is a two-dimensional array, an array of server info structures Fields are...
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 null
Definition: hooks.txt:780
addArg( $arg, $description, $required=true)
Add some args that are needed.
globals()
Potentially debug globals.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
adjustMemoryLimit()
Adjusts PHP&#39;s memory limit to better suit our needs, if needed.
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
$GLOBALS['IP']
commit( $fname=__METHOD__, $flush='')
Commits a transaction previously started using begin().
output( $out, $channel=null)
Throw some output to the user.
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
Definition: hooks.txt:1766
resource $fileHandle
Used when creating separate schema files.
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
Definition: distributors.txt:9
unlockSearchindex( $db)
Unlock the tables.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:123
static findInDefaultPaths( $names, $versionInfo=false)
Same as locateExecutable(), but checks in getPossibleBinPaths() by default.
static shouldExecute()
Should we execute the maintenance script, or just allow it to be included as a standalone class...
static tryOpportunisticExecute( $mode='run')
Run all deferred updates immediately if there are no DB writes active.
const DB_STD
Definition: Maintenance.php:86
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
Definition: injection.txt:35
static getTermSize()
Get the terminal size as a two-element array where the first element is the width (number of columns)...
static readlineEmulation( $prompt)
Emulate readline()
static posix_isatty( $fd)
Wrapper for posix_isatty() We default as considering stdin a tty (for nice readline methods) but trea...
Class for scripts that perform database maintenance and want to log the update in updatelog so we can...
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
$wgDBadminuser
Separate username for maintenance tasks.
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
memoryLimit()
Normally we disable the memory_limit when running admin scripts.
$wgProfileLimit
Only record profiling info for pages that took longer than this.
static emitBufferedStatsdData(IBufferingStatsdDataFactory $stats, Config $config)
Send out any buffered statsd data according to sampling rules.
Definition: MediaWiki.php:933
int $mBatchSize
Batch size.
getBatchSize()
Returns batch size.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
$line
Definition: cdb.php:59
global $wgCommandLineMode
setAgentAndTriggers()
Set triggers like when to try to run deferred updates.
$f
Definition: router.php:79
countDown( $seconds)
Count down from $seconds to zero on the terminal, with a one-second pause between showing each number...
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
Definition: logger.txt:5
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getStdin( $len=null)
Return input from stdin.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
$wgServer
URL of the server.
$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.
const SCHEMA_COMPAT_READ_OLD
Definition: Defines.php:281
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
purgeRedundantText( $delete=true)
Support function for cleaning up redundant text records.
$wgProfiler
Profiler configuration.
validateParamsAndArgs()
Run some validation checks on the params, etc.
Config $config
Accessible via getConfig()
IMaintainableDatabase $mDb
Used by getDB() / setDB()
loadParamsAndArgs( $self=null, $opts=null, $args=null)
Process command line arguments $mOptions becomes an array with keys set to the option names $mArgs be...
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
public function execute()
Definition: maintenance.txt:45
__construct()
Default constructor.
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
setAllowUnregisteredOptions( $allow)
Sets whether to allow unregistered options, which are options passed to a script that do not match an...
$wgShowHostnames
Expose backend server host names through the API and various HTML comments.