Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
232 / 232
100.00% covered (success)
100.00%
9 / 9
CRAP
100.00% covered (success)
100.00%
1 / 1
MediaModerationImageContentsLookup
100.00% covered (success)
100.00%
232 / 232
100.00% covered (success)
100.00%
9 / 9
57
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getImageContents
100.00% covered (success)
100.00%
36 / 36
100.00% covered (success)
100.00%
1 / 1
9
 getThumbnailMimeType
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
6
 getThumbnailWidth
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
8
 shouldThumbnailWidthMeetMinimumRequirements
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getThumbnailForFile
100.00% covered (success)
100.00%
77 / 77
100.00% covered (success)
100.00%
1 / 1
11
 getThumbnailContents
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
8
 getFileContents
100.00% covered (success)
100.00%
35 / 35
100.00% covered (success)
100.00%
1 / 1
11
 incrementImageContentsLookupErrorTotal
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2declare( strict_types=1 );
3
4namespace MediaWiki\Extension\MediaModeration\Services;
5
6use MediaWiki\Config\ServiceOptions;
7use MediaWiki\Extension\MediaModeration\Media\ThumborThumbnailImage;
8use MediaWiki\Extension\MediaModeration\Status\ImageContentsLookupStatus;
9use MediaWiki\FileRepo\File\ArchivedFile;
10use MediaWiki\FileRepo\File\File;
11use MediaWiki\FileRepo\LocalRepo;
12use MediaWiki\Http\HttpRequestFactory;
13use MediaWiki\Language\RawMessage;
14use MediaWiki\MainConfigNames;
15use MediaWiki\Media\MediaTransformError;
16use MediaWiki\Media\ThumbnailImage;
17use MediaWiki\WikiMap\WikiMap;
18use StatusValue;
19use Wikimedia\FileBackend\FileBackend;
20use Wikimedia\Mime\MimeAnalyzer;
21use Wikimedia\Stats\StatsFactory;
22
23/**
24 * This service looks up the contents of the given $file, either by getting a thumbnail
25 * with width as specified in the wgMediaModerationThumbnailWidth config or if this fails
26 * using the original source file.
27 */
28class MediaModerationImageContentsLookup {
29
30    public const CONSTRUCTOR_OPTIONS = [
31        MainConfigNames::ThumbnailSteps,
32        'MediaModerationThumbnailWidth',
33        'MediaModerationThumbnailMinimumSize',
34        'MediaModerationThumborRequestTimeout',
35    ];
36
37    public function __construct(
38        private readonly ServiceOptions $options,
39        private readonly FileBackend $fileBackend,
40        private readonly StatsFactory $statsFactory,
41        private readonly MimeAnalyzer $mimeAnalyzer,
42        private readonly LocalRepo $localRepo,
43        private readonly HttpRequestFactory $httpRequestFactory,
44    ) {
45        $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
46    }
47
48    /**
49     * Gets the image contents as a string for the given $file to be sent to PhotoDNA.
50     *
51     * This function first tries to get a thumbnail for the $file and return the contents of the
52     * thumbnail. If this fails, then the function tries to return the contents of the $file
53     * if the $file is in a format supported by PhotoDNA.
54     *
55     * @param File|ArchivedFile $file
56     * @return ImageContentsLookupStatus
57     */
58    public function getImageContents( $file ): ImageContentsLookupStatus {
59        $wiki = WikiMap::getCurrentWikiId();
60        // Create a status that will be returned, and if it is good will contain the
61        // thumbnail/original file contents and mime type.
62        $returnStatus = new ImageContentsLookupStatus();
63        if ( $file instanceof File ) {
64            // Only try to use the thumbnail if the $file is an instance of the File class,
65            // as support for generating a thumbnail for deleted files is not implemented.
66            $thumbnailStatus = $this->getThumbnailForFile( $file );
67            if ( $thumbnailStatus->isGood() ) {
68                // If we could get the ThumbnailImage object for the $file, then
69                // try to get the contents of the thumbnail along with the mime type.
70                $thumbnail = $thumbnailStatus->getValue();
71                $thumbnailContentsStatus = $this->getThumbnailContents( $thumbnail );
72                $thumbnailMimeTypeStatus = $this->getThumbnailMimeType( $thumbnail );
73                if ( $thumbnailContentsStatus->isGood() && $thumbnailMimeTypeStatus->isGood() ) {
74                    // If we were able to get the thumbnail contents and mime type, then return with them.
75                    return $returnStatus
76                        ->setImageContents( $thumbnailContentsStatus->getValue() )
77                        ->setMimeType( $thumbnailMimeTypeStatus->getValue() );
78                }
79                // Add the failures to the return status for the caller to see.
80                $returnStatus
81                    ->merge( $thumbnailMimeTypeStatus )
82                    ->merge( $thumbnailContentsStatus );
83            }
84            // Add the failures to the return status for the caller to see.
85            $returnStatus->merge( $thumbnailStatus );
86        }
87        // If no thumbnail could be generated for the $file or the $file is an ArchivedFile instance, then we will
88        // reach here. Now try to get the contents of the $file if the mime type type is supported by PhotoDNA.
89        if ( in_array( $file->getMimeType(), MediaModerationFileProcessor::ALLOWED_MIME_TYPES, true ) ) {
90            $fileContentsStatus = $this->getFileContents( $file );
91            if ( $fileContentsStatus->isGood() ) {
92                // We were able to get the contents of the $file
93                if ( $file instanceof File ) {
94                    // Add to the RuntimeException count if $file was a File, as we should
95                    // have been able to generate a thumbnail for it.
96                    $this->statsFactory->withComponent( 'MediaModeration' )
97                        ->getCounter( 'image_contents_lookup_used_source_file_total' )
98                        ->setLabel( 'wiki', $wiki )
99                        ->increment();
100                }
101                // Set the result as OK as we got the original file, but still include the
102                // errors from the thumbnail generation for tracking.
103                return $returnStatus
104                    ->setOK( true )
105                    ->setImageContents( $fileContentsStatus->getValue() )
106                    ->setMimeType( $file->getMimeType() );
107            }
108            // If we were unable to get the contents of the $file, then add the errors from
109            // this to the return status.
110            $returnStatus->merge( $fileContentsStatus );
111        }
112        // If we get here, then we have failed to get any image contents and so should return a fatal status.
113        if ( $returnStatus->isOK() ) {
114            // The $returnStatus can be good and have no message if the image was deleted and the source image is
115            // not supported by PhotoDNA (such as a deleted SVG).
116            $returnStatus->fatal( new RawMessage( "Failed to get image contents for {$file->getName()}" ) );
117        }
118        // Increment the RuntimeException statsd counter, as we have reached a point where
119        // we could not generate a thumbnail where we should have been able to.
120        $this->statsFactory->withComponent( 'MediaModeration' )
121            ->getCounter( 'image_contents_lookup_failure_total' )
122            ->setLabel( 'wiki', $wiki )
123            ->increment();
124        return $returnStatus;
125    }
126
127    /**
128     * Gets the mime type (or best guess for it) of the given $thumbnail.
129     *
130     * @param ThumbnailImage $thumbnail
131     * @return StatusValue
132     */
133    protected function getThumbnailMimeType( ThumbnailImage $thumbnail ): StatusValue {
134        // Attempt to work out the mime type of the thumbnail, so that we can avoid sending thumbnails which
135        // are not supported by PhotoDNA
136        $thumbnailMimeType = null;
137        if ( $thumbnail instanceof ThumborThumbnailImage ) {
138            $thumbnailMimeType = $thumbnail->getContentType();
139        }
140        if ( $thumbnailMimeType === null && $thumbnail->getExtension() ) {
141            $thumbnailMimeType = $this->mimeAnalyzer->getMimeTypeFromExtensionOrNull( $thumbnail->getExtension() );
142        }
143        $thumbnailMimeType ??= $this->mimeAnalyzer->guessMimeType( $thumbnail->getLocalCopyPath() );
144
145        if ( !$thumbnailMimeType ) {
146            // We cannot send a request to PhotoDNA without knowing what the mime type is.
147            $this->incrementImageContentsLookupErrorTotal(
148                'thumbnail', 'mime', 'lookup_failed'
149            );
150            return StatusValue::newFatal( new RawMessage(
151                "Could not get mime type of thumbnail for {$thumbnail->getFile()->getName()}"
152            ) );
153        }
154        if ( !in_array( $thumbnailMimeType, MediaModerationFileProcessor::ALLOWED_MIME_TYPES, true ) ) {
155            // We cannot send a request to PhotoDNA with a thumbnail type that is unsupported by the API.
156            $this->incrementImageContentsLookupErrorTotal(
157                'thumbnail', 'mime', 'unsupported'
158            );
159            return StatusValue::newFatal( new RawMessage(
160                "Mime type of thumbnail for {$thumbnail->getFile()->getName()} is not supported by PhotoDNA."
161            ) );
162        }
163        return StatusValue::newGood( $thumbnailMimeType );
164    }
165
166    /**
167     * Get the thumbnail width to be used that meets the dimension requirements in
168     * $wgMediaModerationThumbnailMinimumSize.
169     *
170     * Priority is given first to checking if the widths in $wgMediaModerationThumbnailWidth or
171     * $wgThumbnailSteps would meet the requirements. If none of these widths work, then a
172     * width is generated by getting the smallest possible width while meeting the dimension
173     * requirements.
174     *
175     * @param File $file
176     * @return int
177     */
178    private function getThumbnailWidth( File $file ): int {
179        $thumbnailWidth = $this->options->get( 'MediaModerationThumbnailWidth' );
180
181        // Without a file width or height, we cannot calculate the optimal width. Therefore just return
182        // $wgMediaModerationThumbnailWidth as a default.
183        if ( !$file->getWidth() || !$file->getHeight() ) {
184            return $thumbnailWidth;
185        }
186
187        // See if $wgMediaModerationThumbnailWidth would produce a thumbnail which meets the minimum height and width
188        // requirements as listed in $wgMediaModerationThumbnailMinimumSize, returning it if it does.
189        if ( $thumbnailWidth && $this->shouldThumbnailWidthMeetMinimumRequirements( $file, $thumbnailWidth ) ) {
190            return $thumbnailWidth;
191        }
192
193        // Next try the same check but on any thumbnail widths listed in ThumbnailSteps to avoid generating too
194        // many thumbnails, as these thumbnail widths should be defined.
195        $thumbnailSteps = $this->options->get( MainConfigNames::ThumbnailSteps );
196        if ( $thumbnailSteps ) {
197            sort( $thumbnailSteps );
198            foreach ( $thumbnailSteps as $step ) {
199                if ( $this->shouldThumbnailWidthMeetMinimumRequirements( $file, $step ) ) {
200                    return $step;
201                }
202            }
203        }
204
205        // As the pre-defined sizes have been tried and did not meet the requirements, we should try to pick a width
206        // by working out the minimum width needed to get a file that is tall enough.
207        $minThumbnailSize = $this->options->get( 'MediaModerationThumbnailMinimumSize' );
208        $minWidthScalingFactor = $minThumbnailSize['width'] / $file->getWidth();
209        $minHeightScalingFactor = $minThumbnailSize['height'] / $file->getHeight();
210        $scalingFactor = max( $minHeightScalingFactor, $minWidthScalingFactor );
211
212        return (int)ceil( $file->getWidth() * $scalingFactor );
213    }
214
215    /**
216     * Works out if for a given thumbnail width and {@link File}, the resulting thumbnail
217     * should meet the minimum requirements for height and width.
218     *
219     * @param File $file
220     * @param int $thumbnailWidth
221     * @return bool
222     */
223    private function shouldThumbnailWidthMeetMinimumRequirements( File $file, int $thumbnailWidth ): bool {
224        $minThumbnailSize = $this->options->get( 'MediaModerationThumbnailMinimumSize' );
225        if ( $thumbnailWidth < $minThumbnailSize['width'] ) {
226            return false;
227        }
228
229        // We can assume that the scaling would be equal for both width and height. Therefore, work out the scaling
230        // factor for the width and then apply that to the file height to get the expected thumbnail height.
231        $scalingFactor = $thumbnailWidth / $file->getWidth();
232        return $file->getHeight() * $scalingFactor >= $minThumbnailSize['height'];
233    }
234
235    /**
236     * @param File $file
237     * @return StatusValue<ThumbnailImage|ThumborThumbnailImage> A StatusValue with a ThumbnailImage object as the value
238     *   if it is a good status.
239     */
240    protected function getThumbnailForFile( File $file ): StatusValue {
241        $wiki = WikiMap::getCurrentWikiId();
242        $genericErrorMessage = 'Could not transform file ' . $file->getName();
243
244        // Attempt to get a thumbnail for the $file
245        $start = microtime( true );
246        $thumbnailWidth = $this->getThumbnailWidth( $file );
247        $thumbProxyUrl = $file->getRepo()->getThumbProxyUrl();
248        $secret = $file->getRepo()->getThumbProxySecret();
249        if ( $thumbProxyUrl && $secret ) {
250            $thumbName = $file->thumbName( [ 'width' => $thumbnailWidth ] );
251            // Specific to Wikimedia setup only: proxy the request to Thumbor,
252            // which should result in the thumbnail being generated on disk
253            // @see wfProxyThumbnailRequest()
254            $req = $this->httpRequestFactory->create(
255                $thumbProxyUrl . $file->getThumbRel( $thumbName ),
256                [
257                    'timeout' => $this->options->get( 'MediaModerationThumborRequestTimeout' ),
258                    'userAgent' => $this->httpRequestFactory->getUserAgent() . ' MediaModerationImageContentsLookup',
259                ],
260                __METHOD__
261            );
262            $req->setHeader( 'X-Swift-Secret', $secret );
263            $result = $req->execute();
264            // Log the HTTP status code from Thumbor (T385448)
265            $this->statsFactory->withComponent( 'MediaModeration' )
266                ->getCounter( 'image_contents_lookup_thumbor_request_total' )
267                ->setLabel( 'wiki', $wiki )
268                ->setLabel( 'status_code', strval( $req->getStatus() ) )
269                ->increment();
270            if ( $result->isGood() ) {
271                $imageContent = $req->getContent();
272                // getimagesizefromstring() can return a PHP Notice if
273                // the contents are invalid. Suppress the notice, and check
274                // instead of the result is truthy.
275                // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged
276                $imageMetadata = @getimagesizefromstring( $imageContent );
277                if ( $imageMetadata ) {
278                    $thumbnail = new ThumborThumbnailImage(
279                        $file,
280                        $file->getThumbUrl( $thumbName ),
281                        [
282                            'width' => $imageMetadata[0],
283                            'height' => $imageMetadata[1]
284                        ],
285                        $imageContent,
286                        $req->getResponseHeader( 'content-type' )
287                    );
288                    $this->statsFactory->withComponent( 'MediaModeration' )
289                        ->getTiming( 'image_contents_lookup_thumbnail_transform_time' )
290                        ->setLabel( 'wiki', $wiki )
291                        ->setLabel( 'method', 'thumbor' )
292                        ->observeSeconds( microtime( true ) - $start );
293                    return StatusValue::newGood( $thumbnail );
294                }
295            }
296            // The request failed, so increment the failure counter and use regular ::transform
297            // for checks done further on.
298            $this->incrementImageContentsLookupErrorTotal(
299                'thumbnail', 'thumbor_transform', 'failed'
300            );
301            $thumbnail = $file->transform( [ 'width' => $thumbnailWidth ] );
302        } else {
303            // For non Wikimedia setups, use RENDER_NOW to ensure we have
304            // a file to work with.
305            $thumbnail = $file->transform( [ 'width' => $thumbnailWidth ], File::RENDER_NOW );
306        }
307        $delay = microtime( true ) - $start;
308        $this->statsFactory->withComponent( 'MediaModeration' )
309            ->getTiming( 'image_contents_lookup_thumbnail_transform_time' )
310            ->setLabel( 'wiki', $wiki )
311            ->setLabel( 'method', 'php' )
312            ->observeSeconds( $delay );
313
314        // Check if the $thumbnail is valid, returning a good status if this is the case.
315        $returnStatus = StatusValue::newGood();
316        if ( !$thumbnail ) {
317            $returnStatus->fatal( new RawMessage( $genericErrorMessage ) );
318        } elseif ( $thumbnail instanceof MediaTransformError ) {
319            $returnStatus->fatal( new RawMessage( $genericErrorMessage . ': ' . $thumbnail->toText() ) );
320        } elseif ( !( $thumbnail instanceof ThumbnailImage ) ) {
321            $returnStatus->fatal( new RawMessage(
322                $genericErrorMessage . ': not an instance of ThumbnailImage, got ' . get_class( $thumbnail )
323            ) );
324        } elseif ( !$thumbnail->hasFile() ) {
325            $returnStatus->fatal( new RawMessage(
326                $genericErrorMessage . ', got a ' . get_class( $thumbnail ) . ' but ::hasFile() returns false.'
327            ) );
328        } elseif ( !$thumbnail->getLocalCopyPath() ) {
329            $returnStatus->fatal( new RawMessage(
330                $genericErrorMessage . ', got a ' . get_class( $thumbnail ) . ' but ::getLocalCopyPath returns false.'
331            ) );
332        } else {
333            $returnStatus = $returnStatus->setResult( true, $thumbnail );
334        }
335
336        if ( !$returnStatus->isGood() ) {
337            $this->incrementImageContentsLookupErrorTotal(
338                'thumbnail', 'transform', 'failed'
339            );
340        }
341        return $returnStatus;
342    }
343
344    protected function getThumbnailContents( ThumbnailImage $thumbnail ): StatusValue {
345        $minThumbnailSize = $this->options->get( 'MediaModerationThumbnailMinimumSize' );
346        if (
347            $thumbnail->getHeight() < $minThumbnailSize['height'] ||
348            $thumbnail->getWidth() < $minThumbnailSize['width']
349        ) {
350            $this->incrementImageContentsLookupErrorTotal(
351                'thumbnail', 'contents', 'too_small'
352            );
353            // PhotoDNA requires that images be at least 160px by 160px, so don't use the
354            // thumbnail if either dimension is too small.
355            return StatusValue::newFatal( new RawMessage(
356                "Thumbnail does not meet dimension requirements for {$thumbnail->getFile()->getName()}"
357            ) );
358        }
359        if ( !( $thumbnail instanceof ThumborThumbnailImage ) && !$thumbnail->getStoragePath() ) {
360            $this->incrementImageContentsLookupErrorTotal(
361                'thumbnail', 'contents', 'lookup_failed'
362            );
363            return StatusValue::newFatal( new RawMessage(
364                "Could not get storage path of thumbnail for {$thumbnail->getFile()->getName()}"
365            ) );
366        }
367        $fileContents = $thumbnail instanceof ThumborThumbnailImage ?
368            $thumbnail->getContent() :
369            $this->fileBackend->getFileContents( [ 'src' => $thumbnail->getStoragePath() ] );
370        if ( !$fileContents ) {
371            $this->incrementImageContentsLookupErrorTotal(
372                'thumbnail', 'contents', 'lookup_failed'
373            );
374            return StatusValue::newFatal( new RawMessage(
375                "Could not get thumbnail contents for {$thumbnail->getFile()->getName()}"
376            ) );
377        }
378        if ( strlen( $fileContents ) > 4000000 ) {
379            $this->incrementImageContentsLookupErrorTotal(
380                'thumbnail', 'contents', 'too_large'
381            );
382            // Check that the size of the file does not exceed 4MB, as PhotoDNA returns an
383            // error for files that are any larger.
384            // strlen returns the size of the string in bytes and 4MB is 4,000,000 bytes.
385            return StatusValue::newFatal( new RawMessage(
386                "Original file contents exceeds 4MB for {$thumbnail->getFile()->getName()}"
387            ) );
388        }
389        return StatusValue::newGood( $fileContents );
390    }
391
392    /**
393     * Gets the contents of the originally uploaded file referenced by $file.
394     *
395     * @param File|ArchivedFile $file
396     * @return StatusValue
397     */
398    protected function getFileContents( $file ): StatusValue {
399        if ( $file->getSize() && $file->getSize() > 4000000 ) {
400            $this->incrementImageContentsLookupErrorTotal(
401                'source_file', 'contents', 'too_large'
402            );
403            // Check that the size of the file does not exceed 4MB, as PhotoDNA returns an
404            // error for files that are any larger.
405            return StatusValue::newFatal( new RawMessage(
406                "Original file contents exceeds 4MB for {$file->getName()}"
407            ) );
408        }
409        if (
410            ( $file->getHeight() && $file->getHeight() < 160 ) ||
411            ( $file->getWidth() && $file->getWidth() < 160 )
412        ) {
413            $this->incrementImageContentsLookupErrorTotal(
414                'source_file', 'contents', 'too_small'
415            );
416            // Check that the height and width is at least 160px by 160px
417            // as PhotoDNA requires that the file be at least that size.
418            // If the height or width is false, then just ignore this check
419            // as PhotoDNA will verify this for us.
420            return StatusValue::newFatal( new RawMessage(
421                "Original file does not meet dimension requirements for {$file->getName()}"
422            ) );
423        }
424        if ( $file instanceof ArchivedFile || $file->isDeleted( File::DELETED_FILE ) ) {
425            // Format for the URL is copied from SpecialUndelete::showFile
426            $filePath = $this->localRepo->getZonePath( 'deleted' ) . '/' .
427                $this->localRepo->getDeletedHashPath( $file->getStorageKey() ) . $file->getStorageKey();
428        } else {
429            $filePath = $file->getPath();
430        }
431        if ( !$filePath ) {
432            $this->incrementImageContentsLookupErrorTotal(
433                'source_file', 'contents', 'lookup_failed'
434            );
435            return StatusValue::newFatal( new RawMessage(
436                "Could not get storage path of original file for {$file->getName()}"
437            ) );
438        }
439        $fileContents = $this->fileBackend->getFileContents( [ 'src' => $filePath ] );
440        if ( !$fileContents ) {
441            $this->incrementImageContentsLookupErrorTotal(
442                'source_file', 'contents', 'lookup_failed'
443            );
444            return StatusValue::newFatal( new RawMessage(
445                "Could not get original file contents for {$file->getName()}"
446            ) );
447        }
448        return StatusValue::newGood( $fileContents );
449    }
450
451    /**
452     * Increments the 'image_contents_lookup_error_total' Prometheus metric with the given label values
453     * to describe the error.
454     *
455     * @param string $imageType Either 'thumbnail' or 'source_file'
456     * @param string $errorType The type of error. Used to group errors into a common group, such as all errors related
457     *   to looking up the contents of an image being 'contents'
458     * @param string $error The error that occurred (for example 'lookup_failed')
459     */
460    private function incrementImageContentsLookupErrorTotal(
461        string $imageType, string $errorType, string $error
462    ): void {
463        $this->statsFactory->withComponent( 'MediaModeration' )
464            ->getCounter( 'image_contents_lookup_error_total' )
465            ->setLabel( 'wiki', WikiMap::getCurrentWikiId() )
466            ->setLabel( 'image_type', $imageType )
467            ->setLabel( 'error_type', $errorType )
468            ->setLabel( 'error', $error )
469            ->increment();
470    }
471}