Debian Codegraph @

extensions/ConfirmEdit/includes/Hooks.php

raw symbols SCIP
1 <?php
2
3 // phpcs:disable MediaWiki.NamingConventions.LowerCamelFunctionsName.FunctionName
4
5 namespace MediaWiki\Extension\ConfirmEdit;
6
7 use MailAddress;
8 use MediaWiki\Api\ApiBase;
9 use MediaWiki\Api\Hook\APIGetAllowedParamsHook;
10 use MediaWiki\Content\Content;
11 use MediaWiki\Context\IContextSource;
12 use MediaWiki\EditPage\EditPage;
13 use MediaWiki\Extension\ConfirmEdit\FancyCaptcha\FancyCaptcha;
14 use MediaWiki\Extension\ConfirmEdit\hCaptcha\HCaptcha;
15 use MediaWiki\Extension\ConfirmEdit\QuestyCaptcha\QuestyCaptcha;
16 use MediaWiki\Extension\ConfirmEdit\ReCaptchaNoCaptcha\ReCaptchaNoCaptcha;
17 use MediaWiki\Extension\ConfirmEdit\SimpleCaptcha\SimpleCaptcha;
18 use MediaWiki\Extension\ConfirmEdit\Turnstile\Turnstile;
19 use MediaWiki\Hook\AlternateEditPreviewHook;
20 use MediaWiki\Hook\EditFilterMergedContentHook;
21 use MediaWiki\Hook\EditPage__showEditForm_fieldsHook;
22 use MediaWiki\Hook\EditPageBeforeEditButtonsHook;
23 use MediaWiki\Hook\EmailUserFormHook;
24 use MediaWiki\Hook\EmailUserHook;
25 use MediaWiki\Html\Html;
26 use MediaWiki\HTMLForm\HTMLForm;
27 use MediaWiki\Output\OutputPage;
28 use MediaWiki\Parser\ParserOutput;
29 use MediaWiki\Permissions\Hook\TitleReadWhitelistHook;
30 use MediaWiki\Registration\ExtensionRegistry;
31 use MediaWiki\ResourceLoader\Hook\ResourceLoaderRegisterModulesHook;
32 use MediaWiki\ResourceLoader\ResourceLoader;
33 use MediaWiki\Revision\RevisionRecord;
34 use MediaWiki\SpecialPage\Hook\AuthChangeFormFieldsHook;
35 use MediaWiki\SpecialPage\SpecialPage;
36 use MediaWiki\Status\Status;
37 use MediaWiki\Storage\EditResult;
38 use MediaWiki\Storage\Hook\PageSaveCompleteHook;
39 use MediaWiki\Title\Title;
40 use MediaWiki\User\User;
41 use MediaWiki\User\UserIdentity;
42 use Wikimedia\IPUtils;
43 use Wikimedia\Message\MessageSpecifier;
44 use Wikimedia\ObjectCache\WANObjectCache;
45 use WikiPage;
46
47 class Hooks implements
48 AlternateEditPreviewHook,
49 EditPageBeforeEditButtonsHook,
50 EmailUserFormHook,
51 EmailUserHook,
52 TitleReadWhitelistHook,
53 ResourceLoaderRegisterModulesHook,
54 PageSaveCompleteHook,
55 EditPage__showEditForm_fieldsHook,
56 EditFilterMergedContentHook,
57 APIGetAllowedParamsHook,
58 AuthChangeFormFieldsHook
59 {
60
61 protected static ?SimpleCaptcha $instance = null;
62
63 private WANObjectCache $cache;
64
65 public function __construct(
66 WANObjectCache $cache
67 ) {
68 $this->cache = $cache;
69 }
70
71 /**
72 * Get the global Captcha instance
73 *
74 * @return SimpleCaptcha
75 */
76 public static function getInstance() {
77 global $wgCaptchaClass;
78 static $map = [
79 'SimpleCaptcha' => SimpleCaptcha::class,
80 'FancyCaptcha' => FancyCaptcha::class,
81 'QuestyCaptcha' => QuestyCaptcha::class,
82 'ReCaptchaNoCaptcha' => ReCaptchaNoCaptcha::class,
83 'HCaptcha' => HCaptcha::class,
84 'Turnstile' => Turnstile::class,
85 ];
86 // Support PHP 7.4: Avoid `new ( $map[$wgCaptchaClass] ?? $wgCaptchaClass )`
87 $className = $map[$wgCaptchaClass] ?? $wgCaptchaClass;
88
89 static::$instance ??= new $className;
90 return static::$instance;
91 }
92
93 /**
94 * @param IContextSource $context
95 * @param Content $content
96 * @param Status $status
97 * @param string $summary
98 * @param User $user
99 * @param bool $minorEdit
100 * @return bool
101 */
102 public function onEditFilterMergedContent( IContextSource $context, Content $content, Status $status,
103 $summary, User $user, $minorEdit
104 ) {
105 $simpleCaptcha = self::getInstance( CaptchaTriggers::EDIT );
106 // Set a flag indicating that ConfirmEdit's implementation of
107 // EditFilterMergedContent ran. This can be checked by other extensions
108 // e.g. AbuseFilter.
109 $simpleCaptcha->setEditFilterMergedContentHandlerInvoked();
110 return $simpleCaptcha->confirmEditMerged( $context, $content, $status, $summary,
111 $user, $minorEdit );
112 }
113
114 /**
115 * @see https://www.mediawiki.org/wiki/Manual:Hooks/PageSaveComplete
116 *
117 * @param WikiPage $wikiPage
118 * @param UserIdentity $user
119 * @param string $summary
120 * @param int $flags
121 * @param RevisionRecord $revisionRecord
122 * @param EditResult $editResult
123 * @return bool|void
124 */
125 public function onPageSaveComplete(
126 $wikiPage,
127 $user,
128 $summary,
129 $flags,
130 $revisionRecord,
131 $editResult
132 ) {
133 $title = $wikiPage->getTitle();
134 if ( $title->getText() === 'Captcha-ip-whitelist' && $title->getNamespace() === NS_MEDIAWIKI ) {
135 $this->cache->delete( $this->cache->makeKey( 'confirmedit', 'ipbypasslist' ) );
136 }
137
138 return true;
139 }
140
141 /**
142 * @see https://www.mediawiki.org/wiki/Manual:Hooks/EditPageBeforeEditButtons
143 *
144 * @param EditPage $editpage Current EditPage object
145 * @param array &$buttons Array of edit buttons, "Save", "Preview", "Live", and "Diff"
146 * @param int &$tabindex HTML tabindex of the last edit check/button
147 */
148 public function onEditPageBeforeEditButtons( $editpage, &$buttons, &$tabindex ) {
149 self::getInstance()->editShowCaptcha( $editpage );
150 }
151
152 /**
153 * @param EditPage $editPage
154 * @param OutputPage $out
155 */
156 public function onEditPage__showEditForm_fields( $editPage, $out ) {
157 self::getInstance()->showEditFormFields( $editPage, $out );
158 }
159
160 /**
161 * @see https://www.mediawiki.org/wiki/Manual:Hooks/EmailUserForm
162 *
163 * @param HTMLForm &$form HTMLForm object
164 * @return bool|void True or no return value to continue or false to abort
165 */
166 public function onEmailUserForm( &$form ) {
167 return self::getInstance()->injectEmailUser( $form );
168 }
169
170 /**
171 * @see https://www.mediawiki.org/wiki/Manual:Hooks/EmailUser
172 *
173 * @param MailAddress &$to MailAddress object of receiving user
174 * @param MailAddress &$from MailAddress object of sending user
175 * @param string &$subject subject of the mail
176 * @param string &$text text of the mail
177 * @param bool|Status|MessageSpecifier|array &$error Out-param for an error.
178 * Should be set to a Status object or boolean false.
179 * @return bool|void True or no return value to continue or false to abort
180 */
181 public function onEmailUser( &$to, &$from, &$subject, &$text, &$error ) {
182 return self::getInstance()->confirmEmailUser( $from, $to, $subject, $text, $error );
183 }
184
185 /**
186 * APIGetAllowedParams hook handler
187 * Default $flags to 1 for backwards-compatible behavior
188 * @param ApiBase $module
189 * @param array &$params
190 * @param int $flags
191 * @return bool
192 */
193 public function onAPIGetAllowedParams( $module, &$params, $flags ) {
194 return self::getInstance()->apiGetAllowedParams( $module, $params, $flags );
195 }
196
197 /**
198 * @param array $requests
199 * @param array $fieldInfo
200 * @param array &$formDescriptor
201 * @param string $action
202 */
203 public function onAuthChangeFormFields(
204 $requests, $fieldInfo, &$formDescriptor, $action
205 ) {
206 self::getInstance()->onAuthChangeFormFields( $requests, $fieldInfo, $formDescriptor, $action );
207 }
208
209 public static function confirmEditSetup() {
210 global $wgCaptchaTriggers;
211
212 // There is no need to run (core) tests with enabled ConfirmEdit - bug T44145
213 if ( defined( 'MW_PHPUNIT_TEST' ) || defined( 'MW_QUIBBLE_CI' ) ) {
214 $wgCaptchaTriggers = array_fill_keys( array_keys( $wgCaptchaTriggers ), false );
215 }
216 }
217
218 /**
219 * @see https://www.mediawiki.org/wiki/Manual:Hooks/TitleReadWhitelist
220 *
221 * @param Title $title
222 * @param User $user
223 * @param bool &$whitelisted
224 * @return bool|void
225 */
226 public function onTitleReadWhitelist( $title, $user, &$whitelisted ) {
227 $image = SpecialPage::getTitleFor( 'Captcha', 'image' );
228 $help = SpecialPage::getTitleFor( 'Captcha', 'help' );
229 if ( $title->equals( $image ) || $title->equals( $help ) ) {
230 $whitelisted = true;
231 }
232 }
233
234 /**
235 *
236 * Callback for extension.json of FancyCaptcha to set a default captcha directory,
237 * which depends on wgUploadDirectory
238 */
239 public static function onFancyCaptchaSetup() {
240 global $wgCaptchaDirectory, $wgUploadDirectory;
241 if ( !$wgCaptchaDirectory ) {
242 $wgCaptchaDirectory = "$wgUploadDirectory/captcha";
243 }
244 }
245
246 /**
247 * @see https://www.mediawiki.org/wiki/Manual:Hooks/AlternateEditPreview
248 *
249 * @param EditPage $editPage
250 * @param Content &$content
251 * @param string &$previewHTML
252 * @param ParserOutput &$parserOutput
253 * @return bool|void
254 */
255 public function onAlternateEditPreview( $editPage, &$content, &$previewHTML,
256 &$parserOutput
257 ) {
258 $title = $editPage->getTitle();
259 $exceptionTitle = Title::makeTitle( NS_MEDIAWIKI, 'Captcha-ip-whitelist' );
260
261 if ( !$title->equals( $exceptionTitle ) ) {
262 return true;
263 }
264
265 $ctx = $editPage->getArticle()->getContext();
266 $out = $ctx->getOutput();
267 $lang = $ctx->getLanguage();
268
269 $lines = explode( "\n", $content->getNativeData() );
270 $previewHTML .= Html::warningBox(
271 $ctx->msg( 'confirmedit-preview-description' )->parse()
272 ) .
273 Html::openElement(
274 'table',
275 [ 'class' => 'wikitable sortable' ]
276 ) .
277 Html::openElement( 'thead' ) .
278 Html::element( 'th', [], $ctx->msg( 'confirmedit-preview-line' )->text() ) .
279 Html::element( 'th', [], $ctx->msg( 'confirmedit-preview-content' )->text() ) .
280 Html::element( 'th', [], $ctx->msg( 'confirmedit-preview-validity' )->text() ) .
281 Html::closeElement( 'thead' );
282
283 foreach ( $lines as $count => $line ) {
284 $ip = trim( $line );
285 if ( $ip === '' || strpos( $ip, '#' ) !== false ) {
286 continue;
287 }
288 if ( IPUtils::isIPAddress( $ip ) ) {
289 $validity = $ctx->msg( 'confirmedit-preview-valid' )->escaped();
290 $css = 'valid';
291 } else {
292 $validity = $ctx->msg( 'confirmedit-preview-invalid' )->escaped();
293 $css = 'notvalid';
294 }
295 $previewHTML .= Html::openElement( 'tr' ) .
296 Html::element(
297 'td',
298 [],
299 $lang->formatNum( $count + 1 )
300 ) .
301 Html::element(
302 'td',
303 [],
304 // IPv6 max length: 8 groups * 4 digits + 7 delimiter = 39
305 // + 11 chars for safety
306 $lang->truncateForVisual( $ip, 50 )
307 ) .
308 Html::rawElement(
309 'td',
310 // possible values:
311 // mw-confirmedit-ip-valid
312 // mw-confirmedit-ip-notvalid
313 [ 'class' => 'mw-confirmedit-ip-' . $css ],
314 $validity
315 ) .
316 Html::closeElement( 'tr' );
317 }
318 $previewHTML .= Html::closeElement( 'table' );
319 $out->addModuleStyles( 'ext.confirmEdit.editPreview.ipwhitelist.styles' );
320
321 return false;
322 }
323
324 /**
325 * @see https://www.mediawiki.org/wiki/Manual:Hooks/ResourceLoaderRegisterModules
326 *
327 * @param ResourceLoader $resourceLoader
328 * @return void
329 */
330 public function onResourceLoaderRegisterModules( ResourceLoader $resourceLoader ): void {
331 $extensionRegistry = ExtensionRegistry::getInstance();
332 $messages = [];
333
334 $messages[] = 'colon-separator';
335 $messages[] = 'captcha-edit';
336 $messages[] = 'captcha-label';
337
338 if ( $extensionRegistry->isLoaded( 'QuestyCaptcha' ) ) {
339 $messages[] = 'questycaptcha-edit';
340 }
341
342 if ( $extensionRegistry->isLoaded( 'FancyCaptcha' ) ) {
343 $messages[] = 'fancycaptcha-edit';
344 $messages[] = 'fancycaptcha-reload-text';
345 $messages[] = 'fancycaptcha-imgcaptcha-ph';
346 }
347
348 $resourceLoader->register( [
349 'ext.confirmEdit.CaptchaInputWidget' => [
350 'localBasePath' => dirname( __DIR__ ),
351 'remoteExtPath' => 'ConfirmEdit',
352 'scripts' => 'resources/libs/ext.confirmEdit.CaptchaInputWidget.js',
353 'styles' => 'resources/libs/ext.confirmEdit.CaptchaInputWidget.less',
354 'messages' => $messages,
355 'dependencies' => 'oojs-ui-core',
356 ]
357 ] );
358 }
359
360 }
361
362 class_alias( Hooks::class, 'ConfirmEditHooks' );