MediaWiki  REL1_31
Go to the documentation of this file.
1 <?php
27 require_once __DIR__ . '/Maintenance.php';
34  function __construct() {
35  parent::__construct();
37  $this->addDescription( 'Pass through all users and change one of their options.
38 The new option is NOT validated.' );
40  $this->addOption( 'list', 'List available user options and their default value' );
41  $this->addOption( 'usage', 'Report all options statistics or just one if you specify it' );
42  $this->addOption( 'old', 'The value to look for', false, true );
43  $this->addOption( 'new', 'Rew value to update users with', false, true );
44  $this->addOption( 'nowarn', 'Hides the 5 seconds warning' );
45  $this->addOption( 'dry', 'Do not save user settings back to database' );
46  $this->addArg( 'option name', 'Name of the option to change or provide statistics about', false );
47  }
52  public function execute() {
53  if ( $this->hasOption( 'list' ) ) {
54  $this->listAvailableOptions();
55  } elseif ( $this->hasOption( 'usage' ) ) {
56  $this->showUsageStats();
57  } elseif ( $this->hasOption( 'old' )
58  && $this->hasOption( 'new' )
59  && $this->hasArg( 0 )
60  ) {
61  $this->updateOptions();
62  } else {
63  $this->maybeHelp( /* force = */ true );
64  }
65  }
70  private function listAvailableOptions() {
71  $def = User::getDefaultOptions();
72  ksort( $def );
73  $maxOpt = 0;
74  foreach ( $def as $opt => $value ) {
75  $maxOpt = max( $maxOpt, strlen( $opt ) );
76  }
77  foreach ( $def as $opt => $value ) {
78  $this->output( sprintf( "%-{$maxOpt}s: %s\n", $opt, $value ) );
79  }
80  }
85  private function showUsageStats() {
86  $option = $this->getArg( 0 );
88  $ret = [];
89  $defaultOptions = User::getDefaultOptions();
91  // We list user by user_id from one of the replica DBs
92  $dbr = wfGetDB( DB_REPLICA );
93  $result = $dbr->select( 'user',
94  [ 'user_id' ],
95  [],
96  __METHOD__
97  );
99  foreach ( $result as $id ) {
100  $user = User::newFromId( $id->user_id );
102  // Get the options and update stats
103  if ( $option ) {
104  if ( !array_key_exists( $option, $defaultOptions ) ) {
105  $this->fatalError( "Invalid user option. Use --list to see valid choices\n" );
106  }
108  $userValue = $user->getOption( $option );
109  if ( $userValue <> $defaultOptions[$option] ) {
110  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
111  @$ret[$option][$userValue]++;
112  }
113  } else {
115  foreach ( $defaultOptions as $name => $defaultValue ) {
116  $userValue = $user->getOption( $name );
117  if ( $userValue != $defaultValue ) {
118  // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
119  @$ret[$name][$userValue]++;
120  }
121  }
122  }
123  }
125  foreach ( $ret as $optionName => $usageStats ) {
126  $this->output( "Usage for <$optionName> (default: '{$defaultOptions[$optionName]}'):\n" );
127  foreach ( $usageStats as $value => $count ) {
128  $this->output( " $count user(s): '$value'\n" );
129  }
130  print "\n";
131  }
132  }
137  private function updateOptions() {
138  $dryRun = $this->hasOption( 'dry' );
139  $option = $this->getArg( 0 );
140  $from = $this->getOption( 'old' );
141  $to = $this->getOption( 'new' );
143  if ( !$dryRun ) {
144  $this->warn( $option, $from, $to );
145  }
147  // We list user by user_id from one of the replica DBs
148  // @todo: getting all users in one query does not scale
149  $dbr = wfGetDB( DB_REPLICA );
150  $result = $dbr->select( 'user',
151  [ 'user_id' ],
152  [],
153  __METHOD__
154  );
156  foreach ( $result as $id ) {
157  $user = User::newFromId( $id->user_id );
159  $curValue = $user->getOption( $option );
160  $username = $user->getName();
162  if ( $curValue == $from ) {
163  $this->output( "Setting {$option} for $username from '{$from}' to '{$to}'): " );
165  // Change value
166  $user->setOption( $option, $to );
168  // Will not save the settings if run with --dry
169  if ( !$dryRun ) {
170  $user->saveSettings();
171  }
172  $this->output( " OK\n" );
173  } else {
174  $this->output( "Not changing '$username' using <{$option}> = '$curValue'\n" );
175  }
176  }
177  }
186  private function warn( $option, $from, $to ) {
187  if ( $this->hasOption( 'nowarn' ) ) {
188  return;
189  }
191  $this->output( <<<WARN
192 The script is about to change the options for ALL USERS in the database.
193 Users with option <$option> = '$from' will be made to use '$to'.
195 Abort with control-c in the next five seconds....
196 WARN
197  );
198  $this->countDown( 5 );
199  }
200 }
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:247
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:614
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
We use the convention $dbr for read and $dbw for write to help you keep track of whether the database object is a the world will explode Or to be a subsequent write query which succeeded on the master may fail when replicated to the slave due to a unique key collision Replication on the slave will stop and it may take hours to repair the database and get it back online Setting read_only in my cnf on the slave will avoid this but given the dire we prefer to have as many checks as possible We provide a but the wrapper functions like please read the documentation for except in special pages derived from QueryPage It s a common pitfall for new developers to submit code containing SQL queries which examine huge numbers of rows Remember that COUNT * is(N), counting rows in atable is like counting beans in a bucket.------------------------------------------------------------------------ Replication------------------------------------------------------------------------The largest installation of MediaWiki, Wikimedia, uses a large set ofslave MySQL servers replicating writes made to a master MySQL server. Itis important to understand the issues associated with this setup if youwant to write code destined for Wikipedia.It 's often the case that the best algorithm to use for a given taskdepends on whether or not replication is in use. Due to our unabashedWikipedia-centrism, we often just use the replication-friendly version, but if you like, you can use wfGetLB() ->getServerCount() > 1 tocheck to see if replication is in use.===Lag===Lag primarily occurs when large write queries are sent to the master.Writes on the master are executed in parallel, but they are executed inserial when they are replicated to the slaves. The master writes thequery to the binlog when the transaction is committed. The slaves pollthe binlog and start executing the query as soon as it appears. They canservice reads while they are performing a write query, but will not readanything more from the binlog and thus will perform no more writes. Thismeans that if the write query runs for a long time, the slaves will lagbehind the master for the time it takes for the write query to complete.Lag can be exacerbated by high read load. MediaWiki 's load balancer willstop sending reads to a slave when it is lagged by more than 30 seconds.If the load ratios are set incorrectly, or if there is too much loadgenerally, this may lead to a slave permanently hovering around 30seconds lag.If all slaves are lagged by more than 30 seconds, MediaWiki will stopwriting to the database. All edits and other write operations will berefused, with an error returned to the user. This gives the slaves achance to catch up. Before we had this mechanism, the slaves wouldregularly lag by several minutes, making review of recent editsdifficult.In addition to this, MediaWiki attempts to ensure that the user seesevents occurring on the wiki in chronological order. A few seconds of lagcan be tolerated, as long as the user sees a consistent picture fromsubsequent requests. This is done by saving the master binlog positionin the session, and then at the start of each request, waiting for theslave to catch up to that position before doing any reads from it. Ifthis wait times out, reads are allowed anyway, but the request isconsidered to be in "lagged slave mode". Lagged slave mode can bechecked by calling wfGetLB() ->getLaggedSlaveMode(). The onlypractical consequence at present is a warning displayed in the pagefooter.===Lag avoidance===To avoid excessive lag, queries which write large numbers of rows shouldbe split up, generally to write one row at a time. Multi-row INSERT ...SELECT queries are the worst offenders should be avoided altogether.Instead do the select first and then the insert.===Working with lag===Despite our best efforts, it 's not practical to guarantee a low-lagenvironment. Lag will usually be less than one second, but mayoccasionally be up to 30 seconds. For scalability, it 's very importantto keep load on the master low, so simply sending all your queries tothe master is not the answer. So when you have a genuine need forup-to-date data, the following approach is advised:1) Do a quick query to the master for a sequence number or timestamp 2) Run the full query on the slave and check if it matches the data you gotfrom the master 3) If it doesn 't, run the full query on the masterTo avoid swamping the master every time the slaves lag, use of thisapproach should be kept to a minimum. In most cases you should just readfrom the slave and let the user deal with the delay.------------------------------------------------------------------------ Lock contention------------------------------------------------------------------------Due to the high write rate on Wikipedia(and some other wikis), MediaWiki developers need to be very careful to structure their writesto avoid long-lasting locks. By default, MediaWiki opens a transactionat the first query, and commits it before the output is sent. Locks willbe held from the time when the query is done until the commit. So youcan reduce lock time by doing as much processing as possible before youdo your write queries.Often this approach is not good enough, and it becomes necessary toenclose small groups of queries in their own transaction. Use thefollowing syntax:$dbw=wfGetDB(DB_MASTER
Definition: postprocess-phan.php:119
maybeHelp( $force=false)
Maybe show the help.
Definition: Maintenance.php:999
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:439
addDescription( $text)
Set the description text.
Definition: Maintenance.php:291
Default constructor.
Definition: userOptions.php:34
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 change
Definition: distributors.txt:9
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 noclasses & $ret
Definition: hooks.txt:2005
Definition: maintenance.txt:50
hasArg( $argId=0)
Does a given argument exist?
Definition: Maintenance.php:300
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the database
Definition: design.txt:13
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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! 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:1993
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:37
static getDefaultOptions()
Combine the language default options with any site-specific options and add the default language vari...
Definition: User.php:1722
Definition: testCompression.php:50
Definition: userOptions.php:202
Definition: userOptions.php:32
Do the actual work.
Definition: userOptions.php:52
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2812
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:219
Definition: defines.php:25
countDown( $seconds)
Count down from $seconds to zero on the terminal, with a one-second pause between showing each number...
Definition: Maintenance.php:1487
</td >< td > &</td >< td > t want your writing to be edited mercilessly and redistributed at will
Definition: All_system_messages.txt:914
Definition: styleTest.css.php:45
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing options(say) and put it in one place. Instead of having little title-reversing if-blocks spread all over the codebase in showAnArticle
List options usage.
Definition: userOptions.php:85
Change our users options.
Definition: userOptions.php:137
List default options and their value.
Definition: userOptions.php:70
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for and distribution as defined by Sections through of this document Licensor shall mean the copyright owner or entity authorized by the copyright owner that is granting the License Legal Entity shall mean the union of the acting entity and all other entities that control are controlled by or are under common control with that entity For the purposes of this definition control direct or to cause the direction or management of such whether by contract or including but not limited to software source documentation and configuration files Object form shall mean any form resulting from mechanical transformation or translation of a Source including but not limited to compiled object generated and conversions to other media types Work shall mean the work of whether in Source or Object made available under the as indicated by a copyright notice that is included in or attached to the whether in Source or Object that is based or other modifications as a an original work of authorship For the purposes of this Derivative Works shall not include works that remain separable or merely the Work and Derivative Works thereof Contribution shall mean any work of including the original version of the Work and any modifications or additions to that Work or Derivative Works that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner For the purposes of this submitted means any form of or written communication sent to the Licensor or its including but not limited to communication on electronic mailing source code control and issue tracking systems that are managed or on behalf the Licensor for the purpose of discussing and improving the but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as Not a Contribution Contributor shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work Grant of Copyright License Subject to the terms and conditions of this each Contributor hereby grants to You a non no royalty irrevocable copyright license to prepare Derivative Works publicly publicly and distribute the Work and such Derivative Works in Source or Object form Grant of Patent License Subject to the terms and conditions of this each Contributor hereby grants to You a non no royalty have made
Definition: APACHE-LICENSE-2.0.txt:77
Definition: opensearch_desc.php:46
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:254
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:271
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:22
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:785
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:388
null for the wiki Added in
Definition: hooks.txt:1591
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:56
hasOption( $name)
Checks to see if a particular param exists.
Definition: Maintenance.php:240
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:310
warn( $option, $from, $to)
The warning message and countdown.
Definition: userOptions.php:186
span about
Definition: parserTests.txt:17699