Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
101 / 101
100.00% covered (success)
100.00%
8 / 8
CRAP
100.00% covered (success)
100.00%
1 / 1
MediaModerationEmailer
100.00% covered (success)
100.00%
101 / 101
100.00% covered (success)
100.00%
8 / 8
28
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
 sendEmailForSha1
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
2
 getEmailSubject
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 getFileObjectsGroupedByFileName
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
6
 getEmailBodyHtml
100.00% covered (success)
100.00%
29 / 29
100.00% covered (success)
100.00%
1 / 1
7
 getEmailBodyPlaintext
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
7
 getEmailBodyIntroductionText
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 getEmailBodyFooterText
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2declare( strict_types=1 );
3
4namespace MediaWiki\Extension\MediaModeration\Services;
5
6use MediaWiki\Config\ServiceOptions;
7use MediaWiki\FileRepo\File\ArchivedFile;
8use MediaWiki\FileRepo\File\File;
9use MediaWiki\FileRepo\File\LocalFile;
10use MediaWiki\Html\Html;
11use MediaWiki\Language\Language;
12use MediaWiki\Language\MessageLocalizer;
13use MediaWiki\Mail\IEmailer;
14use MediaWiki\Mail\MailAddress;
15use MediaWiki\MainConfigNames;
16use Psr\Log\LoggerInterface;
17use StatusValue;
18use Wikimedia\Timestamp\ConvertibleTimestamp;
19
20class MediaModerationEmailer {
21
22    public const CONSTRUCTOR_OPTIONS = [
23        'MediaModerationRecipientList',
24        'MediaModerationFrom',
25        MainConfigNames::CanonicalServer,
26    ];
27
28    public function __construct(
29        private readonly ServiceOptions $options,
30        private readonly IEmailer $emailer,
31        private readonly MediaModerationFileLookup $mediaModerationFileLookup,
32        private readonly MessageLocalizer $messageLocalizer,
33        private readonly Language $language,
34        private readonly LoggerInterface $logger,
35    ) {
36        $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
37    }
38
39    /**
40     * Send an email to those listed in wgMediaModerationRecipientList about files with the given $sha1.
41     *
42     * Do not call this unless the SHA-1 has been determined to be a positive match by PhotoDNA.
43     *
44     * @param string $sha1 The SHA-1 of files to send an email.
45     * @param ?string $minimumTimestamp Optional. If provided, limits the files that are sent in the email
46     *   to those which are uploaded after this date.
47     * @return StatusValue
48     */
49    public function sendEmailForSha1( string $sha1, ?string $minimumTimestamp = null ) {
50        $to = array_map( static function ( $address ) {
51            return new MailAddress( $address );
52        }, $this->options->get( 'MediaModerationRecipientList' ) );
53
54        $emailerStatus = $this->emailer->send(
55            $to,
56            new MailAddress( $this->options->get( 'MediaModerationFrom' ) ),
57            $this->getEmailSubject( $sha1 ),
58            $this->getEmailBodyPlaintext( $sha1, $minimumTimestamp ),
59            $this->getEmailBodyHtml( $sha1, $minimumTimestamp )
60        );
61        if ( !$emailerStatus->isGood() ) {
62            // Something went wrong and the email did not send properly. Log this as a critical error.
63            $this->logger->critical(
64                'Email indicating SHA-1 match failed to send. SHA-1: {sha1}',
65                [ 'sha1' => $sha1, 'status' => $emailerStatus ]
66            );
67        }
68        return $emailerStatus;
69    }
70
71    /**
72     * Returns the subject line for the email sent by ::sendEmailForSha1.
73     *
74     * The subject line includes the SHA-1 and the current date and time to avoid duplications.
75     * Just using the date and time is not unique enough in the case that resendMatchEmails.php is run,
76     * as multiple emails with the same send time could be sent (as the seconds are not included)
77     *
78     * @param string $sha1
79     * @return string
80     */
81    protected function getEmailSubject( string $sha1 ): string {
82        return $this->messageLocalizer->msg( 'mediamoderation-email-subject' )
83            ->params( $sha1 )
84            ->dateTimeParams( ConvertibleTimestamp::now() )
85            ->escaped();
86    }
87
88    /**
89     * Generates a list of File and ArchivedFile objects grouped by their file name (result of ::getName).
90     *
91     * @param string $sha1
92     * @param ?string $minimumTimestamp If not null, then only include File/ArchivedFile objects for this SHA-1 which
93     *   have a timestamp greater than or equal to this value.
94     * @return LocalFile[][]|ArchivedFile[][]
95     */
96    protected function getFileObjectsGroupedByFileName( string $sha1, ?string $minimumTimestamp ): array {
97        $fileObjectsGroupedByFilename = [];
98        foreach ( $this->mediaModerationFileLookup->getFileObjectsForSha1( $sha1, 50 ) as $file ) {
99            // If we are filtering by timestamp, then remove the File/ArchivedFile if the ::getTimestamp method returns
100            // a truthy value and is less than $minimumTimestamp. Falsey values of ::getTimestamp are handled
101            // elsewhere.
102            if ( $minimumTimestamp !== null && $file->getTimestamp() && $file->getTimestamp() < $minimumTimestamp ) {
103                continue;
104            }
105            // Add the object to the return array grouped by filename.
106            if ( !array_key_exists( $file->getName(), $fileObjectsGroupedByFilename ) ) {
107                $fileObjectsGroupedByFilename[$file->getName()] = [];
108            }
109            $fileObjectsGroupedByFilename[$file->getName()][] = $file;
110        }
111        return $fileObjectsGroupedByFilename;
112    }
113
114    /**
115     * Returns the HTML version of the email sent by ::sendEmailForSha1
116     *
117     * @param string $sha1
118     * @param ?string $minimumTimestamp See ::sendEmailForSha1
119     * @return string HTML
120     */
121    protected function getEmailBodyHtml( string $sha1, ?string $minimumTimestamp ): string {
122        // Keeps a track of whether any File/ArchivedFile objects had ::getTimestamp return false,
123        // and if so what the filename was.
124        $missingTimestamps = [];
125        $returnHtml = '';
126        $fileObjectsCount = 0;
127        foreach ( $this->getFileObjectsGroupedByFileName( $sha1, $minimumTimestamp ) as $fileName => $files ) {
128            // Generate a comma-seperator list of the upload timestamps for the matching file versions, with
129            // the URL to the image as a clickable link if it can be accessed publicly.
130            $uploadTimestampsForFile = [];
131            foreach ( $files as $file ) {
132                $fileTimestamp = $file->getTimestamp();
133                if ( !$fileTimestamp ) {
134                    $missingTimestamps[] = $fileName;
135                    continue;
136                }
137                $fileObjectsCount++;
138                // Convert the timestamp out of the computer readable format into a human readable format.
139                $timestampInReadableFormat = htmlspecialchars(
140                    $this->language->timeanddate( $file->getTimestamp(), false, false )
141                );
142                if ( $file instanceof File && $file->getFullUrl() ) {
143                    // If we have a public URL for the image, then use it as the link target for the
144                    // text of the human readable timestamp.
145                    $uploadTimestampsForFile[] = Html::rawElement(
146                        'a',
147                        [ 'href' => $file->getFullUrl() ],
148                        $timestampInReadableFormat
149                    );
150                } else {
151                    // If no public URL can be found, then just add the timestamp.
152                    $uploadTimestampsForFile[] = $timestampInReadableFormat;
153                }
154            }
155            if ( !count( $uploadTimestampsForFile ) ) {
156                // Don't display an empty list which can occur when all matching versions had no upload timestamp.
157                continue;
158            }
159            // Combine the timestamps into a single line for the email html.
160            $returnHtml .= $this->messageLocalizer->msg( 'mediamoderation-email-body-file-line' )
161                ->params( $fileName )
162                ->rawParams( $this->language->listToText( $uploadTimestampsForFile ) )
163                ->parse() . "\n";
164        }
165        return $this->getEmailBodyIntroductionText( $fileObjectsCount, true ) . $returnHtml .
166            $this->getEmailBodyFooterText( $missingTimestamps );
167    }
168
169    /**
170     * Returns the plaintext version of the email sent by ::sendEmailForSha1
171     *
172     * @param string $sha1
173     * @param ?string $minimumTimestamp See ::sendEmailForSha1
174     * @return string
175     */
176    protected function getEmailBodyPlaintext( string $sha1, ?string $minimumTimestamp ): string {
177        $missingTimestamps = [];
178        $returnText = '';
179        $fileObjectsCount = 0;
180        foreach ( $this->getFileObjectsGroupedByFileName( $sha1, $minimumTimestamp ) as $fileName => $files ) {
181            // Generate a comma seperated list of the upload timestamps for file versions that matched. If there is a
182            // publicly accessible URL to the image available, then add after the timestamp.
183            $uploadTimestampsForFile = [];
184            foreach ( $files as $file ) {
185                $fileTimestamp = $file->getTimestamp();
186                if ( !$fileTimestamp ) {
187                    $missingTimestamps[] = $fileName;
188                    continue;
189                }
190                $fileObjectsCount++;
191                // Convert the timestamp out of the computer readable format into a human readable format.
192                $timestampInReadableFormat = $this->language->timeanddate( $file->getTimestamp(), false, false );
193                if ( $file instanceof File && $file->getFullUrl() ) {
194                    // If a public URL is defined, then add this after the upload timestamp for the file version.
195                    $uploadTimestampsForFile[] = $this->messageLocalizer
196                        ->msg( 'mediamoderation-email-body-file-revision-plaintext-url' )
197                        ->params( $timestampInReadableFormat, $file->getFullUrl() )
198                        ->escaped();
199                } else {
200                    // If no public URL can be found, then just add the timestamp.
201                    $uploadTimestampsForFile[] = $timestampInReadableFormat;
202                }
203            }
204            if ( !count( $uploadTimestampsForFile ) ) {
205                // Don't display an empty list which can occur when all matching versions had no upload timestamp.
206                continue;
207            }
208            // Combine the upload timestamps into a comma seperated list.
209            $returnText .= $this->messageLocalizer->msg(
210                'mediamoderation-email-body-file-line',
211                $fileName,
212                $this->language->listToText( $uploadTimestampsForFile )
213            )->escaped() . "\n";
214        }
215        return $this->getEmailBodyIntroductionText( $fileObjectsCount, false ) . $returnText .
216            $this->getEmailBodyFooterText( $missingTimestamps );
217    }
218
219    /**
220     * Returns text to be added to the start of the email body for both the plaintext and HTML version.
221     *
222     * @param int $fileRevisionsCount The number of File/ArchivedFile objects processed which have ::getTimestamp
223     *   return any other value than false.
224     * @param bool $useHtml If true, then the HTML version of the email introduction is returned.
225     * @return string
226     */
227    protected function getEmailBodyIntroductionText( int $fileRevisionsCount, bool $useHtml ): string {
228        // Add the introduction text to the start of the return text
229        $introductionMessage = $this->messageLocalizer->msg( 'mediamoderation-email-body-intro' )
230            ->numParams( $fileRevisionsCount );
231        if ( $useHtml ) {
232            $introductionMessage->rawParams( Html::element(
233                'a',
234                [ 'href' => $this->options->get( MainConfigNames::CanonicalServer ) ],
235                $this->options->get( MainConfigNames::CanonicalServer )
236            ) );
237        } else {
238            $introductionMessage->params( $this->options->get( MainConfigNames::CanonicalServer ) );
239        }
240        return $introductionMessage->escaped() . "\n";
241    }
242
243    /**
244     * Returns text to be added to the end of the email body for both the plaintext and HTML version.
245     *
246     * @param array $missingTimestamps The filenames which had File objects with ::getTimestamp returning false.
247     * @return string
248     */
249    protected function getEmailBodyFooterText( array $missingTimestamps ): string {
250        if ( count( $missingTimestamps ) ) {
251            // If we have any timestamps that were false, then indicate which filenames these were for at the bottom
252            // of the email.
253            return $this->messageLocalizer
254                ->msg( 'mediamoderation-email-body-files-missing-timestamp' )
255                ->params( $this->language->listToText( array_unique( $missingTimestamps ) ) )
256                ->escaped() . "\n";
257        }
258        return '';
259    }
260}