Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
12.90% covered (danger)
12.90%
12 / 93
42.86% covered (danger)
42.86%
6 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
Hooks
12.90% covered (danger)
12.90%
12 / 93
42.86% covered (danger)
42.86%
6 / 14
708.56
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getInstance
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 getActiveCaptchas
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
12
 onEditFilterMergedContent
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 onPageSaveComplete
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getCaptchaTriggerActionFromTitle
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 onEditPageBeforeEditButtons
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 onEditPage__showEditForm_fields
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 onEmailUserForm
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 onEmailUser
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 onAPIGetAllowedParams
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 onAuthChangeFormFields
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 confirmEditSetup
n/a
0 / 0
n/a
0 / 0
3
 onTitleReadWhitelist
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 onFancyCaptchaSetup
n/a
0 / 0
n/a
0 / 0
2
 onAlternateEditPreview
0.00% covered (danger)
0.00%
0 / 48
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2
3declare( strict_types=1 );
4
5namespace MediaWiki\Extension\ConfirmEdit;
6
7use MediaWiki\Api\Hook\APIGetAllowedParamsHook;
8use MediaWiki\Auth\AuthenticationRequest;
9use MediaWiki\Content\Content;
10use MediaWiki\Content\TextContent;
11use MediaWiki\Context\IContextSource;
12use MediaWiki\Context\RequestContext;
13use MediaWiki\Extension\ConfirmEdit\Auth\CaptchaAuthenticationRequest;
14use MediaWiki\Extension\ConfirmEdit\Services\CaptchaFactory;
15use MediaWiki\Extension\ConfirmEdit\SimpleCaptcha\SimpleCaptcha;
16use MediaWiki\Hook\AlternateEditPreviewHook;
17use MediaWiki\Hook\EditFilterMergedContentHook;
18use MediaWiki\Hook\EditPage__showEditForm_fieldsHook;
19use MediaWiki\Hook\EditPageBeforeEditButtonsHook;
20use MediaWiki\Html\Html;
21use MediaWiki\MediaWikiServices;
22use MediaWiki\Permissions\Hook\TitleReadWhitelistHook;
23use MediaWiki\SpecialPage\Hook\AuthChangeFormFieldsHook;
24use MediaWiki\SpecialPage\SpecialPage;
25use MediaWiki\Specials\Hook\EmailUserFormHook;
26use MediaWiki\Specials\Hook\EmailUserHook;
27use MediaWiki\Status\Status;
28use MediaWiki\Storage\Hook\PageSaveCompleteHook;
29use MediaWiki\Title\Title;
30use MediaWiki\User\User;
31use ReflectionClass;
32use Wikimedia\IPUtils;
33use Wikimedia\ObjectCache\WANObjectCache;
34
35class Hooks implements
36    AlternateEditPreviewHook,
37    EditPageBeforeEditButtonsHook,
38    EmailUserFormHook,
39    EmailUserHook,
40    TitleReadWhitelistHook,
41    PageSaveCompleteHook,
42    EditPage__showEditForm_fieldsHook,
43    EditFilterMergedContentHook,
44    APIGetAllowedParamsHook,
45    AuthChangeFormFieldsHook
46{
47    public function __construct(
48        private readonly WANObjectCache $cache,
49        private readonly CaptchaFactory $captchaFactory,
50    ) {
51    }
52
53    /**
54     * Get the global Captcha instance for a specific action.
55     *
56     * If a specific Captcha is not defined in $wgCaptchaTriggers[$action]['class'],
57     * $wgCaptchaClass will be returned instead.
58     *
59     * @deprecated Since 1.47 - Use {@link ConfirmEditCaptchaFactory::getGlobalInstance} instead.
60     */
61    public static function getInstance( string $action = '' ): SimpleCaptcha {
62        wfDeprecated( __METHOD__, '1.47' );
63        return MediaWikiServices::getInstance()->get( 'ConfirmEditCaptchaFactory' )->getGlobalInstance( $action );
64    }
65
66    /**
67     * Gets a list of all currently active Captcha classes, in the Wikis configuration.
68     *
69     * This includes the default/fallback Captcha of $wgCaptchaClass and any set under
70     * $wgCaptchaTriggers[$action]['class'].
71     *
72     * @return array<class-string,SimpleCaptcha>
73     */
74    public static function getActiveCaptchas(): array {
75        $instances = [];
76
77        // We can't rely on static::$instance being loaded with all Captcha Types, so make our own list.
78        /** @var CaptchaFactory $captchaFactory */
79        $captchaFactory = MediaWikiServices::getInstance()->get( 'ConfirmEditCaptchaFactory' );
80        $defaultCaptcha = $captchaFactory->getGlobalInstance();
81        $instances[ ( new ReflectionClass( $defaultCaptcha ) )->getShortName() ] = $defaultCaptcha;
82
83        $captchaTriggers = MediaWikiServices::getInstance()->getMainConfig()->get( 'CaptchaTriggers' );
84        foreach ( $captchaTriggers as $action => $trigger ) {
85            if ( isset( $trigger['class'] ) ) {
86                $class = $captchaFactory->getGlobalInstance( $action );
87                $instances[ $trigger['class'] ] = $class;
88            }
89        }
90
91        return $instances;
92    }
93
94    /** @inheritDoc */
95    public function onEditFilterMergedContent(
96        IContextSource $context,
97        Content $content,
98        Status $status,
99        $summary,
100        User $user,
101        $minoredit
102    ): bool {
103        $simpleCaptcha = $this->captchaFactory->getGlobalInstanceFromContext( $context );
104        // Set a flag indicating that ConfirmEdit's implementation of
105        // EditFilterMergedContent ran.
106        // This can be checked by other MediaWiki extensions, e.g. AbuseFilter.
107        $simpleCaptcha->setEditFilterMergedContentHandlerInvoked();
108        return $simpleCaptcha->confirmEditMerged( $context, $content, $status, $summary,
109            $user, $minoredit );
110    }
111
112    /** @inheritDoc */
113    public function onPageSaveComplete(
114        $wikiPage,
115        $user,
116        $summary,
117        $flags,
118        $revisionRecord,
119        $editResult
120    ) {
121        $ipBypassList = Title::makeTitle( NS_MEDIAWIKI, SimpleCaptcha::IP_BYPASS_LIST );
122        if ( $wikiPage->getTitle()->equals( $ipBypassList ) ) {
123            $this->cache->delete( $this->cache->makeKey( 'confirmedit', 'ipbypasslist' ) );
124        }
125    }
126
127    /**
128     * Get the relevant CaptchaTriggers action depending on whether the page exists
129     *
130     * @deprecated Since 1.47 - Use {@link CaptchaFactory::getGlobalInstanceFromContext} instead.
131     * @param Title $title
132     * @return string one of "edit" or "create"
133     * @see CaptchaTriggers::EDIT
134     * @see CaptchaTriggers::CREATE
135     */
136    public static function getCaptchaTriggerActionFromTitle( Title $title ): string {
137        wfDeprecated( __METHOD__, '1.47' );
138        return $title->exists() ? CaptchaTriggers::EDIT : CaptchaTriggers::CREATE;
139    }
140
141    /** @inheritDoc */
142    public function onEditPageBeforeEditButtons( $editpage, &$buttons, &$tabindex ): void {
143        $this->captchaFactory->getGlobalInstanceFromContext( $editpage->getContext() )->editShowCaptcha( $editpage );
144    }
145
146    /** @inheritDoc */
147    public function onEditPage__showEditForm_fields( $editor, $out ): void {
148        $this->captchaFactory->getGlobalInstanceFromContext( $out )->showEditFormFields( $editor, $out );
149    }
150
151    /** @inheritDoc */
152    public function onEmailUserForm( &$form ) {
153        return $this->captchaFactory->getGlobalInstance( CaptchaTriggers::SENDEMAIL )->injectEmailUser( $form );
154    }
155
156    /** @inheritDoc */
157    public function onEmailUser( &$to, &$from, &$subject, &$text, &$error ) {
158        return $this->captchaFactory->getGlobalInstance( CaptchaTriggers::SENDEMAIL )
159            ->confirmEmailUser( $from, $to, $subject, $text, $error );
160    }
161
162    /** @inheritDoc */
163    public function onAPIGetAllowedParams( $module, &$params, $flags ) {
164        // To quote Happy-melon from 32102375f80e72c8c4359abbeff66a75da463efa...
165        // > Asking for captchas in the API is really silly
166
167        // Create a merged array of API parameters based on active captcha types.
168        // This may result in clashes/overwriting if multiple Captcha use the same parameter names,
169        // but there's not a lot we can do about that...
170        foreach ( self::getActiveCaptchas() as $instance ) {
171            /** @var SimpleCaptcha $instance */
172            $instance->apiGetAllowedParams( $module, $params, $flags );
173        }
174    }
175
176    /** @inheritDoc */
177    public function onAuthChangeFormFields(
178        $requests, $fieldInfo, &$formDescriptor, $action
179    ) {
180        /** @var CaptchaAuthenticationRequest $req */
181        $req = AuthenticationRequest::getRequestByClass(
182            $requests,
183            CaptchaAuthenticationRequest::class,
184            true
185        );
186        if ( !$req ) {
187            return;
188        }
189
190        $captcha = $this->captchaFactory->getGlobalInstanceFromAuthenticationRequest(
191            $req,
192            RequestContext::getMain()->getRequest()->getSession()
193        );
194        $captcha->onAuthChangeFormFields( $requests, $fieldInfo, $formDescriptor, $action );
195    }
196
197    /** @codeCoverageIgnore */
198    public static function confirmEditSetup(): void {
199        global $wgCaptchaTriggers;
200
201        // There is no need to run (core) tests with enabled ConfirmEdit - bug T44145
202        if ( defined( 'MW_PHPUNIT_TEST' ) || defined( 'MW_QUIBBLE_CI' ) ) {
203            $wgCaptchaTriggers = array_fill_keys( array_keys( $wgCaptchaTriggers ), false );
204        }
205    }
206
207    /** @inheritDoc */
208    public function onTitleReadWhitelist( $title, $user, &$allowed ) {
209        $image = SpecialPage::getTitleFor( 'Captcha', 'image' );
210        $help = SpecialPage::getTitleFor( 'Captcha', 'help' );
211        if ( $title->equals( $image ) || $title->equals( $help ) ) {
212            $allowed = true;
213        }
214    }
215
216    /**
217     * Callback for extension.json of FancyCaptcha to set a default captcha directory,
218     * which depends on wgUploadDirectory
219     *
220     * @codeCoverageIgnore
221     */
222    public static function onFancyCaptchaSetup(): void {
223        global $wgCaptchaDirectory, $wgUploadDirectory;
224        if ( !$wgCaptchaDirectory ) {
225            $wgCaptchaDirectory = "$wgUploadDirectory/captcha";
226        }
227    }
228
229    /** @inheritDoc */
230    public function onAlternateEditPreview( $editPage, &$content, &$previewHTML,
231        &$parserOutput
232    ) {
233        $ipBypassList = Title::makeTitle( NS_MEDIAWIKI, SimpleCaptcha::IP_BYPASS_LIST );
234        if ( !$editPage->getTitle()->equals( $ipBypassList ) ) {
235            return true;
236        }
237
238        $ctx = $editPage->getArticle()->getContext();
239        $out = $ctx->getOutput();
240        $lang = $ctx->getLanguage();
241        /** @var TextContent $content */
242        '@phan-var TextContent $content';
243
244        $lines = explode( "\n", $content->getText() );
245        $previewHTML .= Html::warningBox(
246                $ctx->msg( 'confirmedit-preview-description' )->parse()
247            ) .
248            Html::openElement(
249                'table',
250                [ 'class' => 'wikitable sortable' ]
251            ) .
252            Html::openElement( 'thead' ) .
253            Html::element( 'th', [], $ctx->msg( 'confirmedit-preview-line' )->text() ) .
254            Html::element( 'th', [], $ctx->msg( 'confirmedit-preview-content' )->text() ) .
255            Html::element( 'th', [], $ctx->msg( 'confirmedit-preview-validity' )->text() ) .
256            Html::closeElement( 'thead' );
257
258        foreach ( $lines as $count => $line ) {
259            $ip = trim( $line );
260            if ( $ip === '' || strpos( $ip, '#' ) !== false ) {
261                continue;
262            }
263            if ( IPUtils::isIPAddress( $ip ) ) {
264                $validity = $ctx->msg( 'confirmedit-preview-valid' )->escaped();
265                $css = 'valid';
266            } else {
267                $validity = $ctx->msg( 'confirmedit-preview-invalid' )->escaped();
268                $css = 'notvalid';
269            }
270            $previewHTML .= Html::openElement( 'tr' ) .
271                Html::element(
272                    'td',
273                    [],
274                    $lang->formatNum( $count + 1 )
275                ) .
276                Html::element(
277                    'td',
278                    [],
279                    // IPv6 max length: 8 groups * 4 digits + 7 delimiter = 39
280                    // + 11 chars for safety
281                    $lang->truncateForVisual( $ip, 50 )
282                ) .
283                Html::rawElement(
284                    'td',
285                    // possible values:
286                    // mw-confirmedit-ip-valid
287                    // mw-confirmedit-ip-notvalid
288                    [ 'class' => 'mw-confirmedit-ip-' . $css ],
289                    $validity
290                ) .
291                Html::closeElement( 'tr' );
292        }
293        $previewHTML .= Html::closeElement( 'table' );
294        $out->addModuleStyles( 'ext.confirmEdit.editPreview.ipwhitelist.styles' );
295
296        return false;
297    }
298}