Debian Codegraph @

extensions/AbuseFilter/maintenance/UpdateVarDumps.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\AbuseFilter\Maintenance;
4
5 use ExternalStoreAccess;
6 use MediaWiki\Extension\AbuseFilter\AbuseFilterServices;
7 use MediaWiki\Extension\AbuseFilter\KeywordsManager;
8 use MediaWiki\Extension\AbuseFilter\Variables\VariableHolder;
9 use MediaWiki\Extension\AbuseFilter\Variables\VariablesBlobStore;
10 use MediaWiki\Json\FormatJson;
11 use MediaWiki\Maintenance\LoggedUpdateMaintenance;
12 use MediaWiki\MediaWikiServices;
13 use MediaWiki\Title\Title;
14 use UnexpectedValueException;
15 use Wikimedia\Rdbms\IExpression;
16 use Wikimedia\Rdbms\IMaintainableDatabase;
17 use Wikimedia\Rdbms\IResultWrapper;
18 use Wikimedia\Rdbms\LikeValue;
19
20 // @codeCoverageIgnoreStart
21 $IP = getenv( 'MW_INSTALL_PATH' );
22 if ( $IP === false ) {
23 $IP = __DIR__ . '/../../..';
24 }
25 require_once "$IP/maintenance/Maintenance.php";
26 // @codeCoverageIgnoreEnd
27
28 /**
29 * Performs several tasks aiming to update the stored var dumps for filter hits.
30 *
31 * See T213006 for a list.
32 *
33 * @codeCoverageIgnore
34 * This script used to be covered by a test, but it was removed: the script was single-use, so
35 * no more testing is needed. OTOH, maintaining the test was too hard because we needed to create
36 * with serialized classes, which quickly becomes unsustainable.
37 */
38 class UpdateVarDumps extends LoggedUpdateMaintenance {
39 /** @var IMaintainableDatabase A connection to replica */
40 private $dbr;
41 /** @var IMaintainableDatabase A connection to the primary database */
42 private $dbw;
43 /** @var bool Whether we're performing a dry run */
44 private $dryRun = false;
45 /** @var int Count of rows in the abuse_filter_log table */
46 private $allRowsCount;
47 /** @var bool Whether to print progress markers */
48 private $progressMarkers;
49 /** @var string|null */
50 private $printOrphanedFile;
51 /** @var int|null How many seconds to sleep after each batch. */
52 private $sleep;
53 /** @var KeywordsManager */
54 private $keywordsManager;
55 /** @var VariablesBlobStore */
56 private $varBlobStore;
57
58 /**
59 * @inheritDoc
60 */
61 public function __construct() {
62 parent::__construct();
63
64 $this->addDescription( 'Update AbuseFilter var dumps - T213006' );
65 $this->addOption( 'dry-run-verbose', 'Perform a verbose dry run' );
66 $this->addOption( 'dry-run', 'Perform a dry run' );
67 $this->addOption( 'progress-markers', 'Print progress markers every 10 batches' );
68 $this->addOption(
69 'print-orphaned-records-to',
70 'Print ExternalStore urls of orphaned ExternalStore records (if any) ' .
71 'to the given file. Can use stdout, but it\'s not recommended for big databases.',
72 false,
73 true
74 );
75 $this->addOption( 'sleep', 'Sleep this many seconds after each batch', false, true );
76 $this->requireExtension( 'Abuse Filter' );
77 $this->setBatchSize( 500 );
78 }
79
80 /**
81 * @inheritDoc
82 */
83 public function getUpdateKey() {
84 return 'UpdateVarDumps';
85 }
86
87 /**
88 * @inheritDoc
89 */
90 public function doDBUpdates() {
91 if ( $this->hasOption( 'dry-run-verbose' ) || $this->hasOption( 'dry-run' ) ) {
92 // This way the script can be called with dry-run-verbose only and we can check for dry-run
93 $this->dryRun = true;
94 }
95 $this->progressMarkers = $this->hasOption( 'progress-markers' );
96 $this->printOrphanedFile = $this->getOption( 'print-orphaned-records-to' );
97 $this->sleep = $this->getOption( 'sleep' );
98
99 $this->keywordsManager = AbuseFilterServices::getKeywordsManager();
100 $this->varBlobStore = AbuseFilterServices::getVariablesBlobStore();
101
102 // Faulty rows aren't inserted anymore, hence we can query the replica and update the primary database.
103 $this->dbr = $this->getDB( DB_REPLICA );
104 $this->dbw = $this->getDB( DB_PRIMARY );
105
106 // Control batching with the primary key to keep the queries performant and allow gaps
107 $this->allRowsCount = (int)$this->dbr->newSelectQueryBuilder()
108 ->select( 'MAX(afl_id)' )
109 ->from( 'abuse_filter_log' )
110 ->caller( __METHOD__ )
111 ->fetchField();
112
113 if ( $this->allRowsCount === 0 ) {
114 $this->output( "...the abuse_filter_log table is empty.\n" );
115 return !$this->dryRun;
116 }
117
118 // Do the actual work. Note that several actions are superfluous (e.g. in fixMissingDumps
119 // we use "stored-text" but then we replace it in updateAflVarDump), but that's because of SRP.
120
121 // First, ensure that afl_var_dump isn't empty
122 $this->fixMissingDumps();
123 // Then, ensure that abuse_filter_log.afl_var_dump only contains "stored-text:xxxx"
124 $this->moveToText();
125 // Then update the storage format in the text table
126 $this->updateText();
127 // Finally, replace "stored-text:xxxx" with "tt:xxxx" for all rows
128 $this->updateAflVarDump();
129
130 return !$this->dryRun;
131 }
132
133 /**
134 * Handle empty afl_var_dump. gerrit/16527 fixed a bug which caused an extra abuse_filter_log
135 * row to be inserted without the var dump for a given action. If we find a row identical to
136 * the current one but with a valid dump, just delete the current one. Otherwise, store a
137 * very basic var dump for sanity.
138 * This handles point 7. of T213006.
139 */
140 private function fixMissingDumps() {
141 $this->output( "...Checking for missing dumps (1/4)\n" );
142 $batchSize = $this->getBatchSize();
143
144 $prevID = 0;
145 $curID = $batchSize;
146 $deleted = $rebuilt = 0;
147 do {
148 $this->maybePrintProgress( $prevID );
149 $brokenRows = $this->dbr->newSelectQueryBuilder()
150 ->select( '*' )
151 ->from( 'abuse_filter_log' )
152 ->where( [
153 'afl_var_dump' => '',
154 $this->dbr->expr( 'afl_id', '>', $prevID ),
155 $this->dbr->expr( 'afl_id', '<=', $curID ),
156 ] )
157 ->orderBy( 'afl_id' )
158 ->caller( __METHOD__ )
159 ->fetchResultSet();
160 $prevID = $curID;
161 $curID += $batchSize;
162
163 $res = $this->doFixMissingDumps( $brokenRows );
164 $deleted += $res['deleted'];
165 $rebuilt += $res['rebuilt'];
166 $this->waitForReplication();
167 $this->maybeSleep();
168 } while ( $prevID <= $this->allRowsCount );
169
170 if ( $this->dryRun ) {
171 $this->output(
172 "...found $deleted rows with blank afl_var_dump to delete, and " .
173 "$rebuilt rows to rebuild.\n"
174 );
175 } else {
176 $this->output(
177 "...deleted $deleted rows with blank afl_var_dump, and rebuilt " .
178 "$rebuilt rows.\n"
179 );
180 }
181 }
182
183 /**
184 * @param IResultWrapper $brokenRows
185 * @return int[]
186 */
187 private function doFixMissingDumps( IResultWrapper $brokenRows ) {
188 $deleted = 0;
189 foreach ( $brokenRows as $row ) {
190 if ( $row->afl_var_dump === '' ) {
191 $findRow = array_diff_key(
192 get_object_vars( $row ),
193 [ 'afl_var_dump' => true, 'afl_id' => true ]
194 );
195 // This is the case where we may have a duplicate row. The wrong insertion happened
196 // right before the correct one, so their afl_id should only differ by 1, but let's
197 // play safe and only assume it's greater. Note that the two entries are guaranteed
198 // to have the same timestamp.
199 $findRow[] = $this->dbr->expr( 'afl_id', '>', $row->afl_id );
200 $saneDuplicate = $this->dbr->newSelectQueryBuilder()
201 ->select( '1' )
202 ->from( 'abuse_filter_log' )
203 ->where( $findRow )
204 ->caller( __METHOD__ )
205 ->fetchRow();
206
207 if ( $saneDuplicate ) {
208 // Just delete the row!
209 $deleted++;
210 if ( !$this->dryRun ) {
211 $this->dbw->newDeleteQueryBuilder()
212 ->deleteFrom( 'abuse_filter_log' )
213 ->where( [ 'afl_id' => $row->afl_id ] )
214 ->caller( __METHOD__ )
215 ->execute();
216 }
217 continue;
218 }
219 }
220 if ( $this->dryRun ) {
221 continue;
222 }
223 // Build a VariableHolder with the only values we can be sure of
224 $vars = VariableHolder::newFromArray( [
225 'timestamp' => wfTimestamp( TS_UNIX, $row->afl_timestamp ),
226 'action' => $row->afl_action
227 ] );
228 // Add some action-specific variables
229 if ( strpos( $row->afl_action, 'createaccount' ) !== false ) {
230 $vars->setVar( 'accountname', $row->afl_user_text );
231 } else {
232 $vars->setVar( 'user_name', $row->afl_user_text );
233 $title = Title::makeTitle( $row->afl_namespace, $row->afl_title );
234 if ( $row->afl_action !== 'move' ) {
235 $vars->setVar( 'page_title', $title->getText() );
236 $vars->setVar( 'page_prefixedtitle', $title->getPrefixedText() );
237 } else {
238 $vars->setVar( 'moved_from_title', $title->getText() );
239 $vars->setVar( 'moved_from_prefixedtitle', $title->getPrefixedText() );
240 }
241 }
242
243 $storedID = $this->varBlobStore->storeVarDump( $vars );
244 $this->dbw->newUpdateQueryBuilder()
245 ->update( 'abuse_filter_log' )
246 ->set( [ 'afl_var_dump' => $storedID ] )
247 ->where( [ 'afl_id' => $row->afl_id ] )
248 ->caller( __METHOD__ )
249 ->execute();
250 }
251 $rebuilt = $brokenRows->numRows() - $deleted;
252 return [ 'rebuilt' => $rebuilt, 'deleted' => $deleted ];
253 }
254
255 /**
256 * If afl_var_dump contains serialized data, move the dump to the text table.
257 * This handles point 1. of T213006.
258 */
259 private function moveToText() {
260 $this->output( "...Moving serialized data away from the abuse_filter_log table (2/4).\n" );
261 $batchSize = $this->getBatchSize();
262
263 $prevID = 0;
264 $curID = $batchSize;
265 $changeRows = $truncatedDumps = 0;
266 do {
267 $this->maybePrintProgress( $prevID );
268 $res = $this->dbr->newSelectQueryBuilder()
269 ->select( [ 'afl_id', 'afl_var_dump' ] )
270 ->from( 'abuse_filter_log' )
271 ->where( [
272 $this->dbr->expr( 'afl_var_dump', IExpression::NOT_LIKE, new LikeValue(
273 'stored-text:',
274 $this->dbr->anyString()
275 ) ),
276 $this->dbr->expr( 'afl_var_dump', IExpression::NOT_LIKE, new LikeValue(
277 'tt:',
278 $this->dbr->anyString()
279 ) ),
280 $this->dbr->expr( 'afl_var_dump', IExpression::NOT_LIKE, new LikeValue(
281 'es:DB:',
282 $this->dbr->anyString()
283 ) ),
284 $this->dbr->expr( 'afl_id', '>', $prevID ),
285 $this->dbr->expr( 'afl_id', '<=', $curID ),
286 ] )
287 ->orderBy( 'afl_id' )
288 ->caller( __METHOD__ )
289 ->fetchResultSet();
290
291 $prevID = $curID;
292 $curID += $batchSize;
293
294 $result = $this->doMoveToText( $res );
295 $changeRows += $result['change'];
296 $truncatedDumps += $result['truncated'];
297 $this->waitForReplication();
298 $this->maybeSleep();
299 } while ( $prevID <= $this->allRowsCount );
300
301 $msg = $this->dryRun ?
302 "...found $changeRows abuse_filter_log rows with serialized data and $truncatedDumps " .
303 "truncated dumps to rebuild.\n" :
304 "...moved $changeRows abuse_filter_log rows and rebuilt $truncatedDumps " .
305 "truncated dumps.\n";
306
307 $this->output( $msg );
308 }
309
310 /**
311 * @param IResultWrapper $rows
312 * @return int[]
313 */
314 private function doMoveToText( IResultWrapper $rows ) {
315 $changeRows = $truncatedDumps = 0;
316 foreach ( $rows as $row ) {
317 // Sanity: perform a very raw check to confirm that the dump is indeed a serialized value
318 $re = '/^(a:\d+:{|O:25:"[Aa]buse[Ff]ilter[Vv]ariable[Hh]older":\d+:{)/';
319 if ( !preg_match( $re, $row->afl_var_dump ) ) {
320 $this->fatalError(
321 "...found a value in afl_var_dump for afl_id {$row->afl_id} which is " .
322 "neither a reference to the text table or a serialized value: {$row->afl_var_dump}.\n"
323 );
324 }
325
326 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
327 $stored = @unserialize( $row->afl_var_dump );
328 if ( !$stored ) {
329 $re = '/^O:25:"[Aa]buse[Ff]ilter[Vv]ariable[Hh]older":\d+:{/';
330 if ( preg_match( $re, $row->afl_var_dump ) ) {
331 $this->fatalError(
332 "...found a corrupted afl_var_dump for afl_id {$row->afl_id} containing " .
333 "a truncated object: {$row->afl_var_dump}.\n"
334 );
335 }
336 $stored = $this->restoreTruncatedDump( $row->afl_var_dump );
337 $truncatedDumps++;
338 }
339 if ( !is_array( $stored ) && !( $stored instanceof VariableHolder ) ) {
340 $this->fatalError(
341 '...found unexpected data type ( ' . get_debug_type( $stored ) . ' ) in ' .
342 "afl_var_dump for afl_id {$row->afl_id}.\n"
343 );
344 }
345 $changeRows++;
346
347 if ( !$this->dryRun ) {
348 $holder = is_array( $stored ) ? VariableHolder::newFromArray( $stored ) : $stored;
349 // Note: this will upgrade to the new JSON format, so we use tt:
350 $newDump = $this->varBlobStore->storeVarDump( $holder );
351 $this->dbw->newUpdateQueryBuilder()
352 ->update( 'abuse_filter_log' )
353 ->set( [ 'afl_var_dump' => $newDump ] )
354 ->where( [ 'afl_id' => $row->afl_id ] )
355 ->caller( __METHOD__ )
356 ->execute();
357 }
358 }
359 return [ 'change' => $changeRows, 'truncated' => $truncatedDumps ];
360 }
361
362 /**
363 * Try to restore a truncated dumps. This could happen for very old rows, where afl_var_dump
364 * was a blob instead of a longblob, and we tried to insert very long strings there.
365 * This handles point 9. of T214193.
366 *
367 * @param string $dump The broken serialized dump
368 * @return array With everything that we can restore from $dump on success
369 */
370 private function restoreTruncatedDump( $dump ) {
371 // This method makes various assumptions:
372 // 1 - Everything is wrapped inside an array
373 // 2 - Array elements can only be strings, integers, bools or null
374 // 3 - Array keys can only be strings
375 // As this is what a serialized dump should look like.
376 $string = preg_replace( '/^a:\d+:{/', '', $dump );
377
378 $ret = [];
379 $key = null;
380
381 while ( strlen( $string ) > 2 || $string === 'N;' ) {
382 $type = substr( $string, 0, 2 );
383 switch ( $type ) {
384 case 's:':
385 // Quotes aren't escaped, so we need to figure out how many characters to include
386 $matches = [];
387 if ( !preg_match( '/^s:(\d+):"/', $string, $matches ) ) {
388 break 2;
389 }
390 $len = (int)$matches[1];
391 $val = substr( $string, strlen( $matches[0] ), $len );
392 if ( strlen( $val ) === $len ) {
393 if ( $key === null ) {
394 // It's an array key
395 $key = $val;
396 } else {
397 $ret[$key] = $val;
398 $key = null;
399 }
400 $offset = strlen( $matches[0] ) + $len + 2;
401 break;
402 } else {
403 // The truncation happened in the middle of the string
404 break 2;
405 }
406 case 'i:':
407 if ( preg_match( '/^i:(-?\d+);/', $string, $matches ) ) {
408 if ( $key === null ) {
409 throw new UnexpectedValueException( "Unexpected integer key: $string" );
410 }
411 $ret[$key] = intval( $matches[1] );
412 $key = null;
413 $offset = strlen( $matches[0] );
414 break;
415 } else {
416 break 2;
417 }
418 case 'b:':
419 if ( preg_match( '/^b:([01]);/', $string, $matches ) ) {
420 if ( $key === null ) {
421 throw new UnexpectedValueException( "Unexpected bool key: $string" );
422 }
423 $ret[$key] = (bool)$matches[1];
424 $key = null;
425 $offset = 4;
426 break;
427 } else {
428 break 2;
429 }
430 case 'N;':
431 if ( $key === null ) {
432 throw new UnexpectedValueException( "Unexpected null key: $string" );
433 }
434 $ret[$key] = null;
435 $key = null;
436 $offset = 2;
437 break;
438 default:
439 break 2;
440 }
441
442 // Remove the value we have just parsed
443 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
444 // @phan-suppress-next-line PhanTypeMismatchArgumentNullableInternal
445 $string = substr( $string, $offset );
446 }
447
448 if ( $this->hasOption( 'dry-run-verbose' ) ) {
449 $this->output(
450 "...converted the following corrupted dump:\n\n$dump\n\n to this:\n\n" .
451 var_export( $ret, true ) . "\n\n"
452 );
453 }
454
455 return $ret;
456 }
457
458 /**
459 * If the text table (or the External Storage) contains a serialized variable holder
460 * or array, re-store it as a JSON-encoded array. This assumes that afl_var_dump rows starting
461 * with 'tt:' already point to JSON dumps, and afl_var_dump rows starting with 'stored-text:'
462 * only point to serialized dumps.
463 * This handles point 2. and 6. of T213006.
464 */
465 private function updateText() {
466 $this->output(
467 "...Re-storing serialized dumps as JSON-encoded arrays for all rows (3/4).\n"
468 );
469 if ( $this->printOrphanedFile !== null && !$this->dryRun ) {
470 $this->output( "Printing orphaned records to $this->printOrphanedFile.\n" );
471 file_put_contents(
472 $this->printOrphanedFile,
473 "Records orphaned by AbuseFilter's updateVarDumps sccript\n",
474 FILE_APPEND
475 );
476 }
477
478 $batchSize = $this->getBatchSize();
479 $prevID = 0;
480 $curID = $batchSize;
481 $count = 0;
482
483 $idSQL = $this->dbr->buildIntegerCast( $this->dbr->strreplace(
484 'afl_var_dump',
485 $this->dbr->addQuotes( 'stored-text:' ),
486 $this->dbr->addQuotes( '' )
487 ) );
488
489 $dumpLike = new LikeValue( 'stored-text:', $this->dbr->anyString() );
490 $esAccess = MediaWikiServices::getInstance()->getExternalStoreAccess();
491 do {
492 $this->maybePrintProgress( $prevID );
493 $res = $this->dbr->newSelectQueryBuilder()
494 ->select( [ 'old_id', 'old_text', 'old_flags' ] )
495 ->distinct()
496 ->from( 'text' )
497 ->join( 'abuse_filter_log', null, "old_id = $idSQL" )
498 ->where( [
499 $this->dbr->expr( 'afl_var_dump', IExpression::LIKE, $dumpLike ),
500 $this->dbr->expr( 'afl_id', '>', $prevID ),
501 $this->dbr->expr( 'afl_id', '<=', $curID ),
502 ] )
503 ->orderBy( 'old_id' )
504 ->caller( __METHOD__ )
505 ->fetchResultSet();
506
507 $prevID = $curID;
508 $curID += $batchSize;
509 $count += $res->numRows();
510
511 if ( !$this->dryRun ) {
512 $this->doUpdateText( $res, $esAccess );
513 $this->waitForReplication();
514 }
515 $this->maybeSleep();
516 } while ( $prevID <= $this->allRowsCount );
517
518 $msg = $this->dryRun
519 ? "...found $count text rows to update.\n"
520 : "...updated $count text rows.\n";
521 $this->output( $msg );
522 }
523
524 /**
525 * @param IResultWrapper $res text rows
526 * @param ExternalStoreAccess $esAccess
527 */
528 private function doUpdateText( IResultWrapper $res, ExternalStoreAccess $esAccess ) {
529 $orphaned = [];
530 foreach ( $res as $row ) {
531 // This is copied from the old AbuseFilter::loadVarDump
532 $oldFlags = explode( ',', $row->old_flags );
533 $text = $row->old_text;
534 if ( in_array( 'external', $oldFlags ) ) {
535 $text = $esAccess->fetchFromURL( $row->old_text );
536 }
537 if ( in_array( 'gzip', $oldFlags ) ) {
538 $text = gzinflate( $text );
539 }
540
541 if ( FormatJson::decode( $text ) !== null ) {
542 // Already in the new format, apparently.
543 if (
544 !in_array( 'utf-8', $oldFlags, true ) ||
545 in_array( 'nativeDataArray', $oldFlags, true )
546 ) {
547 // Sanity
548 $this->fatalError( "Row {$row->old_id} is JSON-encoded with wrong flags: {$row->old_flags}" );
549 }
550 continue;
551 }
552
553 // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
554 $obj = @unserialize( $text );
555
556 if ( !$obj ) {
557 // Under certain conditions, there might be a truncated dump here, see T264513
558 $obj = $this->restoreTruncatedDump( $text );
559 }
560
561 if ( $obj instanceof VariableHolder ) {
562 $varManager = AbuseFilterServices::getVariablesManager();
563 $varArray = $varManager->dumpAllVars( $obj, [ 'old_wikitext', 'new_wikitext' ] );
564 } elseif ( is_array( $obj ) ) {
565 $varArray = $obj;
566 } else {
567 $type = get_debug_type( $obj );
568 throw new UnexpectedValueException( "Unexpected type for stored blob: $type" );
569 }
570 $varArray = $this->updateVariables( $varArray );
571 // Recreating flags will also ensure that we don't add 'nativeDataArray'
572 $newFlags = [ 'utf-8' ];
573 // This is copied from the old AbuseFilter::storeVarDump
574 $toStore = FormatJson::encode( $varArray );
575 if ( in_array( 'gzip', $oldFlags ) && function_exists( 'gzdeflate' ) ) {
576 $toStore = gzdeflate( $toStore );
577 $newFlags[] = 'gzip';
578 }
579 if ( in_array( 'external', $oldFlags ) ) {
580 $orphaned[] = $row->old_text;
581 $toStore = $esAccess->insert( $toStore );
582 $newFlags[] = 'external';
583 }
584
585 $this->dbw->newUpdateQueryBuilder()
586 ->update( 'text' )
587 ->set( [
588 'old_text' => $toStore,
589 'old_flags' => implode( ',', $newFlags )
590 ] )
591 ->where( [ 'old_id' => $row->old_id ] )
592 ->caller( __METHOD__ )
593 ->execute();
594 }
595 if ( $this->printOrphanedFile !== null && $orphaned ) {
596 file_put_contents( $this->printOrphanedFile, implode( ', ', $orphaned ) . "\n", FILE_APPEND );
597 }
598 }
599
600 /**
601 * Given a stored object, removes some disabled variables and update deprecated ones.
602 * Also ensure that core variables are lowercase.
603 * Handles points 4., 5. and 8. of T213006.
604 *
605 * @param array $vars The stored vars.
606 * @return array
607 */
608 private function updateVariables( array $vars ) {
609 // Remove all variables used in the past to store metadata
610 unset( $vars['context'], $vars['logged_local_ids'], $vars['logged_global_ids'] );
611
612 $builtinVars = $this->getBuiltinVarNames();
613 $newVars = [];
614 foreach ( $vars as $oldName => $value ) {
615 $lowerName = strtolower( $oldName );
616 if ( $lowerName !== $oldName && array_key_exists( $lowerName, $builtinVars ) ) {
617 $oldName = $lowerName;
618 }
619 $deprecatedVars = $this->keywordsManager->getDeprecatedVariables();
620 $newName = $deprecatedVars[$oldName] ?? $oldName;
621 $newVars[$newName] = $value;
622 }
623 return $newVars;
624 }
625
626 /**
627 * Get a set of builtin variable names. Copied from VariableHolder::dumpAllVars.
628 * @return array [ varname => true ] for instantaneous search. All names are lowercase
629 */
630 private function getBuiltinVarNames() {
631 global $wgRestrictionTypes;
632
633 static $coreVariables = null;
634
635 if ( $coreVariables ) {
636 return $coreVariables;
637 }
638
639 $activeVariables = array_keys( $this->keywordsManager->getVarsMappings() );
640 $deprecatedVariables = array_keys( $this->keywordsManager->getDeprecatedVariables() );
641 $disabledVariables = array_keys( $this->keywordsManager->getDisabledVariables() );
642 $coreVariables = array_merge( $activeVariables, $deprecatedVariables, $disabledVariables );
643
644 $prefixes = [ 'moved_from', 'moved_to', 'page' ];
645 foreach ( $wgRestrictionTypes as $action ) {
646 foreach ( $prefixes as $prefix ) {
647 $coreVariables[] = "{$prefix}_restrictions_$action";
648 }
649 }
650
651 $coreVariables = array_fill_keys( $coreVariables, true );
652 $coreVariables = array_change_key_case( $coreVariables );
653
654 return $coreVariables;
655 }
656
657 /**
658 * Replace 'stored-text:' with 'tt:' in afl_var_dump. Handles point 3. of T213006.
659 */
660 private function updateAflVarDump() {
661 $this->output(
662 "...Replacing the 'stored-text:' prefix with 'tt:' (4/4).\n"
663 );
664
665 $batchSize = $this->getBatchSize();
666
667 // Use native SQL functions so that we can update all rows at the same time.
668 $newIdSQL = $this->dbw->strreplace(
669 'afl_var_dump',
670 $this->dbr->addQuotes( 'stored-text:' ),
671 $this->dbr->addQuotes( 'tt:' )
672 );
673
674 $prevID = 0;
675 $curID = $batchSize;
676 $numRows = 0;
677 do {
678 $this->maybePrintProgress( $prevID );
679 $table = 'abuse_filter_log';
680 $var = "afl_var_dump = $newIdSQL";
681 $conds = [
682 $this->dbr->expr( 'afl_id', '>', $prevID ),
683 $this->dbr->expr( 'afl_id', '<=', $curID ),
684 $this->dbr->expr( 'afl_var_dump', IExpression::LIKE,
685 new LikeValue( 'stored-text:', $this->dbr->anyString() ) ),
686 ];
687 $options = [ 'ORDER BY' => 'afl_id ASC' ];
688 if ( $this->dryRun ) {
689 $numRows += $this->dbr->newSelectQueryBuilder()
690 ->from( $table )
691 ->where( $conds )
692 ->caller( __METHOD__ )
693 ->fetchRowCount();
694 } else {
695 $this->dbw->newUpdateQueryBuilder()
696 ->update( $table )
697 ->set( $var )
698 ->where( $conds )
699 ->caller( __METHOD__ )
700 ->execute();
701 $numRows += $this->dbw->affectedRows();
702 $this->waitForReplication();
703 }
704
705 $prevID = $curID;
706 $curID += $batchSize;
707 $this->maybeSleep();
708 } while ( $prevID <= $this->allRowsCount );
709
710 if ( $this->dryRun ) {
711 $this->output( "...would change afl_var_dump for $numRows rows.\n" );
712 } else {
713 $this->output( "...updated afl_var_dump prefix for $numRows rows.\n" );
714 }
715 }
716
717 /**
718 * Print a progress marker if the respective option is enabled
719 *
720 * @param int $start
721 */
722 private function maybePrintProgress( int $start ): void {
723 if ( $this->progressMarkers && $start % ( 10 * $this->getBatchSize() ) === 0 ) {
724 $end = $start + $this->getBatchSize();
725 $this->output( "...Doing range $start - $end\n" );
726 }
727 }
728
729 /**
730 * Sleep for a while, if required. Note: checking the value is several
731 * orders of magnitude faster than calling sleep(0).
732 */
733 private function maybeSleep(): void {
734 if ( $this->sleep ) {
735 sleep( $this->sleep );
736 }
737 }
738 }
739
740 $maintClass = UpdateVarDumps::class;
741 require_once RUN_MAINTENANCE_IF_MAIN;