MediaWiki  1.30.0
recountCategories.php
Go to the documentation of this file.
1 <?php
24 require_once __DIR__ . '/Maintenance.php';
25 
27 
39  public function __construct() {
40  parent::__construct();
41  $this->addDescription( <<<'TEXT'
42 This script refreshes the category membership counts stored in the category
43 table. As time passes, these counts often drift from the actual number of
44 category members. The script identifies rows where the value in the category
45 table does not match the number of categorylinks rows for that category, and
46 updates the category table accordingly.
47 
48 To fully refresh the data in the category table, you need to run this script
49 three times: once in each mode. Alternatively, just one mode can be run if
50 required.
51 TEXT
52  );
53  $this->addOption(
54  'mode',
55  '(REQUIRED) Which category count column to recompute: "pages", "subcats" or "files".',
56  true,
57  true
58  );
59  $this->addOption(
60  'begin',
61  'Only recount categories with cat_id greater than the given value',
62  false,
63  true
64  );
65  $this->addOption(
66  'throttle',
67  'Wait this many milliseconds after each batch. Default: 0',
68  false,
69  true
70  );
71 
72  $this->setBatchSize( 500 );
73  }
74 
75  public function execute() {
76  $this->mode = $this->getOption( 'mode' );
77  if ( !in_array( $this->mode, [ 'pages', 'subcats', 'files' ] ) ) {
78  $this->error( 'Please specify a valid mode: one of "pages", "subcats" or "files".', 1 );
79  }
80 
81  $this->minimumId = intval( $this->getOption( 'begin', 0 ) );
82 
83  // do the work, batch by batch
84  $affectedRows = 0;
85  while ( ( $result = $this->doWork() ) !== false ) {
86  $affectedRows += $result;
87  usleep( $this->getOption( 'throttle', 0 ) * 1000 );
88  }
89 
90  $this->output( "Done! Updated the {$this->mode} counts of $affectedRows categories.\n" .
91  "Now run the script using the other --mode options if you haven't already.\n" );
92  if ( $this->mode === 'pages' ) {
93  $this->output(
94  "Also run 'php cleanupEmptyCategories.php --mode remove' to remove empty,\n" .
95  "nonexistent categories from the category table.\n\n" );
96  }
97  }
98 
99  protected function doWork() {
100  $this->output( "Finding up to {$this->mBatchSize} drifted rows " .
101  "starting at cat_id {$this->minimumId}...\n" );
102 
103  $countingConds = [ 'cl_to = cat_title' ];
104  if ( $this->mode === 'subcats' ) {
105  $countingConds['cl_type'] = 'subcat';
106  } elseif ( $this->mode === 'files' ) {
107  $countingConds['cl_type'] = 'file';
108  }
109 
110  $dbr = $this->getDB( DB_REPLICA, 'vslow' );
111  $countingSubquery = $dbr->selectSQLText( 'categorylinks',
112  'COUNT(*)',
113  $countingConds,
114  __METHOD__ );
115 
116  // First, let's find out which categories have drifted and need to be updated.
117  // The query counts the categorylinks for each category on the replica DB,
118  // but this data can't be used for updating the master, so we don't include it
119  // in the results.
120  $idsToUpdate = $dbr->selectFieldValues( 'category',
121  'cat_id',
122  [
123  'cat_id > ' . $this->minimumId,
124  "cat_{$this->mode} != ($countingSubquery)"
125  ],
126  __METHOD__,
127  [ 'LIMIT' => $this->mBatchSize ]
128  );
129  if ( !$idsToUpdate ) {
130  return false;
131  }
132  $this->output( "Updating cat_{$this->mode} field on " .
133  count( $idsToUpdate ) . " rows...\n" );
134 
135  // In the next batch, start where this query left off. The rows selected
136  // in this iteration shouldn't be selected again after being updated, but
137  // we still keep track of where we are up to, as extra protection against
138  // infinite loops.
139  $this->minimumId = end( $idsToUpdate );
140 
141  // Now, on master, find the correct counts for these categories.
142  $dbw = $this->getDB( DB_MASTER );
143  $res = $dbw->select( 'category',
144  [ 'cat_id', 'count' => "($countingSubquery)" ],
145  [ 'cat_id' => $idsToUpdate ],
146  __METHOD__ );
147 
148  // Update the category counts on the rows we just identified.
149  // This logic is equivalent to Category::refreshCounts, except here, we
150  // don't remove rows when cat_pages is zero and the category description page
151  // doesn't exist - instead we print a suggestion to run
152  // cleanupEmptyCategories.php.
153  $affectedRows = 0;
154  foreach ( $res as $row ) {
155  $dbw->update( 'category',
156  [ "cat_{$this->mode}" => $row->count ],
157  [
158  'cat_id' => $row->cat_id,
159  "cat_{$this->mode} != {$row->count}",
160  ],
161  __METHOD__ );
162  $affectedRows += $dbw->affectedRows();
163  }
164 
165  MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
166 
167  return $affectedRows;
168  }
169 }
170 
171 $maintClass = 'RecountCategories';
172 require_once RUN_MAINTENANCE_IF_MAIN;
you
and give any other recipients of the Program a copy of this License along with the Program You may charge a fee for the physical act of transferring a and you may at your option offer warranty protection in exchange for a fee You may modify your copy or copies of the Program or any portion of thus forming a work based on the and copy and distribute such modifications or work under the terms of Section provided that you also meet all of these that in whole or in part contains or is derived from the Program or any part to be licensed as a whole at no charge to all third parties under the terms of this License c If the modified program normally reads commands interactively when you must cause when started running for such interactive use in the most ordinary to print or display an announcement including an appropriate copyright notice and a notice that there is no and telling the user how to view a copy of this and can be reasonably considered independent and separate works in then this and its do not apply to those sections when you distribute them as separate works But when you distribute the same sections as part of a whole which is a work based on the the distribution of the whole must be on the terms of this whose permissions for other licensees extend to the entire and thus to each and every part regardless of who wrote it it is not the intent of this section to claim rights or contest your rights to work written entirely by you
Definition: COPYING.txt:117
RecountCategories\__construct
__construct()
Default constructor.
Definition: recountCategories.php:39
counts
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view counts
Definition: deferred.txt:4
RecountCategories
Maintenance script that refreshes category membership counts in the category table.
Definition: recountCategories.php:38
captcha-old.count
count
Definition: captcha-old.py:249
stored
The ContentHandler facility adds support for arbitrary content types on wiki instead of relying on wikitext for everything It was introduced in MediaWiki Each kind of stored
Definition: contenthandler.txt:5
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:287
$result
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 '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:1963
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
RUN_MAINTENANCE_IF_MAIN
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
$res
$res
Definition: database.txt:21
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
RecountCategories\execute
execute()
Do the actual work.
Definition: recountCategories.php:75
php
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
updates
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these updates(as a Java servelet could)
script
script(document.cookie)%253c/script%253e</pre ></div > !! end !! test XSS is escaped(inline) !!input< source lang
table
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if so it s not worth the trouble Since there is a job queue in the jobs table
Definition: deferred.txt:11
in
null for the wiki Added in
Definition: hooks.txt:1581
mode
if write to the Free Software Franklin Fifth MA USA Also add information on how to contact you by electronic and paper mail If the program is make it output a short notice like this when it starts in an interactive mode
Definition: COPYING.txt:307
not
if not
Definition: COPYING.txt:307
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:215
value
$status value
Definition: SyntaxHighlight.class.php:315
Alternatively
passed in as a query string parameter to the various URLs constructed here(i.e. $prevlink) $ldel you ll need to handle error etc yourself Alternatively
Definition: hooks.txt:1265
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
DB_MASTER
const DB_MASTER
Definition: defines.php:26
run
and give any other recipients of the Program a copy of this License along with the Program You may charge a fee for the physical act of transferring a and you may at your option offer warranty protection in exchange for a fee You may modify your copy or copies of the Program or any portion of thus forming a work based on the and copy and distribute such modifications or work under the terms of Section provided that you also meet all of these that in whole or in part contains or is derived from the Program or any part to be licensed as a whole at no charge to all third parties under the terms of this License c If the modified program normally reads commands interactively when run
Definition: COPYING.txt:87
and
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
Maintenance\getOption
getOption( $name, $default=null)
Get an option, or return the default.
Definition: Maintenance.php:250
$dbr
if(! $regexes) $dbr
Definition: cleanup.php:94
as
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
Maintenance\getDB
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1251
from
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 from
Definition: APACHE-LICENSE-2.0.txt:43
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:392
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:373
RecountCategories\doWork
doWork()
Definition: recountCategories.php:99
of
globals txt Globals are evil The original MediaWiki code relied on globals for processing context far too often MediaWiki development since then has been a story of slowly moving context out of global variables and into objects Storing processing context in object member variables allows those objects to be reused in a much more flexible way Consider the elegance of
Definition: globals.txt:10
that
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if that
Definition: deferred.txt:11
MediaWikiServices
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
$maintClass
$maintClass
Definition: recountCategories.php:161
data
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of data
Definition: hooks.txt:6
Maintenance\setBatchSize
setBatchSize( $s=0)
Set the batch size.
Definition: Maintenance.php:314