Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
184 / 184
100.00% covered (success)
100.00%
10 / 10
CRAP
100.00% covered (success)
100.00%
1 / 1
ImportExistingFilesToScanTable
100.00% covered (success)
100.00%
184 / 184
100.00% covered (success)
100.00%
10 / 10
36
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
31 / 31
100.00% covered (success)
100.00%
1 / 1
1
 getUpdateKey
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 doDBUpdates
100.00% covered (success)
100.00%
54 / 54
100.00% covered (success)
100.00%
1 / 1
11
 generateDBUpdatesReturnValue
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 getTablesToProcess
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 getEstimatedNumberOfBatchesForTable
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 getTemporaryBatchSize
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
2
 getFileSelectQueryBuilder
100.00% covered (success)
100.00%
17 / 17
100.00% covered (success)
100.00%
1 / 1
3
 getRowsForBatch
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
3
 performBatch
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2declare( strict_types=1 );
3
4namespace MediaWiki\Extension\MediaModeration\Maintenance;
5
6use MediaWiki\Extension\MediaModeration\Services\MediaModerationDatabaseLookup;
7use MediaWiki\Extension\MediaModeration\Services\MediaModerationFileFactory;
8use MediaWiki\Extension\MediaModeration\Services\MediaModerationFileLookup;
9use MediaWiki\Extension\MediaModeration\Services\MediaModerationFileProcessor;
10use MediaWiki\FileRepo\File\FileSelectQueryBuilder;
11use MediaWiki\Maintenance\LoggedUpdateMaintenance;
12use Wikimedia\Rdbms\IReadableDatabase;
13use Wikimedia\Rdbms\IResultWrapper;
14use Wikimedia\Rdbms\SelectQueryBuilder;
15use Wikimedia\Timestamp\ConvertibleTimestamp;
16
17// @codeCoverageIgnoreStart
18$IP = getenv( 'MW_INSTALL_PATH' );
19if ( $IP === false ) {
20    $IP = __DIR__ . '/../../..';
21}
22require_once "$IP/maintenance/Maintenance.php";
23// @codeCoverageIgnoreEnd
24
25class ImportExistingFilesToScanTable extends LoggedUpdateMaintenance {
26
27    /** @var string[] The DB tables that have images to be imported to mediamoderation_scan. */
28    public const TABLES_TO_IMPORT_FROM = [
29        'image',
30        'filearchive',
31        'oldimage',
32    ];
33
34    private IReadableDatabase $dbr;
35    private MediaModerationFileProcessor $mediaModerationFileProcessor;
36    private MediaModerationDatabaseLookup $mediaModerationDatabaseLookup;
37    private MediaModerationFileFactory $mediaModerationFileFactory;
38    private MediaModerationFileLookup $mediaModerationFileLookup;
39
40    public function __construct() {
41        parent::__construct();
42        $this->requireExtension( 'MediaModeration' );
43        $this->addDescription( 'Populates the mediamoderation_scan table with existing images from the wiki.' );
44        $this->addOption(
45            'sleep',
46            'Sleep time (in seconds) between every batch. Default: 1',
47            false,
48            true
49        );
50        $this->addOption(
51            'start-timestamp',
52            'The timestamp which to start importing files from. Can also be a relative timestamp. ' . '
53            Default is for no timestamp start point (which means importing all images).',
54            false,
55            true
56        );
57        $this->addOption(
58            'table',
59            'Allows specifying which table(s) files should be imported from. Default is all supported tables.',
60            false,
61            true,
62            false,
63            true
64        );
65        $this->addOption(
66            'mark-complete',
67            'Allows controlling whether this script should be considered completely run for the purposes ' .
68            'of the updatelog. If provided the script will be marked as complete. ' .
69            "Default is to consider the script completely run if the 'table' and 'start-timestamp' options were left " .
70            'as the default and the script does not error out.',
71        );
72    }
73
74    /** @inheritDoc */
75    protected function getUpdateKey() {
76        return __CLASS__;
77    }
78
79    /** @inheritDoc */
80    protected function doDBUpdates() {
81        $services = $this->getServiceContainer();
82        $this->dbr = $this->getReplicaDB();
83        $this->mediaModerationFileFactory = $services->get( 'MediaModerationFileFactory' );
84        $this->mediaModerationFileProcessor = $services->get( 'MediaModerationFileProcessor' );
85        $this->mediaModerationDatabaseLookup = $services->get( 'MediaModerationDatabaseLookup' );
86        $this->mediaModerationFileLookup = $services->get( 'MediaModerationFileLookup' );
87
88        $startTimestamp = $this->getOption( 'start-timestamp', '' );
89        if ( $startTimestamp ) {
90            $startTimestamp = ConvertibleTimestamp::convert( TS_MW, $this->getOption( 'start-timestamp', '' ) );
91            if ( $startTimestamp === false && $this->getOption( 'start-timestamp', '' ) !== '' ) {
92                // If it could not be parsed by ConvertibleTimestamp, then try parsing it through strtotime in case
93                // it is a relative timestamp
94                $startTimestamp = strtotime( $this->getOption( 'start-timestamp', '' ), ConvertibleTimestamp::time() );
95                if ( $startTimestamp !== false ) {
96                    $startTimestamp = ConvertibleTimestamp::convert( TS_MW, $startTimestamp );
97                }
98            }
99
100            if ( !$startTimestamp ) {
101                $this->fatalError(
102                    '--start-timestamp could not be parsed as either a valid absolute or relative timestamp'
103                );
104            }
105        }
106
107        // Phan false positive. We validated the --start-timestamp value above. It can either be an empty string
108        // or a valid timestamp as a string.
109        '@phan-var string $startTimestamp';
110
111        foreach ( $this->getTablesToProcess() as $table ) {
112            $batchSize = $this->getBatchSize() ?? 200;
113            $this->output( "Now importing rows from the table '$table' in batches of $batchSize.\n" );
114
115            if ( $startTimestamp ) {
116                $this->output(
117                    "Starting from timestamp $startTimestamp and importing files with a greater timestamp.\n"
118                );
119            }
120
121            $previousBatchFinalTimestamp = $startTimestamp;
122            $expectedNumberOfBatches = $this->getEstimatedNumberOfBatchesForTable(
123                $table, $previousBatchFinalTimestamp
124            );
125            $batchNo = 1;
126            do {
127                $outputString = "Batch $batchNo of ~$expectedNumberOfBatches";
128                if ( $previousBatchFinalTimestamp ) {
129                    $outputString .= " with rows starting at timestamp $previousBatchFinalTimestamp";
130                }
131                $this->output( $outputString . ".\n" );
132                [
133                    $filesLeft,
134                    $previousBatchFinalTimestamp
135                ] = $this->performBatch( $table, $previousBatchFinalTimestamp );
136                sleep( intval( $this->getOption( 'sleep', 1 ) ) );
137                $this->waitForReplication();
138                $batchNo += 1;
139            } while ( $filesLeft );
140        }
141        $returnValue = $this->generateDBUpdatesReturnValue();
142        if ( $this->hasOption( 'force' ) ) {
143            // If the script was run with the force option, then don't
144            // print out about how the script has been or has not been
145            // marked as completed.
146            return $returnValue;
147        }
148        if ( $returnValue ) {
149            $this->output( "Script marked as completed (added to updatelog).\n" );
150        } else {
151            $this->output(
152                'Script not marked as completed (not added to updatelog). The script was marked as not complete ' .
153                "because not all the images on the wiki were processed in this run of the script.\n" .
154                'To mark the script as complete and not have it run again through update.php, make sure to run the ' .
155                "script again with the 'mark-complete' option specified. You should only do this once you are sure " .
156                "that all the images on the wiki have been imported.\n"
157            );
158        }
159        return $returnValue;
160    }
161
162    /**
163     * Return the value that should be used as the return value
164     * of ::doDBUpdates. This value depends on the options
165     * passed to the script.
166     *
167     * If true is returned, it should only be done if the script
168     * either has imported all images or the caller of the maintenance
169     * script has specifically intended for the script to marked as
170     * complete.
171     *
172     * @return bool
173     */
174    protected function generateDBUpdatesReturnValue(): bool {
175        // Return true if mark-complete is specified, or if both:
176        // * start-timestamp is not specified or an empty string, and
177        // * table is not specified or includes all tables listed in self::TABLES_TO_IMPORT_FROM.
178        return $this->hasOption( 'mark-complete' ) ||
179            (
180                $this->getOption( 'start-timestamp', '' ) === '' &&
181                $this->getOption( 'table', self::TABLES_TO_IMPORT_FROM ) == self::TABLES_TO_IMPORT_FROM
182            );
183    }
184
185    /**
186     * Processes the user supplied list of tables to process,
187     * with the default being all supported tables.
188     *
189     * Prints an error if the supplied arguments are invalid.
190     *
191     * @return string[] The list of tables to process
192     */
193    protected function getTablesToProcess() {
194        $tablesToProcess = $this->getOption( 'table', self::TABLES_TO_IMPORT_FROM );
195        if ( !count( $tablesToProcess ) ) {
196            $this->fatalError( "The array of tables to have images imported from cannot be empty.\n" );
197        }
198        foreach ( $tablesToProcess as $table ) {
199            if ( !in_array( $table, self::TABLES_TO_IMPORT_FROM ) ) {
200                $this->fatalError( "The table option value '$table' is not a valid table to import images from.\n" );
201            }
202        }
203        return $tablesToProcess;
204    }
205
206    /**
207     * Gets the expected number of batches needed to process a table.
208     * This is used just for visual display and the actual number of batches
209     * may be higher or lower.
210     *
211     * @param string $table
212     * @param string $startTimestamp The timestamp that the processing will start from.
213     * @return int
214     */
215    protected function getEstimatedNumberOfBatchesForTable( string $table, string $startTimestamp ): int {
216        // Get the row count for the $table.
217        $queryBuilder = $this->dbr->newSelectQueryBuilder()
218            ->select( 'COUNT(*)' )
219            ->from( $table );
220        if ( $startTimestamp ) {
221            $queryBuilder->where( $this->dbr->expr(
222                $this->mediaModerationFileLookup->getTimestampFieldForTable( $table ),
223                '>=',
224                $this->dbr->timestamp( $startTimestamp )
225            ) );
226        }
227        $rowCountInTable = $queryBuilder
228            ->caller( __METHOD__ )
229            ->fetchField();
230        // If the row count is zero, then one batch will be performed.
231        if ( !$rowCountInTable ) {
232            return 1;
233        }
234        // The expected batch count is the number of rows in the table
235        // divided by the batch size. This may be higher than the actual
236        // batch count, as it may be temporarily increased to prevent
237        // infinite loops.
238        $batchSize = $this->getBatchSize() ?? 200;
239        $expectedBatchesCount = (int)ceil( $rowCountInTable / $batchSize );
240        if ( $rowCountInTable % $batchSize === 0 ) {
241            // If the batch size divides the row count without a remainder, then
242            // the expected batch count needs to be increased by one as one
243            // more batch will be performed at the end with no rows found.
244            $expectedBatchesCount += 1;
245        }
246        return $expectedBatchesCount;
247    }
248
249    /**
250     * Gets the temporary batch size for use by ::processBatch if it was provided
251     * with $shouldRaiseBatchSize as the boolean 'true'. This is one more than
252     * the number of files with the $previousBatchFinalTimestamp.
253     *
254     * @param FileSelectQueryBuilder $fileSelectQueryBuilder The cloned FileSelectQueryBuilder that is being
255     *   built in ::getSelectFileQueryBuilder. This needs to be cloned to avoid issues with this
256     *   method modifying the query builder.
257     * @param string $timestampField
258     * @param string $previousBatchFinalTimestamp
259     * @return int
260     */
261    protected function getTemporaryBatchSize(
262        FileSelectQueryBuilder $fileSelectQueryBuilder, string $timestampField, string $previousBatchFinalTimestamp
263    ): int {
264        $filesWithTheCutoffTimestamp = (int)$fileSelectQueryBuilder
265            ->clearFields()
266            ->field( 'COUNT(*)' )
267            ->where( $this->dbr->expr( $timestampField, '=', $this->dbr->timestamp( $previousBatchFinalTimestamp ) ) )
268            ->caller( __METHOD__ )
269            ->fetchField();
270        // Sanity check that the new batch size would actually be larger (otherwise
271        // leave the batch size as is as it will be fine).
272        if ( $filesWithTheCutoffTimestamp >= ( $this->getBatchSize() ?? 200 ) ) {
273            $batchSize = $filesWithTheCutoffTimestamp + 1;
274            $this->output(
275                "Temporarily raised the batch size to $batchSize due to files with the same upload timestamp. " .
276                "This is done to prevent an infinite loop. Consider raising the batch size to avoid this.\n"
277            );
278            return $batchSize;
279        }
280        return $this->getBatchSize() ?? 200;
281    }
282
283    /**
284     * Gets the appropriate FileSelectQueryBuilder for the $table and
285     * applies the WHERE conditions, ORDER BY and LIMIT.
286     *
287     * @param string $table The table name currently being processed.
288     * @param string $previousBatchFinalTimestamp The timestamp which the last batch stopped at. This
289     *   is used to filter for files with this timestamp or a newer timestamp.
290     * @param bool $shouldRaiseBatchSize Used to indicate that the previous batch ended and started on
291     *   the same timestamp, so this batch should reattempt that timestamp
292     *   but with a temporarily raised batch size to account for this.
293     * @return FileSelectQueryBuilder
294     */
295    protected function getFileSelectQueryBuilder(
296        string $table, string $previousBatchFinalTimestamp, bool $shouldRaiseBatchSize
297    ): FileSelectQueryBuilder {
298        // Get the appropriate FileSelectQueryBuilder using MediaModerationDatabaseLookup::getFileSelectQueryBuilder
299        $fileSelectQueryBuilder = $this->mediaModerationFileLookup->getFileSelectQueryBuilder( $table );
300        $timestampField = $this->mediaModerationFileLookup->getTimestampFieldForTable( $table );
301        $batchSize = $this->getBatchSize() ?? 200;
302        if ( $shouldRaiseBatchSize ) {
303            // If the previous batch started and ended on the same timestamp,
304            // then temporarily raise the batch count to 1 more than the number
305            // of files with this timestamp to avoid an infinite loop.
306            $batchSize = $this->getTemporaryBatchSize(
307                clone $fileSelectQueryBuilder,
308                $timestampField,
309                $previousBatchFinalTimestamp
310            );
311        }
312        // If the timestamp is not empty, filter for entries with a greater timestamp
313        // than the cutoff timestamp.
314        if ( $previousBatchFinalTimestamp ) {
315            $fileSelectQueryBuilder
316                ->where( $this->dbr->expr(
317                    $timestampField, '>=', $this->dbr->timestamp( $previousBatchFinalTimestamp ) ) );
318        }
319        // Order by the timestamp (oldest to newest) and set the limit as the batch size.
320        $fileSelectQueryBuilder
321            ->orderBy( $timestampField, SelectQueryBuilder::SORT_ASC )
322            ->limit( $batchSize );
323        return $fileSelectQueryBuilder;
324    }
325
326    /**
327     * Gets the rows for a batch along with the timestamp for the last file in the batch.
328     *
329     * @param string $table
330     * @param string $previousBatchFinalTimestamp
331     * @return array{0:IResultWrapper,1:string,2:int} The rows for the batch,
332     *   the timestamp for the last file in the results list, and the LIMIT used for the batch.
333     */
334    protected function getRowsForBatch( string $table, string $previousBatchFinalTimestamp ): array {
335        // Get the FileSelectQueryBuilder with everything but the caller specified.
336        $fileSelectQueryBuilder = $this->getFileSelectQueryBuilder(
337            $table, $previousBatchFinalTimestamp, false
338        );
339        // Specify the caller and then get the rows from the DB.
340        $rows = $fileSelectQueryBuilder
341            ->caller( __METHOD__ )
342            ->fetchResultSet();
343        $lastFileTimestamp = $previousBatchFinalTimestamp;
344        // Check whether the last file in this batch has the same timestamp as in
345        // $previousBatchFinalTimestamp. If so, then increase the batch size to
346        // prevent an infinite loop which would be caused by processing the same
347        // files over and over again with that timestamp.
348        if ( $rows->numRows() ) {
349            $rows->seek( $rows->numRows() - 1 );
350            $lastFileObject = $this->mediaModerationFileFactory->getFileObjectForRow( $rows->fetchObject(), $table );
351            if ( $previousBatchFinalTimestamp === $lastFileObject->getTimestamp() ) {
352                // Temporarily raise the batch size for the next batch as the
353                // last timestamp in this batch is the same as the last timestamp
354                // for the last batch.
355                $fileSelectQueryBuilder = $this->getFileSelectQueryBuilder(
356                    $table, $previousBatchFinalTimestamp, true
357                );
358                $rows = $fileSelectQueryBuilder
359                    ->caller( __METHOD__ )
360                    ->fetchResultSet();
361                $rows->seek( $rows->numRows() - 1 );
362                $lastFileObject = $this->mediaModerationFileFactory->getFileObjectForRow(
363                    $rows->fetchObject(), $table
364                );
365            }
366            // Store the timestamp for the last file, and return it to the caller later in this method.
367            $lastFileTimestamp = $lastFileObject->getTimestamp();
368            // Reset the position of the pointer for the caller to be able to use a foreach loop on $rows.
369            $rows->rewind();
370        }
371        return [ $rows, $lastFileTimestamp, $fileSelectQueryBuilder->getQueryInfo()['options']['LIMIT'] ];
372    }
373
374    /**
375     * Perform a batch of imports to the mediamoderation_scan table from the $table
376     * starting at the $lastFileTimestamp going towards newer files.
377     *
378     * @param string $table
379     * @param string $previousBatchFinalTimestamp
380     * @return array{0:bool,1:string} First value is whether another batch should be run, second value is the new
381     *   value of $previousBatchFinalTimestamp, and third value is the new value of $shouldRaiseBatchSize
382     */
383    protected function performBatch( string $table, string $previousBatchFinalTimestamp ): array {
384        [ $rows, $lastFileTimestamp, $batchSizeUsedForBatch ] = $this->getRowsForBatch(
385            $table, $previousBatchFinalTimestamp
386        );
387        foreach ( $rows as $row ) {
388            // Get the File or ArchivedFile object for this $row.
389            $fileObject = $this->mediaModerationFileFactory->getFileObjectForRow( $row, $table );
390            // Exclude any file that has a SHA-1 value that is false or empty.
391            // This can happen in some filearchive rows where the image no
392            // longer exists.
393            // Also check if the SHA-1 exists in the scan table using a replica DB
394            // before attempting to insert the file to reduce the number of
395            // unnecessary reads on the primary DB.
396            if (
397                $fileObject->getSha1() &&
398                !$this->mediaModerationDatabaseLookup->fileExistsInScanTable( $fileObject )
399            ) {
400                $this->mediaModerationFileProcessor->insertFile( $fileObject );
401            }
402        }
403        // Return false as the first item of the array if the number of rows processed
404        // was less than the batch size. This will happen when there are no more images
405        // to process.
406        return [
407            $rows->count() >= $batchSizeUsedForBatch,
408            $lastFileTimestamp
409        ];
410    }
411}
412
413// @codeCoverageIgnoreStart
414$maintClass = ImportExistingFilesToScanTable::class;
415require_once RUN_MAINTENANCE_IF_MAIN;
416// @codeCoverageIgnoreEnd