MediaWiki REL1_30
recountCategories.php
Go to the documentation of this file.
1<?php
24require_once __DIR__ . '/Maintenance.php';
25
27
39 public function __construct() {
40 parent::__construct();
41 $this->addDescription( <<<'TEXT'
42This script refreshes the category membership counts stored in the category
43table. As time passes, these counts often drift from the actual number of
44category members. The script identifies rows where the value in the category
45table does not match the number of categorylinks rows for that category, and
46updates the category table accordingly.
47
48To fully refresh the data in the category table, you need to run this script
49three times: once in each mode. Alternatively, just one mode can be run if
50required.
51TEXT
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';
172require_once RUN_MAINTENANCE_IF_MAIN;
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
setBatchSize( $s=0)
Set the batch size.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Maintenance script that refreshes category membership counts in the category table.
__construct()
Default constructor.
execute()
Do the actual work.
if(! $regexes) $dbr
Definition cleanup.php:94
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
$res
Definition database.txt:21
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:5
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)
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:16
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 and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling output() to send it all. It could be easily changed to send incrementally if that becomes useful
namespace being checked & $result
Definition hooks.txt:2293
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults error
Definition hooks.txt:2581
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:1389
require_once RUN_MAINTENANCE_IF_MAIN
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:26