MediaWiki REL1_31
Captcha.php
Go to the documentation of this file.
1<?php
2
4
9 protected static $messagePrefix = 'captcha-';
10
12 private $captchaSolved = null;
13
19 protected $action;
20
22 protected $trigger;
23
27 public function setAction( $action ) {
28 $this->action = $action;
29 }
30
34 public function setTrigger( $trigger ) {
35 $this->trigger = $trigger;
36 }
37
43 public function getError() {
44 return null;
45 }
46
53 function getCaptcha() {
54 $a = mt_rand( 0, 100 );
55 $b = mt_rand( 0, 10 );
56
57 /* Minus sign is used in the question. UTF-8,
58 since the api uses text/plain, not text/html */
59 $op = mt_rand( 0, 1 ) ? '+' : '−';
60
61 // No space before and after $op, to ensure correct
62 // directionality.
63 $test = "$a$op$b";
64 $answer = ( $op == '+' ) ? ( $a + $b ) : ( $a - $b );
65 return [ 'question' => $test, 'answer' => $answer ];
66 }
67
71 function addCaptchaAPI( &$resultArr ) {
72 $captcha = $this->getCaptcha();
73 $index = $this->storeCaptcha( $captcha );
74 $resultArr['captcha'] = $this->describeCaptchaType();
75 $resultArr['captcha']['id'] = $index;
76 $resultArr['captcha']['question'] = $captcha['question'];
77 }
78
84 public function describeCaptchaType() {
85 return [
86 'type' => 'simple',
87 'mime' => 'text/plain',
88 ];
89 }
90
120 public function getFormInformation( $tabIndex = 1 ) {
121 $captcha = $this->getCaptcha();
122 $index = $this->storeCaptcha( $captcha );
123
124 return [
125 'html' => "<p><label for=\"wpCaptchaWord\">{$captcha['question']} = </label>" .
126 Xml::element( 'input', [
127 'name' => 'wpCaptchaWord',
128 'class' => 'mw-ui-input',
129 'id' => 'wpCaptchaWord',
130 'size' => 5,
131 'autocomplete' => 'off',
132 'tabindex' => $tabIndex ] ) . // tab in before the edit textarea
133 "</p>\n" .
134 Xml::element( 'input', [
135 'type' => 'hidden',
136 'name' => 'wpCaptchaId',
137 'id' => 'wpCaptchaId',
138 'value' => $index ] )
139 ];
140 }
141
149 public function addFormToOutput( OutputPage $out, $tabIndex = 1 ) {
150 $this->addFormInformationToOutput( $out, $this->getFormInformation( $tabIndex ) );
151 }
152
160 public function addFormInformationToOutput( OutputPage $out, array $formInformation ) {
161 if ( !$formInformation ) {
162 return;
163 }
164 if ( isset( $formInformation['html'] ) ) {
165 $out->addHTML( $formInformation['html'] );
166 }
167 if ( isset( $formInformation['modules'] ) ) {
168 $out->addModules( $formInformation['modules'] );
169 }
170 if ( isset( $formInformation['modulestyles'] ) ) {
171 $out->addModuleStyles( $formInformation['modulestyles'] );
172 }
173 if ( isset( $formInformation['headitems'] ) ) {
174 $out->addHeadItems( $formInformation['headitems'] );
175 }
176 }
177
183 public function getCaptchaInfo( $captchaData, $id ) {
184 return $captchaData['question'] . ' =';
185 }
186
192 function showEditFormFields( &$editPage, &$out ) {
193 $page = $editPage->getArticle()->getPage();
194 if ( !isset( $page->ConfirmEdit_ActivateCaptcha ) ) {
195 return;
196 }
197
198 if ( $this->action !== 'edit' ) {
199 unset( $page->ConfirmEdit_ActivateCaptcha );
200 $out->addWikiText( $this->getMessage( $this->action )->text() );
201 $this->addFormToOutput( $out );
202 }
203 }
204
209 function editShowCaptcha( $editPage ) {
210 $context = $editPage->getArticle()->getContext();
211 $page = $editPage->getArticle()->getPage();
212 $out = $context->getOutput();
213 if ( isset( $page->ConfirmEdit_ActivateCaptcha ) ||
214 $this->shouldCheck( $page, '', '', $context )
215 ) {
216 $out->addWikiText( $this->getMessage( $this->action )->text() );
217 $this->addFormToOutput( $out );
218 }
219 unset( $page->ConfirmEdit_ActivateCaptcha );
220 }
221
229 public function getMessage( $action ) {
230 // one of captcha-edit, captcha-addurl, captcha-badlogin, captcha-createaccount,
231 // captcha-create, captcha-sendemail
232 $name = static::$messagePrefix . $action;
233 $msg = wfMessage( $name );
234 // obtain a more tailored message, if possible, otherwise, fall back to
235 // the default for edits
236 return $msg->isDisabled() ? wfMessage( static::$messagePrefix . 'edit' ) : $msg;
237 }
238
245 function injectEmailUser( &$form ) {
246 $out = $form->getOutput();
247 $user = $form->getUser();
249 $this->action = 'sendemail';
250 if ( $user->isAllowed( 'skipcaptcha' ) ) {
251 wfDebug( "ConfirmEdit: user group allows skipping captcha on email sending\n" );
252 return true;
253 }
254 $formInformation = $this->getFormInformation();
255 $formMetainfo = $formInformation;
256 unset( $formMetainfo['html'] );
257 $this->addFormInformationToOutput( $out, $formMetainfo );
258 $form->addFooterText(
259 "<div class='captcha'>" .
260 $out->parse( $this->getMessage( 'sendemail' )->text() ) .
261 $formInformation['html'] .
262 "</div>\n" );
263 }
264 return true;
265 }
266
274 global $wgCaptchaBadLoginExpiration, $wgCaptchaBadLoginPerUserExpiration;
275
276 $cache = ObjectCache::getLocalClusterInstance();
277
279 $key = $this->badLoginKey();
280 $count = ObjectCache::getLocalClusterInstance()->get( $key );
281 if ( !$count ) {
282 $cache->add( $key, 0, $wgCaptchaBadLoginExpiration );
283 }
284
285 $cache->incr( $key );
286 }
287
289 $key = $this->badLoginPerUserKey( $username );
290 $count = $cache->get( $key );
291 if ( !$count ) {
292 $cache->add( $key, 0, $wgCaptchaBadLoginPerUserExpiration );
293 }
294
295 $cache->incr( $key );
296 }
297 }
298
303 public function resetBadLoginCounter( $username ) {
305 $cache = ObjectCache::getLocalClusterInstance();
306 $cache->delete( $this->badLoginPerUserKey( $username ) );
307 }
308 }
309
316 public function isBadLoginTriggered() {
317 global $wgCaptchaBadLoginAttempts;
318
319 $cache = ObjectCache::getLocalClusterInstance();
321 && (int)$cache->get( $this->badLoginKey() ) >= $wgCaptchaBadLoginAttempts;
322 }
323
330 public function isBadLoginPerUserTriggered( $u ) {
331 global $wgCaptchaBadLoginPerUserAttempts;
332
333 $cache = ObjectCache::getLocalClusterInstance();
334
335 if ( is_object( $u ) ) {
336 $u = $u->getName();
337 }
339 && (int)$cache->get( $this->badLoginPerUserKey( $u ) ) >= $wgCaptchaBadLoginPerUserAttempts;
340 }
341
350 function isIPWhitelisted() {
351 global $wgCaptchaWhitelistIP, $wgRequest;
352 $ip = $wgRequest->getIP();
353
354 if ( $wgCaptchaWhitelistIP ) {
355 if ( IP::isInRanges( $ip, $wgCaptchaWhitelistIP ) ) {
356 return true;
357 }
358 }
359
360 $whitelistMsg = wfMessage( 'captcha-ip-whitelist' )->inContentLanguage();
361 if ( !$whitelistMsg->isDisabled() ) {
362 $whitelistedIPs = $this->getWikiIPWhitelist( $whitelistMsg );
363 if ( IP::isInRanges( $ip, $whitelistedIPs ) ) {
364 return true;
365 }
366 }
367
368 return false;
369 }
370
378 private function getWikiIPWhitelist( Message $msg ) {
379 $cache = ObjectCache::getMainWANInstance();
380 $cacheKey = $cache->makeKey( 'confirmedit', 'ipwhitelist' );
381
382 $cachedWhitelist = $cache->get( $cacheKey );
383 if ( $cachedWhitelist === false ) {
384 // Could not retrieve from cache so build the whitelist directly
385 // from the wikipage
386 $whitelist = $this->buildValidIPs(
387 explode( "\n", $msg->plain() )
388 );
389 // And then store it in cache for one day. This cache is cleared on
390 // modifications to the whitelist page.
391 // @see ConfirmEditHooks::onPageContentSaveComplete()
392 $cache->set( $cacheKey, $whitelist, 86400 );
393 } else {
394 // Whitelist from the cache
395 $whitelist = $cachedWhitelist;
396 }
397
398 return $whitelist;
399 }
400
412 private function buildValidIPs( array $input ) {
413 // Remove whitespace and blank lines first
414 $ips = array_map( 'trim', $input );
415 $ips = array_filter( $ips );
416
417 $validIPs = [];
418 foreach ( $ips as $ip ) {
419 if ( IP::isIPAddress( $ip ) ) {
420 $validIPs[] = $ip;
421 }
422 }
423
424 return $validIPs;
425 }
426
431 private function badLoginKey() {
432 global $wgRequest;
433 $ip = $wgRequest->getIP();
434 return wfGlobalCacheKey( 'captcha', 'badlogin', 'ip', $ip );
435 }
436
442 private function badLoginPerUserKey( $username ) {
444 return wfGlobalCacheKey( 'captcha', 'badlogin', 'user', md5( $username ) );
445 }
446
457 function keyMatch( $answer, $info ) {
458 return $answer == $info['answer'];
459 }
460
461 // ----------------------------------
462
469 public function captchaTriggers( $title, $action ) {
470 return $this->triggersCaptcha( $action, $title );
471 }
472
483 public function triggersCaptcha( $action, $title = null ) {
484 global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
485
486 $result = false;
487 $triggers = $wgCaptchaTriggers;
488 $attributeCaptchaTriggers = ExtensionRegistry::getInstance()
490 if ( is_array( $attributeCaptchaTriggers ) ) {
491 $triggers += $attributeCaptchaTriggers;
492 }
493
494 if ( isset( $triggers[$action] ) ) {
495 $result = $triggers[$action];
496 }
497
498 if (
499 $title !== null &&
500 isset( $wgCaptchaTriggersOnNamespace[$title->getNamespace()][$action] )
501 ) {
502 $result = $wgCaptchaTriggersOnNamespace[$title->getNamespace()][$action];
503 }
504
505 return $result;
506 }
507
517 function shouldCheck( WikiPage $page, $content, $section, $context, $oldtext = null ) {
518 global $wgAllowConfirmedEmail;
519
520 if ( !$context instanceof IContextSource ) {
522 }
523
524 $request = $context->getRequest();
525 $user = $context->getUser();
526
527 // captcha check exceptions, which will return always false
528 if ( $user->isAllowed( 'skipcaptcha' ) ) {
529 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
530 return false;
531 } elseif ( $this->isIPWhitelisted() ) {
532 wfDebug( "ConfirmEdit: user IP is whitelisted" );
533 return false;
534 } elseif ( $wgAllowConfirmedEmail && $user->isEmailConfirmed() ) {
535 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
536 return false;
537 }
538
539 $title = $page->getTitle();
540 $this->trigger = '';
541
542 if ( $content instanceof Content ) {
543 if ( $content->getModel() == CONTENT_MODEL_WIKITEXT ) {
544 $newtext = $content->getNativeData();
545 } else {
546 $newtext = null;
547 }
548 $isEmpty = $content->isEmpty();
549 } else {
550 $newtext = $content;
551 $isEmpty = $content === '';
552 }
553
554 if ( $this->triggersCaptcha( 'edit', $title ) ) {
555 // Check on all edits
556 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
557 $user->getName(),
558 $title->getPrefixedText() );
559 $this->action = 'edit';
560 wfDebug( "ConfirmEdit: checking all edits...\n" );
561 return true;
562 }
563
564 if ( $this->triggersCaptcha( 'create', $title ) && !$title->exists() ) {
565 // Check if creating a page
566 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
567 $user->getName(),
568 $title->getPrefixedText() );
569 $this->action = 'create';
570 wfDebug( "ConfirmEdit: checking on page creation...\n" );
571 return true;
572 }
573
574 // The following checks are expensive and should be done only,
575 // if we can assume, that the edit will be saved
576 if ( !$request->wasPosted() ) {
577 wfDebug(
578 "ConfirmEdit: request not posted, assuming that no content will be saved -> no CAPTCHA check"
579 );
580 return false;
581 }
582
583 if ( !$isEmpty && $this->triggersCaptcha( 'addurl', $title ) ) {
584 // Only check edits that add URLs
585 if ( $content instanceof Content ) {
586 // Get links from the database
587 $oldLinks = $this->getLinksFromTracker( $title );
588 // Share a parse operation with Article::doEdit()
589 $editInfo = $page->prepareContentForEdit( $content );
590 if ( $editInfo->output ) {
591 $newLinks = array_keys( $editInfo->output->getExternalLinks() );
592 } else {
593 $newLinks = [];
594 }
595 } else {
596 // Get link changes in the slowest way known to man
597 $oldtext = isset( $oldtext ) ? $oldtext : $this->loadText( $title, $section );
598 $oldLinks = $this->findLinks( $title, $oldtext );
599 $newLinks = $this->findLinks( $title, $newtext );
600 }
601
602 $unknownLinks = array_filter( $newLinks, [ $this, 'filterLink' ] );
603 $addedLinks = array_diff( $unknownLinks, $oldLinks );
604 $numLinks = count( $addedLinks );
605
606 if ( $numLinks > 0 ) {
607 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
608 $numLinks,
609 $user->getName(),
610 $title->getPrefixedText(),
611 implode( ", ", $addedLinks ) );
612 $this->action = 'addurl';
613 return true;
614 }
615 }
616
617 global $wgCaptchaRegexes;
618 if ( $newtext !== null && $wgCaptchaRegexes ) {
619 if ( !is_array( $wgCaptchaRegexes ) ) {
620 throw new UnexpectedValueException(
621 '$wgCaptchaRegexes is required to be an array, ' . gettype( $wgCaptchaRegexes ) . ' given.'
622 );
623 }
624 // Custom regex checks. Reuse $oldtext if set above.
625 $oldtext = isset( $oldtext ) ? $oldtext : $this->loadText( $title, $section );
626
627 foreach ( $wgCaptchaRegexes as $regex ) {
628 $newMatches = [];
629 if ( preg_match_all( $regex, $newtext, $newMatches ) ) {
630 $oldMatches = [];
631 preg_match_all( $regex, $oldtext, $oldMatches );
632
633 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
634
635 $numHits = count( $addedMatches );
636 if ( $numHits > 0 ) {
637 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
638 $numHits,
639 $regex,
640 $user->getName(),
641 $title->getPrefixedText(),
642 implode( ", ", $addedMatches ) );
643 $this->action = 'edit';
644 return true;
645 }
646 }
647 }
648 }
649
650 return false;
651 }
652
659 function filterLink( $url ) {
660 global $wgCaptchaWhitelist;
661 static $regexes = null;
662
663 if ( $regexes === null ) {
664 $source = wfMessage( 'captcha-addurl-whitelist' )->inContentLanguage();
665
666 $regexes = $source->isDisabled()
667 ? []
668 : $this->buildRegexes( explode( "\n", $source->plain() ) );
669
670 if ( $wgCaptchaWhitelist !== false ) {
671 array_unshift( $regexes, $wgCaptchaWhitelist );
672 }
673 }
674
675 foreach ( $regexes as $regex ) {
676 if ( preg_match( $regex, $url ) ) {
677 return false;
678 }
679 }
680
681 return true;
682 }
683
690 function buildRegexes( $lines ) {
691 # Code duplicated from the SpamBlacklist extension (r19197)
692 # and later modified.
693
694 # Strip comments and whitespace, then remove blanks
695 $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
696
697 # No lines, don't make a regex which will match everything
698 if ( count( $lines ) == 0 ) {
699 wfDebug( "No lines\n" );
700 return [];
701 } else {
702 # Make regex
703 # It's faster using the S modifier even though it will usually only be run once
704 // $regex = 'http://+[a-z0-9_\-.]*(' . implode( '|', $lines ) . ')';
705 // return '/' . str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $regex) ) . '/Si';
706 $regexes = [];
707 $regexStart = [
708 'normal' => '/^(?:https?:)?\/\/+[a-z0-9_\-.]*(?:',
709 'noprotocol' => '/^(?:',
710 ];
711 $regexEnd = [
712 'normal' => ')/Si',
713 'noprotocol' => ')/Si',
714 ];
715 $regexMax = 4096;
716 $build = [];
717 foreach ( $lines as $line ) {
718 # Extract flags from the line
719 $options = [];
720 if ( preg_match( '/^(.*?)\s*<([^<>]*)>$/', $line, $matches ) ) {
721 if ( $matches[1] === '' ) {
722 wfDebug( "Line with empty regex\n" );
723 continue;
724 }
725 $line = $matches[1];
726 $opts = preg_split( '/\s*\|\s*/', trim( $matches[2] ) );
727 foreach ( $opts as $opt ) {
728 $opt = strtolower( $opt );
729 if ( $opt == 'noprotocol' ) {
730 $options['noprotocol'] = true;
731 }
732 }
733 }
734
735 $key = isset( $options['noprotocol'] ) ? 'noprotocol' : 'normal';
736
737 // FIXME: not very robust size check, but should work. :)
738 if ( !isset( $build[$key] ) ) {
739 $build[$key] = $line;
740 } elseif ( strlen( $build[$key] ) + strlen( $line ) > $regexMax ) {
741 $regexes[] = $regexStart[$key] .
742 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build[$key] ) ) .
743 $regexEnd[$key];
744 $build[$key] = $line;
745 } else {
746 $build[$key] .= '|' . $line;
747 }
748 }
749 foreach ( $build as $key => $value ) {
750 $regexes[] = $regexStart[$key] .
751 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build[$key] ) ) .
752 $regexEnd[$key];
753 }
754 return $regexes;
755 }
756 }
757
763 function getLinksFromTracker( $title ) {
765 $id = $title->getArticleID(); // should be zero queries
766 $res = $dbr->select( 'externallinks', [ 'el_to' ],
767 [ 'el_from' => $id ], __METHOD__ );
768 $links = [];
769 foreach ( $res as $row ) {
770 $links[] = $row->el_to;
771 }
772 return $links;
773 }
774
783 private function doConfirmEdit( WikiPage $page, $newtext, $section, IContextSource $context ) {
784 global $wgUser, $wgRequest;
785 $request = $context->getRequest();
786
787 // FIXME: Stop using wgRequest in other parts of ConfirmEdit so we can
788 // stop having to duplicate code for it.
789 if ( $request->getVal( 'captchaid' ) ) {
790 $request->setVal( 'wpCaptchaId', $request->getVal( 'captchaid' ) );
791 $wgRequest->setVal( 'wpCaptchaId', $request->getVal( 'captchaid' ) );
792 }
793 if ( $request->getVal( 'captchaword' ) ) {
794 $request->setVal( 'wpCaptchaWord', $request->getVal( 'captchaword' ) );
795 $wgRequest->setVal( 'wpCaptchaWord', $request->getVal( 'captchaword' ) );
796 }
797 if ( $this->shouldCheck( $page, $newtext, $section, $context ) ) {
798 return $this->passCaptchaLimitedFromRequest( $wgRequest, $wgUser );
799 } else {
800 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
801 return true;
802 }
803 }
804
815 function confirmEditMerged( $context, $content, $status, $summary, $user, $minorEdit ) {
816 if ( !$context->canUseWikiPage() ) {
817 // we check WikiPage only
818 // try to get an appropriate title for this page
819 $title = $context->getTitle();
820 if ( $title instanceof Title ) {
821 $title = $title->getFullText();
822 } else {
823 // otherwise it's an unknown page where this function is called from
824 $title = 'unknown';
825 }
826 // log this error, it could be a problem in another extension,
827 // edits should always have a WikiPage if
828 // they go through EditFilterMergedContent.
829 wfDebug( __METHOD__ . ': Skipped ConfirmEdit check: No WikiPage for title ' . $title );
830 return true;
831 }
832 $page = $context->getWikiPage();
833 if ( !$this->doConfirmEdit( $page, $content, false, $context ) ) {
835 $status->apiHookResult = [];
836 // give an error message for the user to know, what goes wrong here.
837 // this can't be done for addurl trigger, because this requires one "free" save
838 // for the user, which we don't know, when he did it.
839 if ( $this->action === 'edit' ) {
840 $status->fatal(
841 new RawMessage(
842 Html::element(
843 'div',
844 [ 'class' => 'errorbox' ],
845 $context->msg( 'captcha-edit-fail' )->text()
846 )
847 )
848 );
849 }
850 $this->addCaptchaAPI( $status->apiHookResult );
851 $page->ConfirmEdit_ActivateCaptcha = true;
852 return false;
853 }
854 return true;
855 }
856
864 public function needCreateAccountCaptcha( User $creatingUser = null ) {
865 global $wgUser;
866 $creatingUser = $creatingUser ?: $wgUser;
867
869 if ( $creatingUser->isAllowed( 'skipcaptcha' ) ) {
870 wfDebug( "ConfirmEdit: user group allows skipping captcha on account creation\n" );
871 return false;
872 }
873 if ( $this->isIPWhitelisted() ) {
874 return false;
875 }
876 return true;
877 }
878 return false;
879 }
880
890 function confirmEmailUser( $from, $to, $subject, $text, &$error ) {
891 global $wgUser, $wgRequest;
892
894 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
895 wfDebug( "ConfirmEdit: user group allows skipping captcha on email sending\n" );
896 return true;
897 }
898 if ( $this->isIPWhitelisted() ) {
899 return true;
900 }
901
902 if ( defined( 'MW_API' ) ) {
903 # API mode
904 # Asking for captchas in the API is really silly
905 $error = Status::newFatal( 'captcha-disabledinapi' );
906 return false;
907 }
908 $this->trigger = "{$wgUser->getName()} sending email";
909 if ( !$this->passCaptchaLimitedFromRequest( $wgRequest, $wgUser ) ) {
910 $error = Status::newFatal( 'captcha-sendemail-fail' );
911 return false;
912 }
913 }
914 return true;
915 }
916
921 protected function isAPICaptchaModule( $module ) {
922 return $module instanceof ApiEditPage;
923 }
924
931 public function APIGetAllowedParams( &$module, &$params, $flags ) {
932 if ( $this->isAPICaptchaModule( $module ) ) {
933 $params['captchaword'] = [
934 ApiBase::PARAM_HELP_MSG => 'captcha-apihelp-param-captchaword',
935 ];
936 $params['captchaid'] = [
937 ApiBase::PARAM_HELP_MSG => 'captcha-apihelp-param-captchaid',
938 ];
939 }
940
941 return true;
942 }
943
953 list( $index, $word ) = $this->getCaptchaParamsFromRequest( $request );
954 return $this->passCaptchaLimited( $index, $word, $user );
955 }
956
962 $index = $request->getVal( 'wpCaptchaId' );
963 $word = $request->getVal( 'wpCaptchaWord' );
964 return [ $index, $word ];
965 }
966
977 public function passCaptchaLimited( $index, $word, User $user ) {
978 // don't increase pingLimiter here, just check, if CAPTCHA limit exceeded
979 if ( $user->pingLimiter( 'badcaptcha', 0 ) ) {
980 // for debugging add an proper error message, the user just see an false captcha error message
981 $this->log( 'User reached RateLimit, preventing action' );
982 return false;
983 }
984
985 if ( $this->passCaptcha( $index, $word ) ) {
986 return true;
987 }
988
989 // captcha was not solved: increase limit and return false
990 $user->pingLimiter( 'badcaptcha' );
991 return false;
992 }
993
1002 list( $index, $word ) = $this->getCaptchaParamsFromRequest( $request );
1003 return $this->passCaptcha( $index, $word );
1004 }
1005
1013 protected function passCaptcha( $index, $word ) {
1014 // Don't check the same CAPTCHA twice in one session,
1015 // if the CAPTCHA was already checked - Bug T94276
1016 if ( isset( $this->captchaSolved ) ) {
1017 return $this->captchaSolved;
1018 }
1019
1020 $info = $this->retrieveCaptcha( $index );
1021 if ( $info ) {
1022 if ( $this->keyMatch( $word, $info ) ) {
1023 $this->log( "passed" );
1024 $this->clearCaptcha( $index );
1025 $this->captchaSolved = true;
1026 return true;
1027 } else {
1028 $this->clearCaptcha( $index );
1029 $this->log( "bad form input" );
1030 $this->captchaSolved = false;
1031 return false;
1032 }
1033 } else {
1034 $this->log( "new captcha session" );
1035 return false;
1036 }
1037 }
1038
1043 function log( $message ) {
1044 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
1045 }
1046
1058 public function storeCaptcha( $info ) {
1059 if ( !isset( $info['index'] ) ) {
1060 // Assign random index if we're not udpating
1061 $info['index'] = strval( mt_rand() );
1062 }
1063 CaptchaStore::get()->store( $info['index'], $info );
1064 return $info['index'];
1065 }
1066
1072 public function retrieveCaptcha( $index ) {
1073 return CaptchaStore::get()->retrieve( $index );
1074 }
1075
1081 public function clearCaptcha( $index ) {
1082 CaptchaStore::get()->clear( $index );
1083 }
1084
1093 function loadText( $title, $section, $flags = Revision::READ_LATEST ) {
1094 global $wgParser;
1095
1096 $rev = Revision::newFromTitle( $title, false, $flags );
1097 if ( is_null( $rev ) ) {
1098 return "";
1099 }
1100
1101 $content = $rev->getContent();
1102 $text = ContentHandler::getContentText( $content );
1103 if ( $section !== '' ) {
1104 return $wgParser->getSection( $text, $section );
1105 }
1106
1107 return $text;
1108 }
1109
1116 function findLinks( $title, $text ) {
1117 global $wgParser, $wgUser;
1118
1119 $options = new ParserOptions();
1120 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
1121 $out = $wgParser->parse( $text, $title, $options );
1122
1123 return array_keys( $out->getExternalLinks() );
1124 }
1125
1129 function showHelp() {
1130 global $wgOut;
1131 $wgOut->setPageTitle( wfMessage( 'captchahelp-title' )->text() );
1132 $wgOut->addWikiMsg( 'captchahelp-text' );
1133 if ( CaptchaStore::get()->cookiesNeeded() ) {
1134 $wgOut->addWikiMsg( 'captchahelp-cookies-needed' );
1135 }
1136 }
1137
1142 $captchaData = $this->getCaptcha();
1143 $id = $this->storeCaptcha( $captchaData );
1144 return new CaptchaAuthenticationRequest( $id, $captchaData );
1145 }
1146
1154 public function onAuthChangeFormFields(
1155 array $requests, array $fieldInfo, array &$formDescriptor, $action
1156 ) {
1157 $req = AuthenticationRequest::getRequestByClass( $requests,
1158 CaptchaAuthenticationRequest::class );
1159 if ( !$req ) {
1160 return;
1161 }
1162
1163 $formDescriptor['captchaWord'] = [
1164 'label-message' => null,
1165 'autocomplete' => false,
1166 'persistent' => false,
1167 'required' => true,
1168 ] + $formDescriptor['captchaWord'];
1169 }
1170}
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfGlobalCacheKey()
Make a cache key with database-agnostic prefix.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
$wgUser
Definition Setup.php:902
$wgOut
Definition Setup.php:912
$wgParser
Definition Setup.php:917
if(! $wgDBerrorLogTZ) $wgRequest
Definition Setup.php:737
$line
Definition cdb.php:59
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:124
A module that allows for editing and creating pages.
Generic captcha authentication request class.
static get()
Get somewhere to store captcha data that will persist between requests.
const AS_HOOK_ERROR_EXPECTED
Status: A hook function returned an error.
Definition EditPage.php:68
This is a value object for authentication requests.
The Message class provides methods which fulfil two basic services:
Definition Message.php:159
This class should be covered by a general architecture document which does not exist as of January 20...
Set options of the Parser.
Variant of the Message class.
static getMain()
Get the RequestContext object associated with the main request.
Demo CAPTCHA (not for production usage) and base class for real CAPTCHAs.
Definition Captcha.php:8
getMessage( $action)
Show a message asking the user to enter a captcha on edit The result will be treated as wiki text.
Definition Captcha.php:229
buildRegexes( $lines)
Build regex from whitelist.
Definition Captcha.php:690
findLinks( $title, $text)
Extract a list of all recognized HTTP links in the text.
Definition Captcha.php:1116
isIPWhitelisted()
Check if the current IP is allowed to skip captchas.
Definition Captcha.php:350
isBadLoginTriggered()
Check if a bad login has already been registered for this IP address.
Definition Captcha.php:316
addFormToOutput(OutputPage $out, $tabIndex=1)
Uses getFormInformation() to get the CAPTCHA form and adds it to the given OutputPage object.
Definition Captcha.php:149
retrieveCaptcha( $index)
Fetch this session's captcha info.
Definition Captcha.php:1072
static $messagePrefix
Definition Captcha.php:9
log( $message)
Log the status and any triggering info for debugging or statistics.
Definition Captcha.php:1043
isAPICaptchaModule( $module)
Definition Captcha.php:921
loadText( $title, $section, $flags=Revision::READ_LATEST)
Retrieve the current version of the page or section being edited...
Definition Captcha.php:1093
triggersCaptcha( $action, $title=null)
Checks, whether the passed action should trigger a CAPTCHA.
Definition Captcha.php:483
keyMatch( $answer, $info)
Check if the submitted form matches the captcha session data provided by the plugin when the form was...
Definition Captcha.php:457
passCaptchaFromRequest(WebRequest $request, User $user)
Given a required captcha run, test form input for correct input on the open session.
Definition Captcha.php:1001
APIGetAllowedParams(&$module, &$params, $flags)
Definition Captcha.php:931
getCaptchaInfo( $captchaData, $id)
Definition Captcha.php:183
showEditFormFields(&$editPage, &$out)
Show error message for missing or incorrect captcha on EditPage.
Definition Captcha.php:192
getError()
Return the error from the last passCaptcha* call.
Definition Captcha.php:43
editShowCaptcha( $editPage)
Insert the captcha prompt into an edit form.
Definition Captcha.php:209
needCreateAccountCaptcha(User $creatingUser=null)
Logic to check if we need to pass a captcha for the current user to create a new account,...
Definition Captcha.php:864
showHelp()
Show a page explaining what this wacky thing is.
Definition Captcha.php:1129
badLoginPerUserKey( $username)
Cache key for badloginPerUser checks.
Definition Captcha.php:442
badLoginKey()
Internal cache key for badlogin checks.
Definition Captcha.php:431
filterLink( $url)
Filter callback function for URL whitelisting.
Definition Captcha.php:659
injectEmailUser(&$form)
Inject whazawhoo @fixme if multiple thingies insert a header, could break.
Definition Captcha.php:245
getLinksFromTracker( $title)
Load external links from the externallinks table.
Definition Captcha.php:763
string $trigger
Used in log messages.
Definition Captcha.php:22
getFormInformation( $tabIndex=1)
Insert a captcha prompt into the edit form.
Definition Captcha.php:120
string $action
Used to select the right message.
Definition Captcha.php:19
confirmEditMerged( $context, $content, $status, $summary, $user, $minorEdit)
An efficient edit filter callback based on the text after section merging.
Definition Captcha.php:815
buildValidIPs(array $input)
From a list of unvalidated input, get all the valid IP addresses and IP ranges from it.
Definition Captcha.php:412
isBadLoginPerUserTriggered( $u)
Is the per-user captcha triggered?
Definition Captcha.php:330
confirmEmailUser( $from, $to, $subject, $text, &$error)
Check the captcha on Special:EmailUser.
Definition Captcha.php:890
passCaptchaLimited( $index, $word, User $user)
Checks, if the user reached the amount of false CAPTCHAs and give him some vacation or run self::pass...
Definition Captcha.php:977
passCaptchaLimitedFromRequest(WebRequest $request, User $user)
Checks, if the user reached the amount of false CAPTCHAs and give him some vacation or run self::pass...
Definition Captcha.php:952
addFormInformationToOutput(OutputPage $out, array $formInformation)
Processes the given $formInformation array and adds the options (see getFormInformation()) to the giv...
Definition Captcha.php:160
setAction( $action)
Definition Captcha.php:27
getWikiIPWhitelist(Message $msg)
Get the on-wiki IP whitelist stored in [[MediaWiki:Captcha-ip-whitelist]] page from cache if possible...
Definition Captcha.php:378
storeCaptcha( $info)
Generate a captcha session ID and save the info in PHP's session storage.
Definition Captcha.php:1058
increaseBadLoginCounter( $username)
Increase bad login counter after a failed login.
Definition Captcha.php:273
captchaTriggers( $title, $action)
Definition Captcha.php:469
clearCaptcha( $index)
Clear out existing captcha info from the session, to ensure it can't be reused.
Definition Captcha.php:1081
passCaptcha( $index, $word)
Given a required captcha run, test form input for correct input on the open session.
Definition Captcha.php:1013
getCaptchaParamsFromRequest(WebRequest $request)
Definition Captcha.php:961
shouldCheck(WikiPage $page, $content, $section, $context, $oldtext=null)
Definition Captcha.php:517
addCaptchaAPI(&$resultArr)
Definition Captcha.php:71
doConfirmEdit(WikiPage $page, $newtext, $section, IContextSource $context)
Backend function for confirmEditMerged()
Definition Captcha.php:783
createAuthenticationRequest()
Definition Captcha.php:1141
setTrigger( $trigger)
Definition Captcha.php:34
getCaptcha()
Returns an array with 'question' and 'answer' keys.
Definition Captcha.php:53
describeCaptchaType()
Describes the captcha type for API clients.
Definition Captcha.php:84
boolean null $captchaSolved
Was the CAPTCHA already passed and if yes, with which result?
Definition Captcha.php:12
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
Modify the apprearance of the captcha field.
Definition Captcha.php:1154
resetBadLoginCounter( $username)
Reset bad login counter after a successful login.
Definition Captcha.php:303
Represents a title within MediaWiki.
Definition Title.php:39
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:53
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
Definition User.php:1210
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Class representing a MediaWiki article and history.
Definition WikiPage.php:37
prepareContentForEdit(Content $content, $revision=null, User $user=null, $serialFormat=null, $useCache=true)
Prepare content which is about to be saved.
getTitle()
Get the title object of the article.
Definition WikiPage.php:236
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition design.txt:18
this hook is for auditing only $req
Definition hooks.txt:990
namespace being checked & $result
Definition hooks.txt:2323
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2806
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action or null $user:User who performed the tagging when the tagging is subsequent to the action or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy: boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
Definition hooks.txt:1051
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition hooks.txt:2001
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition hooks.txt:2811
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition hooks.txt:864
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead. & $feedLinks hooks can tweak the array to change how login etc forms should look $requests
Definition hooks.txt:304
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:785
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition hooks.txt:3022
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition hooks.txt:1777
const CONTENT_MODEL_WIKITEXT
Definition Defines.php:245
Base interface for content objects.
Definition Content.php:34
Interface for objects which can provide a MediaWiki context on request.
$cache
Definition mcc.php:33
$source
if(is_array($mode)) switch( $mode) $input
const DB_REPLICA
Definition defines.php:25
$lines
Definition router.php:61
$params