Debian Codegraph @

extensions/ConfirmEdit/SimpleCaptcha/SimpleCaptcha.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\ConfirmEdit\SimpleCaptcha;
4
5 use MailAddress;
6 use MediaWiki\Api\ApiBase;
7 use MediaWiki\Api\ApiEditPage;
8 use MediaWiki\Auth\AuthenticationRequest;
9 use MediaWiki\Cache\CacheKeyHelper;
10 use MediaWiki\Config\Config;
11 use MediaWiki\Config\ConfigException;
12 use MediaWiki\Content\Content;
13 use MediaWiki\Content\TextContent;
14 use MediaWiki\Context\IContextSource;
15 use MediaWiki\Context\RequestContext;
16 use MediaWiki\EditPage\EditPage;
17 use MediaWiki\Extension\ConfirmEdit\Auth\CaptchaAuthenticationRequest;
18 use MediaWiki\Extension\ConfirmEdit\CaptchaTriggers;
19 use MediaWiki\Extension\ConfirmEdit\Hooks\HookRunner;
20 use MediaWiki\Extension\ConfirmEdit\Store\CaptchaStore;
21 use MediaWiki\ExternalLinks\ExternalLinksLookup;
22 use MediaWiki\ExternalLinks\LinkFilter;
23 use MediaWiki\HTMLForm\HTMLForm;
24 use MediaWiki\MediaWikiServices;
25 use MediaWiki\Message\Message;
26 use MediaWiki\Output\OutputPage;
27 use MediaWiki\Parser\ParserOptions;
28 use MediaWiki\Registration\ExtensionRegistry;
29 use MediaWiki\Request\ContentSecurityPolicy;
30 use MediaWiki\Request\WebRequest;
31 use MediaWiki\Revision\RevisionAccessException;
32 use MediaWiki\Revision\SlotRecord;
33 use MediaWiki\Status\Status;
34 use MediaWiki\Title\Title;
35 use MediaWiki\User\User;
36 use OOUI\FieldLayout;
37 use OOUI\HiddenInputWidget;
38 use OOUI\NumberInputWidget;
39 use UnexpectedValueException;
40 use Wikimedia\IPUtils;
41 use Wikimedia\Rdbms\IDBAccessObject;
42 use WikiPage;
43
44 /**
45 * Demo CAPTCHA (not for production usage) and base class for real CAPTCHAs
46 */
47 class SimpleCaptcha {
48 /** @var string */
49 protected static $messagePrefix = 'captcha-';
50
51 /** @var bool Override to force showing the CAPTCHA to users who don't have "skipcaptcha" right. */
52 private bool $forceShowCaptcha = false;
53
54 /** @var bool|null Was the CAPTCHA already passed and if yes, with which result? */
55 private ?bool $captchaSolved = null;
56
57 /** @var bool Flag to indicate whether the onEditFilterMergedContent hook was invoked. */
58 private bool $editFilterMergedContentHandlerCalled = false;
59
60 /** @var bool[] Activate captchas status list for a pages by key */
61 private $activatedCaptchas = [];
62
63 /**
64 * Used to select the right message.
65 * One of sendmail, createaccount, badlogin, edit, create, addurl.
66 * @var string
67 */
68 protected $action;
69
70 /** @var string Used in log messages. */
71 protected $trigger;
72
73 /**
74 * @param string $action
75 */
76 public function setAction( $action ) {
77 $this->action = $action;
78 }
79
80 /**
81 * @param string $trigger
82 */
83 public function setTrigger( $trigger ) {
84 $this->trigger = $trigger;
85 }
86
87 /**
88 * Return the error from the last passCaptcha* call.
89 * Not implemented but needed by some child classes.
90 * @return mixed
91 */
92 public function getError() {
93 return null;
94 }
95
96 /**
97 * Returns an array with 'question' and 'answer' keys.
98 * Subclasses might use different structure.
99 * Since MW 1.27 all subclasses must implement this method.
100 * @return array
101 */
102 public function getCaptcha() {
103 $a = random_int( 0, 100 );
104 $b = random_int( 0, 10 );
105
106 /* Minus sign is used in the question. UTF-8,
107 since the api uses text/plain, not text/html */
108 $op = random_int( 0, 1 ) ? '+' : '−';
109
110 // No space before and after $op, to ensure correct
111 // directionality.
112 $test = "$a$op$b";
113 $answer = ( $op == '+' ) ? ( $a + $b ) : ( $a - $b );
114 return [ 'question' => $test, 'answer' => $answer ];
115 }
116
117 /**
118 * Returns a list of activate captchas for a page by key.
119 * @return bool[]
120 */
121 public function getActivatedCaptchas() {
122 return $this->activatedCaptchas;
123 }
124
125 /**
126 * @param array &$resultArr
127 */
128 protected function addCaptchaAPI( &$resultArr ) {
129 $captcha = $this->getCaptcha();
130 $index = $this->storeCaptcha( $captcha );
131 $resultArr['captcha'] = $this->describeCaptchaType();
132 $resultArr['captcha']['id'] = $index;
133 $resultArr['captcha']['question'] = $captcha['question'];
134 }
135
136 /**
137 * Describes the captcha type for API clients.
138 * @return array An array with keys 'type' and 'mime', and possibly other
139 * implementation-specific
140 */
141 public function describeCaptchaType() {
142 return [
143 'type' => 'simple',
144 'mime' => 'text/plain',
145 ];
146 }
147
148 /**
149 * Insert a captcha prompt into the edit form.
150 * This sample implementation generates a simple arithmetic operation;
151 * it would be easy to defeat by machine.
152 *
153 * Override this!
154 *
155 * It is not guaranteed that the CAPTCHA will load synchronously with the main page
156 * content. So you can not rely on registering handlers before page load. E.g.:
157 *
158 * NOT SAFE: $( window ).on( 'load', handler )
159 * SAFE: $( handler )
160 *
161 * However, if the HTML is loaded dynamically via AJAX, the following order will
162 * be used.
163 *
164 * headitems => modulestyles + modules => add main HTML to DOM when modulestyles +
165 * modules are ready.
166 *
167 * @param int $tabIndex Tab index to start from
168 *
169 * @return array Associative array with the following keys:
170 * string html - Main HTML
171 * array modules (optional) - Array of ResourceLoader module names
172 * array modulestyles (optional) - Array of ResourceLoader module names to be
173 * included as style-only modules.
174 * array headitems (optional) - Head items (see OutputPage::addHeadItems), as a numeric array
175 * of raw HTML strings. Do not use unless no other option is feasible.
176 */
177 public function getFormInformation( $tabIndex = 1 ) {
178 $captcha = $this->getCaptcha();
179 $index = $this->storeCaptcha( $captcha );
180
181 return [
182 'html' =>
183 new FieldLayout(
184 new NumberInputWidget( [
185 'name' => 'wpCaptchaWord',
186 'classes' => [ 'simplecaptcha-answer' ],
187 'id' => 'wpCaptchaWord',
188 'autocomplete' => 'off',
189 // tab in before the edit textarea
190 'tabIndex' => $tabIndex
191 ] ),
192 [
193 'align' => 'left',
194 'label' => $captcha['question'] . ' = ',
195 'classes' => [ 'simplecaptcha-field' ],
196 ]
197 ) .
198 new HiddenInputWidget( [
199 'name' => 'wpCaptchaId',
200 'id' => 'wpCaptchaId',
201 'value' => $index
202 ] ),
203 'modulestyles' => [
204 'ext.confirmEdit.simpleCaptcha'
205 ]
206 ];
207 }
208
209 /**
210 * @return string[]
211 */
212 public static function getCSPUrls() {
213 return [];
214 }
215
216 /**
217 * Adds the CSP policies necessary for the captcha module to work in a CSP enforced
218 * setup.
219 *
220 * @param ContentSecurityPolicy $csp The CSP instance to add the policies to, usually
221 * obtained from {@link OutputPage::getCSP()}
222 */
223 public static function addCSPSources( ContentSecurityPolicy $csp ) {
224 foreach ( static::getCSPUrls() as $src ) {
225 $csp->addScriptSrc( $src );
226 $csp->addStyleSrc( $src );
227 }
228 }
229
230 /**
231 * Uses getFormInformation() to get the CAPTCHA form and adds it to the given
232 * OutputPage object.
233 *
234 * @param OutputPage $out The OutputPage object to which the form should be added
235 * @param int $tabIndex See self::getFormInformation
236 */
237 public function addFormToOutput( OutputPage $out, $tabIndex = 1 ) {
238 $this->addFormInformationToOutput( $out, $this->getFormInformation( $tabIndex ) );
239 }
240
241 /**
242 * Processes the given $formInformation array and adds the options (see getFormInformation())
243 * to the given OutputPage object.
244 *
245 * @param OutputPage $out The OutputPage object to which the form should be added
246 * @param array $formInformation
247 */
248 public function addFormInformationToOutput( OutputPage $out, array $formInformation ) {
249 static::addCSPSources( $out->getCSP() );
250
251 if ( !$formInformation ) {
252 return;
253 }
254 if ( isset( $formInformation['html'] ) ) {
255 $out->addHTML( $formInformation['html'] );
256 }
257 if ( isset( $formInformation['modules'] ) ) {
258 $out->addModules( $formInformation['modules'] );
259 }
260 if ( isset( $formInformation['modulestyles'] ) ) {
261 $out->addModuleStyles( $formInformation['modulestyles'] );
262 }
263 if ( isset( $formInformation['headitems'] ) ) {
264 $out->addHeadItems( $formInformation['headitems'] );
265 }
266 }
267
268 /**
269 * @param array $captchaData Data given by getCaptcha
270 * @param string $id ID given by storeCaptcha
271 * @return string Description of the captcha. Format is not specified; could be text, HTML, URL...
272 */
273 public function getCaptchaInfo( $captchaData, $id ) {
274 return array_key_exists( 'question', $captchaData ) ? ( $captchaData['question'] . ' =' ) : '';
275 }
276
277 /**
278 * Show error message for missing or incorrect captcha on EditPage.
279 * @param EditPage $editPage
280 * @param OutputPage $out
281 */
282 public function showEditFormFields( EditPage $editPage, OutputPage $out ) {
283 $out->enableOOUI();
284 $page = $editPage->getArticle()->getPage();
285 $key = CacheKeyHelper::getKeyForPage( $page );
286 if ( !isset( $this->activatedCaptchas[$key] ) ) {
287 return;
288 }
289
290 if ( $this->action !== 'edit' ) {
291 unset( $this->activatedCaptchas[$key] );
292 $out->addHTML( $this->getMessage( $this->action )->parseAsBlock() );
293 $this->addFormToOutput( $out );
294 }
295 }
296
297 /**
298 * Insert the captcha prompt into an edit form.
299 * @param EditPage $editPage
300 */
301 public function editShowCaptcha( $editPage ) {
302 $context = $editPage->getArticle()->getContext();
303 $page = $editPage->getArticle()->getPage();
304 $out = $context->getOutput();
305 $key = CacheKeyHelper::getKeyForPage( $page );
306 if ( isset( $this->activatedCaptchas[$key] ) ||
307 $this->shouldCheck( $page, '', '', $context )
308 ) {
309 $out->addHTML( $this->getMessage( $this->action )->parseAsBlock() );
310 $this->addFormToOutput( $out );
311 }
312 unset( $this->activatedCaptchas[$key] );
313 }
314
315 /**
316 * Show a message asking the user to enter a captcha on edit
317 * The result will be treated as wiki text
318 *
319 * @param string $action Action being performed
320 * @return Message
321 */
322 public function getMessage( $action ) {
323 // one of captcha-edit, captcha-addurl, captcha-badlogin, captcha-createaccount,
324 // captcha-create, captcha-sendemail
325 $name = static::$messagePrefix . $action;
326 $msg = wfMessage( $name );
327 // obtain a more tailored message, if possible, otherwise, fall back to
328 // the default for edits
329 return $msg->isDisabled() ? wfMessage( static::$messagePrefix . 'edit' ) : $msg;
330 }
331
332 /**
333 * Inject whazawhoo
334 * @fixme if multiple thingies insert a header, could break
335 * @param HTMLForm $form
336 * @return bool true to keep running callbacks
337 */
338 public function injectEmailUser( HTMLForm $form ) {
339 $out = $form->getOutput();
340 $user = $form->getUser();
341 if ( $this->triggersCaptcha( CaptchaTriggers::SENDEMAIL ) ) {
342 $this->action = 'sendemail';
343 if ( $this->canSkipCaptcha( $user, $form->getConfig() ) ) {
344 return true;
345 }
346 $formInformation = $this->getFormInformation();
347 $formMetainfo = $formInformation;
348 unset( $formMetainfo['html'] );
349 $this->addFormInformationToOutput( $out, $formMetainfo );
350 $form->addFooterHtml(
351 "<div class='captcha'>" .
352 $this->getMessage( 'sendemail' )->parseAsBlock() .
353 $formInformation['html'] .
354 "</div>\n" );
355 }
356 return true;
357 }
358
359 /**
360 * Check if the current IP is allowed to skip solving a captcha.
361 * This checks the bypass list from two sources.
362 * 1) From the server-side config array $wgCaptchaWhitelistIP (deprecated) or $wgCaptchaBypassIPs
363 * 2) From the local [[MediaWiki:Captcha-ip-whitelist]] message
364 *
365 * @return bool true if the IP can bypass a captcha, false if not
366 */
367 private function canIPBypassCaptcha() {
368 global $wgCaptchaWhitelistIP, $wgCaptchaBypassIPs, $wgRequest;
369 $ip = $wgRequest->getIP();
370
371 // Deprecated; to be removed later
372 if ( $wgCaptchaWhitelistIP && IPUtils::isInRanges( $ip, $wgCaptchaWhitelistIP ) ) {
373 return true;
374 }
375
376 if ( $wgCaptchaBypassIPs && IPUtils::isInRanges( $ip, $wgCaptchaBypassIPs ) ) {
377 return true;
378 }
379
380 $msg = wfMessage( 'captcha-ip-whitelist' )->inContentLanguage();
381 if ( !$msg->isDisabled() ) {
382 $allowedIPs = $this->getWikiIPBypassList( $msg );
383 if ( IPUtils::isInRanges( $ip, $allowedIPs ) ) {
384 return true;
385 }
386 }
387
388 return false;
389 }
390
391 /**
392 * Get the on-wiki IP bypass list stored on a MediaWiki page from cache if possible.
393 *
394 * @param Message $msg Message on wiki with IP lists
395 * @return array Allowed IP addresses or IP ranges, empty array if none
396 */
397 private function getWikiIPBypassList( Message $msg ) {
398 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
399 $cacheKey = $cache->makeKey( 'confirmedit', 'ipbypasslist' );
400
401 $cached = $cache->get( $cacheKey );
402 if ( $cached !== false ) {
403 return $cached;
404 }
405
406 // Could not retrieve from cache, so build the list directly
407 // from the MediaWiki page
408 $list = $this->buildValidIPs(
409 explode( "\n", $msg->plain() )
410 );
411 // And then store it in cache for one day.
412 // This cache is cleared on modifications to the wiki page.
413 // @see MediaWiki\Extension\ConfirmEdit\Hooks::onPageSaveComplete()
414 $cache->set( $cacheKey, $list, 86400 );
415
416 return $list;
417 }
418
419 /**
420 * From a list of unvalidated input, get all the valid
421 * IP addresses and IP ranges from it.
422 *
423 * Note that only lines with just the IP address or the IP range is considered
424 * as valid. Whitespace is allowed, but if there is any other character on
425 * the line, it's not considered as a valid entry.
426 *
427 * @param string[] $input
428 * @return string[] of valid IP addresses and IP ranges
429 */
430 private function buildValidIPs( array $input ) {
431 // Remove whitespace and blank lines first
432 $ips = array_map( 'trim', $input );
433 $ips = array_filter( $ips );
434
435 $validIPs = [];
436 foreach ( $ips as $ip ) {
437 if ( IPUtils::isIPAddress( $ip ) ) {
438 $validIPs[] = $ip;
439 }
440 }
441
442 return $validIPs;
443 }
444
445 /**
446 * Check if the submitted form matches the captcha session data provided
447 * by the plugin when the form was generated.
448 *
449 * Override this!
450 *
451 * @param string $answer
452 * @param array $info
453 * @return bool
454 */
455 protected function keyMatch( $answer, $info ) {
456 return $answer == $info['answer'];
457 }
458
459 // ----------------------------------
460
461 /**
462 * @param Title $title
463 * @param string $action (edit/create/addurl...)
464 * @return bool true if action triggers captcha on $title's namespace
465 * @deprecated since 1.5.1 Use triggersCaptcha instead
466 */
467 public function captchaTriggers( $title, $action ) {
468 return $this->triggersCaptcha( $action, $title );
469 }
470
471 /**
472 * Checks, whether the passed action should trigger a CAPTCHA. The optional $title parameter
473 * will be used to check namespace specific CAPTCHA triggers.
474 *
475 * @param string $action The CAPTCHA trigger to check (see CaptchaTriggers for ConfirmEdit
476 * built-in triggers)
477 * @param Title|null $title An optional Title object, if the namespace specific triggers
478 * should be checked, too.
479 * @return bool True, if the action should trigger a CAPTCHA, false otherwise
480 */
481 public function triggersCaptcha( $action, $title = null ) {
482 // Captcha was already solved, we don't need to check anything else.
483 if ( $this->isCaptchaSolved() ) {
484 return false;
485 }
486
487 global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
488
489 $result = false;
490 $triggers = $wgCaptchaTriggers;
491 $attributeCaptchaTriggers = ExtensionRegistry::getInstance()
492 ->getAttribute( CaptchaTriggers::EXT_REG_ATTRIBUTE_NAME );
493 if ( is_array( $attributeCaptchaTriggers ) ) {
494 $triggers += $attributeCaptchaTriggers;
495 }
496
497 if ( isset( $triggers[$action] ) ) {
498 $result = $triggers[$action];
499 }
500
501 if (
502 $title !== null &&
503 isset( $wgCaptchaTriggersOnNamespace[$title->getNamespace()][$action] )
504 ) {
505 $result = $wgCaptchaTriggersOnNamespace[$title->getNamespace()][$action];
506 }
507
508 // SimpleCaptcha has been instructed to force showing the CAPTCHA, no need to
509 // check what other hook implementations think.
510 if ( $this->shouldForceShowCaptcha() ) {
511 return true;
512 }
513
514 $hookRunner = new HookRunner(
515 MediaWikiServices::getInstance()->getHookContainer()
516 );
517 $hookRunner->onConfirmEditTriggersCaptcha( $action, $title, $result );
518
519 return $result;
520 }
521
522 /**
523 * @param WikiPage $page
524 * @param Content|string $content
525 * @param string $section
526 * @param IContextSource $context
527 * @param string|null $oldtext The content of the revision prior to $content When
528 * null this will be loaded from the database.
529 * @return bool true if the captcha should run
530 */
531 public function shouldCheck( WikiPage $page, $content, $section, $context, $oldtext = null ) {
532 if ( !$context instanceof IContextSource ) {
533 $context = RequestContext::getMain();
534 }
535
536 $request = $context->getRequest();
537 $user = $context->getUser();
538
539 if ( $this->canSkipCaptcha( $user, $context->getConfig() ) ) {
540 return false;
541 }
542
543 $title = $page->getTitle();
544 $this->trigger = '';
545
546 if ( $content instanceof Content ) {
547 if ( $content->getModel() == CONTENT_MODEL_WIKITEXT ) {
548 $newtext = $content->getNativeData();
549 } else {
550 $newtext = null;
551 }
552 $isEmpty = $content->isEmpty();
553 } else {
554 $newtext = $content;
555 $isEmpty = $content === '';
556 }
557
558 if ( $this->triggersCaptcha( 'edit', $title ) ) {
559 // Check on all edits
560 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
561 $user->getName(),
562 $title->getPrefixedText() );
563 $this->action = 'edit';
564 wfDebug( "ConfirmEdit: checking all edits...\n" );
565 return true;
566 }
567
568 if ( $this->triggersCaptcha( 'create', $title ) && !$title->exists() ) {
569 // Check if creating a page
570 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
571 $user->getName(),
572 $title->getPrefixedText() );
573 $this->action = 'create';
574 wfDebug( "ConfirmEdit: checking on page creation...\n" );
575 return true;
576 }
577
578 // The following checks are expensive and should be done only,
579 // if we can assume, that the edit will be saved
580 if ( !$request->wasPosted() ) {
581 wfDebug(
582 "ConfirmEdit: request not posted, assuming that no content will be saved -> no CAPTCHA check"
583 );
584 return false;
585 }
586
587 if ( !$isEmpty && $this->triggersCaptcha( 'addurl', $title ) ) {
588 // Only check edits that add URLs
589 if ( $content instanceof Content ) {
590 // Get links from the database
591 $oldLinks = ExternalLinksLookup::getExternalLinksForPage(
592 $title->getArticleID(),
593 MediaWikiServices::getInstance()
594 ->getConnectionProvider()
595 ->getReplicaDatabase(),
596 __METHOD__
597 );
598 // Share a parse operation with Article::doEdit()
599 $editInfo = $page->prepareContentForEdit( $content, null, $user );
600 if ( $editInfo->output ) {
601 $newLinks = LinkFilter::getIndexedUrlsNonReversed(
602 array_keys( $editInfo->output->getExternalLinks() )
603 );
604 } else {
605 $newLinks = [];
606 }
607 } else {
608 // Get link changes in the slowest way known to man
609 $oldtext ??= $this->loadText( $title, $section );
610 $oldLinks = $this->findLinks( $title, $oldtext );
611 $newLinks = $this->findLinks( $title, $newtext );
612 }
613
614 $unknownLinks = array_filter( $newLinks, [ $this, 'filterLink' ] );
615 $addedLinks = array_diff( $unknownLinks, $oldLinks );
616 $numLinks = count( $addedLinks );
617
618 if ( $numLinks > 0 ) {
619 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
620 $numLinks,
621 $user->getName(),
622 $title->getPrefixedText(),
623 implode( ", ", $addedLinks ) );
624 $this->action = 'addurl';
625 return true;
626 }
627 }
628
629 global $wgCaptchaRegexes;
630 if ( $newtext !== null && $wgCaptchaRegexes ) {
631 if ( !is_array( $wgCaptchaRegexes ) ) {
632 throw new UnexpectedValueException(
633 '$wgCaptchaRegexes is required to be an array, ' . get_debug_type( $wgCaptchaRegexes ) . ' given.'
634 );
635 }
636 // Custom regex checks. Reuse $oldtext if set above.
637 $oldtext ??= $this->loadText( $title, $section );
638
639 foreach ( $wgCaptchaRegexes as $regex ) {
640 $newMatches = [];
641 if ( preg_match_all( $regex, $newtext, $newMatches ) ) {
642 $oldMatches = [];
643 preg_match_all( $regex, $oldtext, $oldMatches );
644
645 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
646
647 $numHits = count( $addedMatches );
648 if ( $numHits > 0 ) {
649 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
650 $numHits,
651 $regex,
652 $user->getName(),
653 $title->getPrefixedText(),
654 implode( ", ", $addedMatches ) );
655 $this->action = 'edit';
656 return true;
657 }
658 }
659 }
660 }
661
662 return false;
663 }
664
665 public function isCaptchaSolved(): ?bool {
666 return $this->captchaSolved;
667 }
668
669 protected function setCaptchaSolved( ?bool $captchaSolved ): void {
670 $this->captchaSolved = $captchaSolved;
671 }
672
673 /**
674 * @return bool True if an override is set to force showing a CAPTCHA
675 * to the user. Note that users with "skipcaptcha" right may still
676 * bypass this override.
677 */
678 public function shouldForceShowCaptcha(): bool {
679 return $this->forceShowCaptcha;
680 }
681
682 /**
683 * @param bool $forceShowCaptcha True if the caller wants to force showing
684 * a CAPTCHA to the user. Note that users with "skipcaptcha" right may
685 * still bypass this override.
686 * @return void
687 */
688 public function setForceShowCaptcha( bool $forceShowCaptcha ): void {
689 $this->forceShowCaptcha = $forceShowCaptcha;
690 }
691
692 /**
693 * @return bool Was the EditFilterMergedContent hook implementation already
694 * invoked?
695 */
696 public function editFilterMergedContentHandlerAlreadyInvoked(): bool {
697 return $this->editFilterMergedContentHandlerCalled;
698 }
699
700 /**
701 * @return void Set a flag on the class stating that EditFilterMergedContent handler
702 * was already run.
703 */
704 public function setEditFilterMergedContentHandlerInvoked(): void {
705 $this->editFilterMergedContentHandlerCalled = true;
706 }
707
708 /**
709 * Filter callback function for URL allow-listing
710 * @param string $url string to check
711 * @return bool true if unknown, false if allowed
712 */
713 private function filterLink( $url ) {
714 global $wgCaptchaWhitelist, $wgCaptchaIgnoredUrls;
715 static $regexes = null;
716
717 if ( $regexes === null ) {
718 $source = wfMessage( 'captcha-addurl-whitelist' )->inContentLanguage();
719
720 $regexes = $source->isDisabled()
721 ? []
722 : $this->buildRegexes( explode( "\n", $source->plain() ) );
723
724 // DEPRECATED
725 if ( $wgCaptchaWhitelist !== false ) {
726 array_unshift( $regexes, $wgCaptchaWhitelist );
727 }
728 if ( $wgCaptchaIgnoredUrls !== false ) {
729 array_unshift( $regexes, $wgCaptchaIgnoredUrls );
730 }
731 }
732
733 foreach ( $regexes as $regex ) {
734 if ( preg_match( $regex, $url ) ) {
735 return false;
736 }
737 }
738
739 return true;
740 }
741
742 /**
743 * Build regex from list of URLs
744 * @param string[] $lines string from MediaWiki page
745 * @return string[] Regexes
746 * @private
747 */
748 private function buildRegexes( $lines ) {
749 # Code duplicated from the SpamBlacklist extension (r19197)
750 # and later modified.
751
752 # Strip comments and whitespace, then remove blanks
753 $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
754
755 # No lines, don't make a regex which will match everything
756 if ( count( $lines ) === 0 ) {
757 wfDebug( "No lines\n" );
758 return [];
759 } else {
760 # Make regex
761 # It's faster using the S modifier even though it will usually only be run once
762 // $regex = 'http://+[a-z0-9_\-.]*(' . implode( '|', $lines ) . ')';
763 // return '/' . str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $regex) ) . '/Si';
764 $regexes = [];
765 $regexStart = [
766 'normal' => '/^(?:https?:)?\/\/+[a-z0-9_\-.]*(?:',
767 'noprotocol' => '/^(?:',
768 ];
769 $regexEnd = [
770 'normal' => ')/Si',
771 'noprotocol' => ')/Si',
772 ];
773 $regexMax = 4096;
774 $build = [];
775 foreach ( $lines as $line ) {
776 # Extract flags from the line
777 $options = [];
778 if ( preg_match( '/^(.*?)\s*<([^<>]*)>$/', $line, $matches ) ) {
779 if ( $matches[1] === '' ) {
780 wfDebug( "Line with empty regex\n" );
781 continue;
782 }
783 $line = $matches[1];
784 $opts = preg_split( '/\s*\|\s*/', trim( $matches[2] ) );
785 foreach ( $opts as $opt ) {
786 $opt = strtolower( $opt );
787 if ( $opt == 'noprotocol' ) {
788 $options['noprotocol'] = true;
789 }
790 }
791 }
792
793 $key = isset( $options['noprotocol'] ) ? 'noprotocol' : 'normal';
794
795 // FIXME: not very robust size check, but should work. :)
796 if ( !isset( $build[$key] ) ) {
797 $build[$key] = $line;
798 } elseif ( strlen( $build[$key] ) + strlen( $line ) > $regexMax ) {
799 $regexes[] = $regexStart[$key] .
800 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build[$key] ) ) .
801 $regexEnd[$key];
802 $build[$key] = $line;
803 } else {
804 $build[$key] .= '|' . $line;
805 }
806 }
807 foreach ( $build as $key => $value ) {
808 $regexes[] = $regexStart[$key] .
809 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $value ) ) .
810 $regexEnd[$key];
811 }
812 return $regexes;
813 }
814 }
815
816 /**
817 * Backend function for confirmEditMerged()
818 * @param WikiPage $page
819 * @param Content|string $newtext
820 * @param string $section
821 * @param IContextSource $context
822 * @param User $user
823 * @return bool false if the CAPTCHA is rejected, true otherwise
824 */
825 private function doConfirmEdit(
826 WikiPage $page,
827 $newtext,
828 $section,
829 IContextSource $context,
830 User $user
831 ) {
832 global $wgRequest;
833 $request = $context->getRequest();
834
835 // FIXME: Stop using wgRequest in other parts of ConfirmEdit so we can
836 // stop having to duplicate code for it.
837 if ( $request->getVal( 'captchaid' ) ) {
838 $request->setVal( 'wpCaptchaId', $request->getVal( 'captchaid' ) );
839 $wgRequest->setVal( 'wpCaptchaId', $request->getVal( 'captchaid' ) );
840 }
841 if ( $request->getVal( 'captchaword' ) ) {
842 $request->setVal( 'wpCaptchaWord', $request->getVal( 'captchaword' ) );
843 $wgRequest->setVal( 'wpCaptchaWord', $request->getVal( 'captchaword' ) );
844 }
845 if ( $this->shouldCheck( $page, $newtext, $section, $context ) ) {
846 return $this->passCaptchaLimitedFromRequest( $wgRequest, $user );
847 } else {
848 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
849 return true;
850 }
851 }
852
853 /**
854 * An efficient edit filter callback based on the text after section merging
855 * @param IContextSource $context
856 * @param Content $content
857 * @param Status $status
858 * @param string $summary
859 * @param User $user
860 * @param bool $minorEdit
861 * @return bool
862 */
863 public function confirmEditMerged( $context, $content, $status, $summary, $user, $minorEdit ) {
864 $title = $context->getTitle();
865 if ( !( $title->canExist() ) ) {
866 // we check WikiPage only
867 // try to get an appropriate title for this page
868 $title = $context->getTitle();
869 if ( $title instanceof Title ) {
870 $title = $title->getFullText();
871 } else {
872 // otherwise it's an unknown page where this function is called from
873 $title = 'unknown';
874 }
875 // log this error, it could be a problem in another extension,
876 // edits should always have a WikiPage if
877 // they go through EditFilterMergedContent.
878 wfDebug( __METHOD__ . ': Skipped ConfirmEdit check: No WikiPage for title ' . $title );
879 return true;
880 }
881 $page = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $title );
882 if ( !$this->doConfirmEdit( $page, $content, '', $context, $user ) ) {
883 $status->value = EditPage::AS_HOOK_ERROR_EXPECTED;
884 $status->statusData = [];
885 // give an error message for the user to know, what goes wrong here.
886 // this can't be done for addurl trigger, because this requires one "free" save
887 // for the user, which we don't know, when he did it.
888 if ( $this->action === 'edit' ) {
889 // Default message is that the user failed a CAPTCHA, so show 'captcha-edit-fail'.
890 $message = 'captcha-edit-fail';
891 if ( $this->shouldForceShowCaptcha() ) {
892 // If an extension set the forceShowCaptcha property, then it likely means
893 // that the user already submitted an edit, and so the 'captcha-edit'
894 // message is more appropriate.
895 $message = 'captcha-edit';
896 [ $_index, $word ] = $this->getCaptchaParamsFromRequest(
897 RequestContext::getMain()->getRequest()
898 );
899 // But if there's a word supplied in the request, then we should
900 // use 'captcha-edit-fail' as it indicates a failed attempt
901 // at solving the CAPTCHA by the user.
902 if ( $word ) {
903 $message = 'captcha-edit-fail';
904 }
905 }
906 $status->fatal( $message );
907 }
908 $this->addCaptchaAPI( $status->statusData );
909 $key = CacheKeyHelper::getKeyForPage( $page );
910 $this->activatedCaptchas[$key] = true;
911 return false;
912 }
913 return true;
914 }
915
916 /**
917 * Logic to check if we need to pass a captcha for the current user
918 * to create a new account, or not
919 *
920 * @param User $creatingUser
921 * @return bool true to show captcha, false to skip captcha
922 */
923 public function needCreateAccountCaptcha( User $creatingUser ) {
924 if ( $this->triggersCaptcha( CaptchaTriggers::CREATE_ACCOUNT ) ) {
925 if ( $this->canSkipCaptcha( $creatingUser,
926 \MediaWiki\MediaWikiServices::getInstance()->getMainConfig() ) ) {
927 return false;
928 }
929 return true;
930 }
931 return false;
932 }
933
934 /**
935 * Check the captcha on Special:EmailUser
936 * @param MailAddress $from
937 * @param MailAddress $to
938 * @param string $subject
939 * @param string $text
940 * @param string &$error
941 * @return bool true to continue saving, false to abort and show a captcha form
942 */
943 public function confirmEmailUser( $from, $to, $subject, $text, &$error ) {
944 global $wgRequest;
945
946 $user = RequestContext::getMain()->getUser();
947 if ( $this->triggersCaptcha( CaptchaTriggers::SENDEMAIL ) ) {
948 if ( $this->canSkipCaptcha( $user,
949 \MediaWiki\MediaWikiServices::getInstance()->getMainConfig() ) ) {
950 return true;
951 }
952
953 if ( defined( 'MW_API' ) ) {
954 # API mode
955 # Asking for captchas in the API is really silly
956 $error = Status::newFatal( 'captcha-disabledinapi' );
957 return false;
958 }
959 $this->trigger = "{$user->getName()} sending email";
960 if ( !$this->passCaptchaLimitedFromRequest( $wgRequest, $user ) ) {
961 $error = Status::newFatal( 'captcha-sendemail-fail' );
962 return false;
963 }
964 }
965 return true;
966 }
967
968 /**
969 * @param ApiBase $module
970 * @return bool
971 */
972 protected function isAPICaptchaModule( $module ) {
973 return $module instanceof ApiEditPage;
974 }
975
976 /**
977 * @param ApiBase $module
978 * @param array &$params
979 * @param int $flags
980 * @return bool
981 */
982 public function apiGetAllowedParams( ApiBase $module, &$params, $flags ) {
983 if ( $this->isAPICaptchaModule( $module ) ) {
984 $params['captchaword'] = [
985 ApiBase::PARAM_HELP_MSG => 'captcha-apihelp-param-captchaword',
986 ];
987 $params['captchaid'] = [
988 ApiBase::PARAM_HELP_MSG => 'captcha-apihelp-param-captchaid',
989 ];
990 }
991
992 return true;
993 }
994
995 /**
996 * Checks, if the user reached the amount of false CAPTCHAs and give him some vacation
997 * or run self::passCaptcha() and clear counter if correct.
998 *
999 * @param WebRequest $request
1000 * @param User $user
1001 * @return bool
1002 */
1003 public function passCaptchaLimitedFromRequest( WebRequest $request, User $user ) {
1004 [ $index, $word ] = $this->getCaptchaParamsFromRequest( $request );
1005 return $this->passCaptchaLimited( $index, $word, $user );
1006 }
1007
1008 /**
1009 * @param WebRequest $request
1010 * @return string[]|null[] [ captcha ID, captcha solution ]
1011 */
1012 protected function getCaptchaParamsFromRequest( WebRequest $request ) {
1013 $index = $request->getVal( 'wpCaptchaId' );
1014 $word = $request->getVal( 'wpCaptchaWord' );
1015 return [ $index, $word ];
1016 }
1017
1018 /**
1019 * Checks, if the user reached the amount of false CAPTCHAs and give him some vacation
1020 * or run self::passCaptcha() and clear counter if correct.
1021 *
1022 * @param string|null $index Captcha identifier
1023 * @param string|null $word Captcha solution
1024 * @param User $user User for throttling captcha solving attempts
1025 * @return bool
1026 * @see self::passCaptcha()
1027 */
1028 public function passCaptchaLimited( $index, $word, User $user ) {
1029 // don't increase pingLimiter here, just check, if CAPTCHA limit exceeded
1030 if ( $user->pingLimiter( 'badcaptcha', 0 ) ) {
1031 // for debugging add an proper error message, the user just see an false captcha error message
1032 $this->log( 'User reached RateLimit, preventing action' );
1033 return false;
1034 }
1035
1036 if ( $this->passCaptcha( $index, $word ) ) {
1037 return true;
1038 }
1039
1040 // captcha was not solved: increase limit and return false
1041 $user->pingLimiter( 'badcaptcha' );
1042 return false;
1043 }
1044
1045 /**
1046 * Given a required captcha run, test form input for correct
1047 * input on the open session.
1048 * @param WebRequest $request
1049 * @param User $user
1050 * @return bool if passed, false if failed or new session
1051 */
1052 public function passCaptchaFromRequest( WebRequest $request, User $user ) {
1053 [ $index, $word ] = $this->getCaptchaParamsFromRequest( $request );
1054 return $this->passCaptcha( $index, $word );
1055 }
1056
1057 /**
1058 * Given a required captcha run, test form input for correct
1059 * input on the open session.
1060 * @param string|null $index Captcha identifier
1061 * @param string|null $word Captcha solution
1062 * @return bool if passed, false if failed or new session
1063 */
1064 protected function passCaptcha( $index, $word ) {
1065 // Don't check the same CAPTCHA twice in one session,
1066 // if the CAPTCHA was already checked - Bug T94276
1067 if ( $this->isCaptchaSolved() !== null ) {
1068 return (bool)$this->isCaptchaSolved();
1069 }
1070
1071 if ( $index === null ) {
1072 $this->log( "new captcha session" );
1073 // If no captcha ID was passed, we need to start a new session (T384858).
1074 return false;
1075 }
1076
1077 $info = $this->retrieveCaptcha( $index );
1078 if ( $info ) {
1079 if ( $this->keyMatch( $word, $info ) ) {
1080 $this->log( "passed" );
1081 $this->clearCaptcha( $index );
1082 $this->setCaptchaSolved( true );
1083 return true;
1084 } else {
1085 $this->clearCaptcha( $index );
1086 $this->log( "bad form input" );
1087 $this->setCaptchaSolved( false );
1088 return false;
1089 }
1090 } else {
1091 $this->log( "new captcha session" );
1092 return false;
1093 }
1094 }
1095
1096 /**
1097 * Log the status and any triggering info for debugging or statistics
1098 * @param string $message
1099 */
1100 protected function log( $message ) {
1101 wfDebugLog(
1102 'captcha',
1103 'ConfirmEdit: ' . $message . '; {trigger}',
1104 'all',
1105 [ 'trigger' => $this->trigger ]
1106 );
1107 }
1108
1109 /**
1110 * Generate a captcha session ID and save the info in PHP's session storage.
1111 * (Requires the user to have cookies enabled to get through the captcha.)
1112 *
1113 * A random ID is used so legit users can make edits in multiple tabs or
1114 * windows without being unnecessarily hobbled by a serial order requirement.
1115 * Pass the returned id value into the edit form as wpCaptchaId.
1116 *
1117 * @param array $info data to store
1118 * @return string captcha ID key
1119 */
1120 public function storeCaptcha( $info ) {
1121 if ( !isset( $info['index'] ) ) {
1122 // Assign random index if we're not updating
1123 $info['index'] = (string)random_int( 0, PHP_INT_MAX );
1124 }
1125 CaptchaStore::get()->store( $info['index'], $info );
1126 return $info['index'];
1127 }
1128
1129 /**
1130 * Fetch this session's captcha info.
1131 * @param string $index
1132 * @return array|false array of info, or false if missing
1133 */
1134 public function retrieveCaptcha( $index ) {
1135 return CaptchaStore::get()->retrieve( $index );
1136 }
1137
1138 /**
1139 * Clear out existing captcha info from the session, to ensure
1140 * it can't be reused.
1141 * @param string $index
1142 */
1143 public function clearCaptcha( $index ) {
1144 CaptchaStore::get()->clear( $index );
1145 }
1146
1147 /**
1148 * Retrieve the current version of the page or section being edited...
1149 * @param Title $title
1150 * @param string $section
1151 * @param int $flags Flags for Revision loading methods
1152 * @return string
1153 * @private
1154 */
1155 private function loadText( $title, $section, $flags = IDBAccessObject::READ_LATEST ) {
1156 $revRecord = MediaWikiServices::getInstance()
1157 ->getRevisionLookup()
1158 ->getRevisionByTitle( $title, 0, $flags );
1159
1160 if ( $revRecord === null ) {
1161 return "";
1162 }
1163
1164 try {
1165 $content = $revRecord->getContent( SlotRecord::MAIN );
1166 } catch ( RevisionAccessException $e ) {
1167 return '';
1168 }
1169
1170 $text = ( $content instanceof TextContent ) ? $content->getText() : null;
1171 if ( $section !== '' ) {
1172 return MediaWikiServices::getInstance()->getParser()
1173 ->getSection( $text, $section );
1174 }
1175
1176 return $text;
1177 }
1178
1179 /**
1180 * Extract a list of all recognized HTTP links in the text.
1181 * @param Title $title
1182 * @param string $text
1183 * @return string[]
1184 */
1185 private function findLinks( $title, $text ) {
1186 $parser = MediaWikiServices::getInstance()->getParser();
1187 $user = $parser->getUserIdentity();
1188 $options = new ParserOptions( $user );
1189 $text = $parser->preSaveTransform( $text, $title, $user, $options );
1190 $out = $parser->parse( $text, $title, $options );
1191
1192 return array_keys( $out->getExternalLinks() );
1193 }
1194
1195 /**
1196 * Show a page explaining what this wacky thing is.
1197 */
1198 public function showHelp() {
1199 $context = RequestContext::getMain();
1200 $out = $context->getOutput();
1201 $out->setPageTitleMsg( $context->msg( 'captchahelp-title' ) );
1202 $out->addWikiMsg( 'captchahelp-text' );
1203 if ( CaptchaStore::get()->cookiesNeeded() ) {
1204 $out->addWikiMsg( 'captchahelp-cookies-needed' );
1205 }
1206 }
1207
1208 /**
1209 * @return CaptchaAuthenticationRequest
1210 */
1211 public function createAuthenticationRequest() {
1212 $captchaData = $this->getCaptcha();
1213 $id = $this->storeCaptcha( $captchaData );
1214 return new CaptchaAuthenticationRequest( $id, $captchaData );
1215 }
1216
1217 /**
1218 * Modify the appearance of the captcha field
1219 * @param AuthenticationRequest[] $requests
1220 * @param array $fieldInfo Field description as given by AuthenticationRequest::mergeFieldInfo
1221 * @param array &$formDescriptor A form descriptor suitable for the HTMLForm constructor
1222 * @param string $action One of the AuthManager::ACTION_* constants
1223 */
1224 public function onAuthChangeFormFields(
1225 array $requests, array $fieldInfo, array &$formDescriptor, $action
1226 ) {
1227 $req = AuthenticationRequest::getRequestByClass( $requests,
1228 CaptchaAuthenticationRequest::class );
1229 if ( !$req ) {
1230 return;
1231 }
1232
1233 $formDescriptor['captchaWord'] = [
1234 'label-message' => null,
1235 'autocomplete' => false,
1236 'persistent' => false,
1237 'required' => true,
1238 ] + $formDescriptor['captchaWord'];
1239 }
1240
1241 /**
1242 * Check whether the user provided / IP making the request is allowed to skip captchas
1243 * @param User $user
1244 * @param Config $config
1245 * @return bool
1246 * @throws ConfigException
1247 */
1248 public function canSkipCaptcha( $user, Config $config ) {
1249 $allowConfirmEmail = $config->get( 'AllowConfirmedEmail' );
1250
1251 if ( $user->isAllowed( 'skipcaptcha' ) ) {
1252 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
1253 return true;
1254 }
1255
1256 if ( $this->canIPBypassCaptcha() ) {
1257 wfDebug( "ConfirmEdit: user IP can bypass captcha" );
1258 return true;
1259 }
1260 if ( $user->isSystemUser() ) {
1261 wfDebug( "ConfirmEdit: system user skips captcha\n" );
1262 return true;
1263 }
1264
1265 if ( $allowConfirmEmail && $user->isEmailConfirmed() ) {
1266 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
1267 return true;
1268 }
1269
1270 return false;
1271 }
1272 }