Don't check namespace in SpecialWantedtemplates
[lhc/web/wiklou.git] / maintenance / updateCollation.php
1 <?php
2 /**
3 * Find all rows in the categorylinks table whose collation is out-of-date
4 * (cl_collation != $wgCategoryCollation) and repopulate cl_sortkey
5 * using the page title and cl_sortkey_prefix.
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
21 *
22 * @file
23 * @ingroup Maintenance
24 * @author Aryeh Gregor (Simetrical)
25 */
26
27 require_once __DIR__ . '/Maintenance.php';
28
29 /**
30 * Maintenance script that will find all rows in the categorylinks table
31 * whose collation is out-of-date.
32 *
33 * @ingroup Maintenance
34 */
35 class UpdateCollation extends Maintenance {
36 const BATCH_SIZE = 10000; // Number of rows to process in one batch
37 const SYNC_INTERVAL = 20; // Wait for slaves after this many batches
38
39 public $sizeHistogram = array();
40
41 public function __construct() {
42 parent::__construct();
43
44 global $wgCategoryCollation;
45 $this->mDescription = <<<TEXT
46 This script will find all rows in the categorylinks table whose collation is
47 out-of-date (cl_collation != '$wgCategoryCollation') and repopulate cl_sortkey
48 using the page title and cl_sortkey_prefix. If all collations are
49 up-to-date, it will do nothing.
50 TEXT;
51
52 $this->addOption( 'force', 'Run on all rows, even if the collation is ' .
53 'supposed to be up-to-date.' );
54 $this->addOption( 'previous-collation', 'Set the previous value of ' .
55 '$wgCategoryCollation here to speed up this script, especially if your ' .
56 'categorylinks table is large. This will only update rows with that ' .
57 'collation, though, so it may miss out-of-date rows with a different, ' .
58 'even older collation.', false, true );
59 $this->addOption( 'target-collation', 'Set this to the new collation type to ' .
60 'use instead of $wgCategoryCollation. Usually you should not use this, ' .
61 'you should just update $wgCategoryCollation in LocalSettings.php.',
62 false, true );
63 $this->addOption( 'dry-run', 'Don\'t actually change the collations, just ' .
64 'compile statistics.' );
65 $this->addOption( 'verbose-stats', 'Show more statistics.' );
66 }
67
68 public function execute() {
69 global $wgCategoryCollation;
70
71 $dbw = $this->getDB( DB_MASTER );
72 $force = $this->getOption( 'force' );
73 $dryRun = $this->getOption( 'dry-run' );
74 $verboseStats = $this->getOption( 'verbose-stats' );
75 if ( $this->hasOption( 'target-collation' ) ) {
76 $collationName = $this->getOption( 'target-collation' );
77 $collation = Collation::factory( $collationName );
78 } else {
79 $collationName = $wgCategoryCollation;
80 $collation = Collation::singleton();
81 }
82
83 // Collation sanity check: in some cases the constructor will work,
84 // but this will raise an exception, breaking all category pages
85 $collation->getFirstLetter( 'MediaWiki' );
86
87 $options = array(
88 'LIMIT' => self::BATCH_SIZE,
89 'ORDER BY' => 'cl_to, cl_type, cl_from',
90 'STRAIGHT_JOIN',
91 );
92
93 if ( $force || $dryRun ) {
94 $collationConds = array();
95 } else {
96 if ( $this->hasOption( 'previous-collation' ) ) {
97 $collationConds['cl_collation'] = $this->getOption( 'previous-collation' );
98 } else {
99 $collationConds = array( 0 =>
100 'cl_collation != ' . $dbw->addQuotes( $collationName )
101 );
102 }
103
104 $count = $dbw->estimateRowCount(
105 'categorylinks',
106 '*',
107 $collationConds,
108 __METHOD__
109 );
110 // Improve estimate if feasible
111 if ( $count < 1000000 ) {
112 $count = $dbw->selectField(
113 'categorylinks',
114 'COUNT(*)',
115 $collationConds,
116 __METHOD__
117 );
118 }
119 if ( $count == 0 ) {
120 $this->output( "Collations up-to-date.\n" );
121
122 return;
123 }
124 $this->output( "Fixing collation for $count rows.\n" );
125 }
126
127 $count = 0;
128 $batchCount = 0;
129 $batchConds = array();
130 do {
131 $this->output( "Selecting next " . self::BATCH_SIZE . " rows..." );
132 $res = $dbw->select(
133 array( 'categorylinks', 'page' ),
134 array( 'cl_from', 'cl_to', 'cl_sortkey_prefix', 'cl_collation',
135 'cl_sortkey', 'cl_type', 'page_namespace', 'page_title'
136 ),
137 array_merge( $collationConds, $batchConds, array( 'cl_from = page_id' ) ),
138 __METHOD__,
139 $options
140 );
141 $this->output( " processing..." );
142
143 if ( !$dryRun ) {
144 $dbw->begin( __METHOD__ );
145 }
146 foreach ( $res as $row ) {
147 $title = Title::newFromRow( $row );
148 if ( !$row->cl_collation ) {
149 # This is an old-style row, so the sortkey needs to be
150 # converted.
151 if ( $row->cl_sortkey == $title->getText()
152 || $row->cl_sortkey == $title->getPrefixedText()
153 ) {
154 $prefix = '';
155 } else {
156 # Custom sortkey, use it as a prefix
157 $prefix = $row->cl_sortkey;
158 }
159 } else {
160 $prefix = $row->cl_sortkey_prefix;
161 }
162 # cl_type will be wrong for lots of pages if cl_collation is 0,
163 # so let's update it while we're here.
164 if ( $title->getNamespace() == NS_CATEGORY ) {
165 $type = 'subcat';
166 } elseif ( $title->getNamespace() == NS_FILE ) {
167 $type = 'file';
168 } else {
169 $type = 'page';
170 }
171 $newSortKey = $collation->getSortKey(
172 $title->getCategorySortkey( $prefix ) );
173 if ( $verboseStats ) {
174 $this->updateSortKeySizeHistogram( $newSortKey );
175 }
176
177 if ( !$dryRun ) {
178 $dbw->update(
179 'categorylinks',
180 array(
181 'cl_sortkey' => $newSortKey,
182 'cl_sortkey_prefix' => $prefix,
183 'cl_collation' => $collationName,
184 'cl_type' => $type,
185 'cl_timestamp = cl_timestamp',
186 ),
187 array( 'cl_from' => $row->cl_from, 'cl_to' => $row->cl_to ),
188 __METHOD__
189 );
190 }
191 if ( $row ) {
192 $batchConds = array( $this->getBatchCondition( $row, $dbw ) );
193 }
194 }
195 if ( !$dryRun ) {
196 $dbw->commit( __METHOD__ );
197 }
198
199 $count += $res->numRows();
200 $this->output( "$count done.\n" );
201
202 if ( !$dryRun && ++$batchCount % self::SYNC_INTERVAL == 0 ) {
203 $this->output( "Waiting for slaves ... " );
204 wfWaitForSlaves();
205 $this->output( "done\n" );
206 }
207 } while ( $res->numRows() == self::BATCH_SIZE );
208
209 $this->output( "$count rows processed\n" );
210
211 if ( $verboseStats ) {
212 $this->output( "\n" );
213 $this->showSortKeySizeHistogram();
214 }
215 }
216
217 /**
218 * Return an SQL expression selecting rows which sort above the given row,
219 * assuming an ordering of cl_to, cl_type, cl_from
220 * @param stdClass $row
221 * @param DatabaseBase $dbw
222 * @return string
223 */
224 function getBatchCondition( $row, $dbw ) {
225 $fields = array( 'cl_to', 'cl_type', 'cl_from' );
226 $first = true;
227 $cond = false;
228 $prefix = false;
229 foreach ( $fields as $field ) {
230 $encValue = $dbw->addQuotes( $row->$field );
231 $inequality = "$field > $encValue";
232 $equality = "$field = $encValue";
233 if ( $first ) {
234 $cond = $inequality;
235 $prefix = $equality;
236 $first = false;
237 } else {
238 $cond .= " OR ($prefix AND $inequality)";
239 $prefix .= " AND $equality";
240 }
241 }
242
243 return $cond;
244 }
245
246 function updateSortKeySizeHistogram( $key ) {
247 $length = strlen( $key );
248 if ( !isset( $this->sizeHistogram[$length] ) ) {
249 $this->sizeHistogram[$length] = 0;
250 }
251 $this->sizeHistogram[$length]++;
252 }
253
254 function showSortKeySizeHistogram() {
255 $maxLength = max( array_keys( $this->sizeHistogram ) );
256 if ( $maxLength == 0 ) {
257 return;
258 }
259 $numBins = 20;
260 $coarseHistogram = array_fill( 0, $numBins, 0 );
261 $coarseBoundaries = array();
262 $boundary = 0;
263 for ( $i = 0; $i < $numBins - 1; $i++ ) {
264 $boundary += $maxLength / $numBins;
265 $coarseBoundaries[$i] = round( $boundary );
266 }
267 $coarseBoundaries[$numBins - 1] = $maxLength + 1;
268 $raw = '';
269 for ( $i = 0; $i <= $maxLength; $i++ ) {
270 if ( $raw !== '' ) {
271 $raw .= ', ';
272 }
273 if ( !isset( $this->sizeHistogram[$i] ) ) {
274 $val = 0;
275 } else {
276 $val = $this->sizeHistogram[$i];
277 }
278 for ( $coarseIndex = 0; $coarseIndex < $numBins - 1; $coarseIndex++ ) {
279 if ( $coarseBoundaries[$coarseIndex] > $i ) {
280 $coarseHistogram[$coarseIndex] += $val;
281 break;
282 }
283 }
284 if ( $coarseIndex == $numBins - 1 ) {
285 $coarseHistogram[$coarseIndex] += $val;
286 }
287 $raw .= $val;
288 }
289
290 $this->output( "Sort key size histogram\nRaw data: $raw\n\n" );
291
292 $maxBinVal = max( $coarseHistogram );
293 $scale = 60 / $maxBinVal;
294 $prevBoundary = 0;
295 for ( $coarseIndex = 0; $coarseIndex < $numBins; $coarseIndex++ ) {
296 if ( !isset( $coarseHistogram[$coarseIndex] ) ) {
297 $val = 0;
298 } else {
299 $val = $coarseHistogram[$coarseIndex];
300 }
301 $boundary = $coarseBoundaries[$coarseIndex];
302 $this->output( sprintf( "%-10s %-10d |%s\n",
303 $prevBoundary . '-' . ( $boundary - 1 ) . ': ',
304 $val,
305 str_repeat( '*', $scale * $val ) ) );
306 $prevBoundary = $boundary;
307 }
308 }
309 }
310
311 $maintClass = "UpdateCollation";
312 require_once RUN_MAINTENANCE_IF_MAIN;