Debian Codegraph @

maintenance/userOptions.php

raw symbols SCIP
1 <?php
2 /**
3 * Script to change users preferences on the fly.
4 *
5 * Made on an original idea by Fooey (freenode)
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 Antoine Musso <hashar at free dot fr>
25 */
26
27 use MediaWiki\User\User;
28 use MediaWiki\User\UserIdentityValue;
29 use Wikimedia\Rdbms\IExpression;
30 use Wikimedia\Rdbms\SelectQueryBuilder;
31
32 // @codeCoverageIgnoreStart
33 require_once __DIR__ . '/Maintenance.php';
34 // @codeCoverageIgnoreEnd
35
36 /**
37 * @ingroup Maintenance
38 */
39 class UserOptionsMaintenance extends Maintenance {
40
41 public function __construct() {
42 parent::__construct();
43
44 $this->addDescription( 'Pass through all users and change or delete one of their options.
45 The new option is NOT validated.' );
46
47 $this->addOption( 'list', 'List available user options and their default value' );
48 $this->addOption( 'usage', 'Report all options statistics or just one if you specify it' );
49 $this->addOption(
50 'old',
51 'The value to look for. If it is a default value for the option, pass --old-is-default as well.',
52 false, true, false, true
53 );
54 $this->addOption( 'old-is-default', 'If passed, --old is interpreted as a default value.' );
55 $this->addOption( 'new', 'New value to update users with', false, true );
56 $this->addOption( 'delete', 'Delete the option instead of updating' );
57 $this->addOption( 'delete-defaults', 'Delete user_properties row matching the default' );
58 $this->addOption( 'fromuserid', 'Start from this user ID when changing/deleting options',
59 false, true );
60 $this->addOption( 'touserid', 'Do not go beyond this user ID when changing/deleting options',
61 false, true );
62 $this->addOption( 'nowarn', 'Hides the 5 seconds warning' );
63 $this->addOption( 'dry', 'Do not save user settings back to database' );
64 $this->addArg( 'option name', 'Name of the option to change or provide statistics about', false );
65 $this->setBatchSize( 100 );
66 }
67
68 /**
69 * Do the actual work
70 */
71 public function execute() {
72 if ( $this->hasOption( 'list' ) ) {
73 $this->listAvailableOptions();
74 } elseif ( $this->hasOption( 'usage' ) ) {
75 $this->showUsageStats();
76 } elseif ( $this->hasOption( 'old' )
77 && $this->hasOption( 'new' )
78 && $this->hasArg( 0 )
79 ) {
80 $this->updateOptions();
81 } elseif ( $this->hasOption( 'delete' ) ) {
82 $this->deleteOptions();
83 } elseif ( $this->hasOption( 'delete-defaults' ) ) {
84 $this->deleteDefaults();
85 } else {
86 $this->maybeHelp( true );
87 }
88 }
89
90 /**
91 * List default options and their value
92 */
93 private function listAvailableOptions() {
94 $userOptionsLookup = $this->getServiceContainer()->getUserOptionsLookup();
95 $def = $userOptionsLookup->getDefaultOptions( null );
96 ksort( $def );
97 $maxOpt = 0;
98 foreach ( $def as $opt => $value ) {
99 $maxOpt = max( $maxOpt, strlen( $opt ) );
100 }
101 foreach ( $def as $opt => $value ) {
102 $this->output( sprintf( "%-{$maxOpt}s: %s\n", $opt, $value ) );
103 }
104 }
105
106 /**
107 * List options usage
108 */
109 private function showUsageStats() {
110 $option = $this->getArg( 0 );
111
112 $ret = [];
113 $userOptionsLookup = $this->getServiceContainer()->getUserOptionsLookup();
114 $defaultOptions = $userOptionsLookup->getDefaultOptions();
115
116 if ( $option && !array_key_exists( $option, $defaultOptions ) ) {
117 $this->fatalError( "Invalid user option. Use --list to see valid choices\n" );
118 }
119
120 // We list user by user_id from one of the replica DBs
121 $dbr = $this->getServiceContainer()->getConnectionProvider()->getReplicaDatabase();
122
123 $result = $dbr->newSelectQueryBuilder()
124 ->select( [ 'user_id' ] )
125 ->from( 'user' )
126 ->caller( __METHOD__ )->fetchResultSet();
127
128 foreach ( $result as $id ) {
129 $user = User::newFromId( $id->user_id );
130
131 // Get the options and update stats
132 if ( $option ) {
133 $userValue = $userOptionsLookup->getOption( $user, $option );
134 if ( $userValue != $defaultOptions[$option] ) {
135 $ret[$option][$userValue] = ( $ret[$option][$userValue] ?? 0 ) + 1;
136 }
137 } else {
138 foreach ( $defaultOptions as $name => $defaultValue ) {
139 $userValue = $userOptionsLookup->getOption( $user, $name );
140 if ( $userValue != $defaultValue ) {
141 $ret[$name][$userValue] = ( $ret[$name][$userValue] ?? 0 ) + 1;
142 }
143 }
144 }
145 }
146
147 foreach ( $ret as $optionName => $usageStats ) {
148 $this->output( "Usage for <$optionName> (default: '{$defaultOptions[$optionName]}'):\n" );
149 foreach ( $usageStats as $value => $count ) {
150 $this->output( " $count user(s): '$value'\n" );
151 }
152 print "\n";
153 }
154 }
155
156 /**
157 * Change our users options
158 */
159 private function updateOptions() {
160 $dryRun = $this->hasOption( 'dry' );
161 $settingWord = $dryRun ? 'Would set' : 'Setting';
162 $option = $this->getArg( 0 );
163 $fromIsDefault = $this->hasOption( 'old-is-default' );
164 $from = $this->getOption( 'old' );
165 $to = $this->getOption( 'new' );
166
167 // The fromuserid parameter is inclusive, but iterating is easier with an exclusive
168 // range so convert it.
169 $fromUserId = (int)$this->getOption( 'fromuserid', 1 ) - 1;
170 $toUserId = (int)$this->getOption( 'touserid', 0 ) ?: null;
171 $fromAsText = implode( '|', $from );
172
173 if ( !$dryRun ) {
174 $forUsers = ( $fromUserId || $toUserId ) ? "some users (ID $fromUserId-$toUserId)" : 'ALL USERS';
175 $this->warn(
176 <<<WARN
177 The script is about to change the options for $forUsers in the database.
178 Users with option <$option> = '$fromAsText' will be made to use '$to'.
179
180 Abort with control-c in the next five seconds....
181 WARN
182 );
183 }
184
185 $userOptionsManager = $this->getServiceContainer()->getUserOptionsManager();
186 $tempUserConfig = $this->getServiceContainer()->getTempUserConfig();
187 $dbr = $this->getReplicaDB();
188 $queryBuilderTemplate = $dbr->newSelectQueryBuilder()
189 ->table( 'user' )
190 ->leftJoin( 'user_properties', null, [
191 'user_id = up_user',
192 'up_property' => $option,
193 ] )
194 ->fields( [ 'user_id', 'user_name' ] )
195 // up_value is unindexed so this can be slow, but should be acceptable in a script
196 ->where( [ 'up_value' => $fromIsDefault ? null : $from ] )
197 // need to order by ID so we can use ID ranges for query continuation
198 // also needed for the fromuserid / touserid parameters to work
199 ->orderBy( 'user_id', SelectQueryBuilder::SORT_ASC )
200 ->limit( $this->getBatchSize() )
201 ->caller( __METHOD__ );
202 if ( $toUserId ) {
203 $queryBuilderTemplate->andWhere( $dbr->expr( 'user_id', '<=', $toUserId ) );
204 }
205
206 if ( $tempUserConfig->isKnown() ) {
207 $queryBuilderTemplate->andWhere(
208 $tempUserConfig->getMatchCondition( $dbr, 'user_name', IExpression::NOT_LIKE )
209 );
210 }
211
212 do {
213 $queryBuilder = clone $queryBuilderTemplate;
214 $queryBuilder->andWhere( $dbr->expr( 'user_id', '>', $fromUserId ) );
215 $result = $queryBuilder->fetchResultSet();
216 foreach ( $result as $row ) {
217 $fromUserId = (int)$row->user_id;
218 $oldOptionIsDefault = true;
219
220 $user = UserIdentityValue::newRegistered( $row->user_id, $row->user_name );
221 if ( $fromIsDefault ) {
222 // $user has the default value for $option; skip if it doesn't match
223 // NOTE: This is intentionally a loose comparison. $from is always a string
224 // (coming from the command line), but the default value might be of a
225 // different type.
226 $oldOptionMatchingDefault = null;
227 foreach ( $from as $oldOption ) {
228 $oldOptionIsDefault = $oldOption != $userOptionsManager->getDefaultOption( $option, $user );
229 if ( $oldOptionIsDefault ) {
230 $oldOptionMatchingDefault = $oldOption;
231 break;
232 }
233 }
234 $fromAsText = $oldOptionMatchingDefault ?? $fromAsText;
235 }
236
237 $this->output( "$settingWord {$option} for {$row->user_name} from '{$fromAsText}' to '{$to}'\n" );
238 if ( !$dryRun && $oldOptionIsDefault ) {
239 $userOptionsManager->setOption( $user, $option, $to );
240 $userOptionsManager->saveOptions( $user );
241 }
242 }
243 $this->waitForReplication();
244 } while ( $result->numRows() );
245 }
246
247 /**
248 * Delete occurrences of the option (with the given value, if provided)
249 */
250 private function deleteOptions() {
251 $dryRun = $this->hasOption( 'dry' );
252 $option = $this->getArg( 0 );
253 $fromUserId = (int)$this->getOption( 'fromuserid', 0 );
254 $toUserId = (int)$this->getOption( 'touserid', 0 ) ?: null;
255 $old = $this->getOption( 'old' );
256
257 if ( !$dryRun ) {
258 $forUsers = ( $fromUserId || $toUserId ) ? "some users (ID $fromUserId-$toUserId)" : 'ALL USERS';
259 $this->warn( <<<WARN
260 The script is about to delete '$option' option for $forUsers from user_properties table.
261 This action is IRREVERSIBLE.
262
263 Abort with control-c in the next five seconds....
264 WARN
265 );
266 }
267
268 $dbr = $this->getReplicaDB();
269 $dbw = $this->getPrimaryDB();
270
271 $rowsNum = 0;
272 $rowsInThisBatch = -1;
273 $minUserId = $fromUserId;
274 while ( $rowsInThisBatch != 0 ) {
275 $queryBuilder = $dbr->newSelectQueryBuilder()
276 ->select( 'up_user' )
277 ->from( 'user_properties' )
278 ->where( [ 'up_property' => $option, $dbr->expr( 'up_user', '>', $minUserId ) ] );
279 if ( $this->hasOption( 'touserid' ) ) {
280 $queryBuilder->andWhere( $dbr->expr( 'up_user', '<', $toUserId ) );
281 }
282 if ( $this->hasOption( 'old' ) ) {
283 $queryBuilder->andWhere( [ 'up_value' => $old ] );
284 }
285 // need to order by ID so we can use ID ranges for query continuation
286 $queryBuilder
287 ->orderBy( 'up_user', SelectQueryBuilder::SORT_ASC )
288 ->limit( $this->getBatchSize() );
289
290 $userIds = $queryBuilder->caller( __METHOD__ )->fetchFieldValues();
291 if ( $userIds === [] ) {
292 // no rows left
293 break;
294 }
295
296 if ( !$dryRun ) {
297 $delete = $dbw->newDeleteQueryBuilder()
298 ->deleteFrom( 'user_properties' )
299 ->where( [ 'up_property' => $option, 'up_user' => $userIds ] );
300 if ( $this->hasOption( 'old' ) ) {
301 $delete->andWhere( [ 'up_value' => $old ] );
302 }
303 $delete->caller( __METHOD__ )->execute();
304 $rowsInThisBatch = $dbw->affectedRows();
305 } else {
306 $rowsInThisBatch = count( $userIds );
307 }
308
309 $this->waitForReplication();
310 $rowsNum += $rowsInThisBatch;
311 $minUserId = max( $userIds );
312 }
313
314 if ( !$dryRun ) {
315 $this->output( "Done! Deleted $rowsNum rows.\n" );
316 } else {
317 $this->output( "Would delete $rowsNum rows.\n" );
318 }
319 }
320
321 private function deleteDefaults() {
322 $dryRun = $this->hasOption( 'dry' );
323 $option = $this->getArg( 0 );
324 $fromUserId = (int)$this->getOption( 'fromuserid', 0 );
325 $toUserId = (int)$this->getOption( 'touserid', 0 ) ?: null;
326
327 if ( $option === null ) {
328 $this->fatalError( "Option name is required" );
329 }
330
331 if ( !$dryRun ) {
332 $this->warn( <<<WARN
333 This script is about to delete all rows in user_properties that match the current
334 defaults for the user (including conditional defaults).
335 This action is IRREVERSIBLE.
336
337 Abort with control-c in the next five seconds....
338 WARN
339 );
340 }
341
342 $dbr = $this->getDB( DB_REPLICA );
343 $dbw = $this->getDB( DB_PRIMARY );
344
345 $queryBuilderTemplate = $dbr->newSelectQueryBuilder()
346 ->select( [ 'user_id', 'user_name', 'up_value' ] )
347 ->from( 'user_properties' )
348 ->join( 'user', null, [ 'up_user = user_id' ] )
349 ->where( [ 'up_property' => $option ] )
350 ->limit( $this->getBatchSize() )
351 ->caller( __METHOD__ );
352
353 if ( $toUserId !== null ) {
354 $queryBuilderTemplate->andWhere( $dbr->expr( 'up_user', '<=', $toUserId ) );
355 }
356
357 $userOptionsManager = $this->getServiceContainer()->getUserOptionsManager();
358 do {
359 $queryBuilder = clone $queryBuilderTemplate;
360 $queryBuilder->andWhere( $dbr->expr( 'up_user', '>', $fromUserId ) );
361 $result = $queryBuilder->fetchResultSet();
362 foreach ( $result as $row ) {
363 $fromUserId = (int)$row->user_id;
364
365 // NOTE: If up_value equals to the default, this will drop the row. Otherwise, it
366 // is going to be a no-op.
367 $user = UserIdentityValue::newRegistered( $row->user_id, $row->user_name );
368 $userOptionsManager->setOption( $user, $option, $row->up_value );
369 $userOptionsManager->saveOptions( $user );
370 }
371 $this->waitForReplication();
372 } while ( $result->numRows() );
373
374 $this->output( "Done!\n" );
375 }
376
377 /**
378 * The warning message and countdown
379 *
380 * @param string $message
381 */
382 private function warn( string $message ) {
383 if ( $this->hasOption( 'nowarn' ) ) {
384 return;
385 }
386
387 $this->output( $message );
388 $this->countDown( 5 );
389 }
390 }
391
392 // @codeCoverageIgnoreStart
393 $maintClass = UserOptionsMaintenance::class;
394 require_once RUN_MAINTENANCE_IF_MAIN;
395 // @codeCoverageIgnoreEnd