MediaWiki REL1_33
SimpleCaptcha.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 public 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 protected 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' =>
126 new OOUI\FieldLayout(
127 new OOUI\NumberInputWidget( [
128 'name' => 'wpCaptchaWord',
129 'classes' => [ 'simplecaptcha-answer' ],
130 'id' => 'wpCaptchaWord',
131 'autocomplete' => 'off',
132 // tab in before the edit textarea
133 'tabIndex' => $tabIndex
134 ] ),
135 [
136 'align' => 'left',
137 'label' => $captcha['question'] . ' = ',
138 'classes' => [ 'simplecaptcha-field' ],
139 ]
140 ) .
142 'name' => 'wpCaptchaId',
143 'id' => 'wpCaptchaId',
144 'value' => $index
145 ] ),
146 'modulestyles' => [
147 'ext.confirmEdit.simpleCaptcha'
148 ]
149 ];
150 }
151
159 public function addFormToOutput( OutputPage $out, $tabIndex = 1 ) {
160 $this->addFormInformationToOutput( $out, $this->getFormInformation( $tabIndex ) );
161 }
162
170 public function addFormInformationToOutput( OutputPage $out, array $formInformation ) {
171 if ( !$formInformation ) {
172 return;
173 }
174 if ( isset( $formInformation['html'] ) ) {
175 $out->addHTML( $formInformation['html'] );
176 }
177 if ( isset( $formInformation['modules'] ) ) {
178 $out->addModules( $formInformation['modules'] );
179 }
180 if ( isset( $formInformation['modulestyles'] ) ) {
181 $out->addModuleStyles( $formInformation['modulestyles'] );
182 }
183 if ( isset( $formInformation['headitems'] ) ) {
184 $out->addHeadItems( $formInformation['headitems'] );
185 }
186 }
187
193 public function getCaptchaInfo( $captchaData, $id ) {
194 return $captchaData['question'] . ' =';
195 }
196
202 public function showEditFormFields( &$editPage, &$out ) {
203 $out->enableOOUI();
204 $page = $editPage->getArticle()->getPage();
205 if ( !isset( $page->ConfirmEdit_ActivateCaptcha ) ) {
206 return;
207 }
208
209 if ( $this->action !== 'edit' ) {
210 unset( $page->ConfirmEdit_ActivateCaptcha );
211 $out->addHTML( $this->getMessage( $this->action )->parseAsBlock() );
212 $this->addFormToOutput( $out );
213 }
214 }
215
220 public function editShowCaptcha( $editPage ) {
221 $context = $editPage->getArticle()->getContext();
222 $page = $editPage->getArticle()->getPage();
223 $out = $context->getOutput();
224 if ( isset( $page->ConfirmEdit_ActivateCaptcha ) ||
225 $this->shouldCheck( $page, '', '', $context )
226 ) {
227 $out->addHTML( $this->getMessage( $this->action )->parseAsBlock() );
228 $this->addFormToOutput( $out );
229 }
230 unset( $page->ConfirmEdit_ActivateCaptcha );
231 }
232
240 public function getMessage( $action ) {
241 // one of captcha-edit, captcha-addurl, captcha-badlogin, captcha-createaccount,
242 // captcha-create, captcha-sendemail
243 $name = static::$messagePrefix . $action;
244 $msg = wfMessage( $name );
245 // obtain a more tailored message, if possible, otherwise, fall back to
246 // the default for edits
247 return $msg->isDisabled() ? wfMessage( static::$messagePrefix . 'edit' ) : $msg;
248 }
249
256 public function injectEmailUser( &$form ) {
257 $out = $form->getOutput();
258 $user = $form->getUser();
260 $this->action = 'sendemail';
261 if ( $this->canSkipCaptcha( $user, $form->getConfig() ) ) {
262 return true;
263 }
264 $formInformation = $this->getFormInformation();
265 $formMetainfo = $formInformation;
266 unset( $formMetainfo['html'] );
267 $this->addFormInformationToOutput( $out, $formMetainfo );
268 $form->addFooterText(
269 "<div class='captcha'>" .
270 $this->getMessage( 'sendemail' )->parseAsBlock() .
271 $formInformation['html'] .
272 "</div>\n" );
273 }
274 return true;
275 }
276
285
286 $cache = ObjectCache::getLocalClusterInstance();
287
289 $key = $this->badLoginKey();
290 $count = ObjectCache::getLocalClusterInstance()->get( $key );
291 if ( !$count ) {
292 $cache->add( $key, 0, $wgCaptchaBadLoginExpiration );
293 }
294
295 $cache->incr( $key );
296 }
297
299 $key = $this->badLoginPerUserKey( $username );
300 $count = $cache->get( $key );
301 if ( !$count ) {
302 $cache->add( $key, 0, $wgCaptchaBadLoginPerUserExpiration );
303 }
304
305 $cache->incr( $key );
306 }
307 }
308
313 public function resetBadLoginCounter( $username ) {
315 $cache = ObjectCache::getLocalClusterInstance();
316 $cache->delete( $this->badLoginPerUserKey( $username ) );
317 }
318 }
319
326 public function isBadLoginTriggered() {
328
329 $cache = ObjectCache::getLocalClusterInstance();
331 && (int)$cache->get( $this->badLoginKey() ) >= $wgCaptchaBadLoginAttempts;
332 }
333
340 public function isBadLoginPerUserTriggered( $u ) {
342
343 $cache = ObjectCache::getLocalClusterInstance();
344
345 if ( is_object( $u ) ) {
346 $u = $u->getName();
347 }
349 && (int)$cache->get( $this->badLoginPerUserKey( $u ) ) >= $wgCaptchaBadLoginPerUserAttempts;
350 }
351
360 private function isIPWhitelisted() {
362 $ip = $wgRequest->getIP();
363
364 if ( $wgCaptchaWhitelistIP ) {
365 if ( IP::isInRanges( $ip, $wgCaptchaWhitelistIP ) ) {
366 return true;
367 }
368 }
369
370 $whitelistMsg = wfMessage( 'captcha-ip-whitelist' )->inContentLanguage();
371 if ( !$whitelistMsg->isDisabled() ) {
372 $whitelistedIPs = $this->getWikiIPWhitelist( $whitelistMsg );
373 if ( IP::isInRanges( $ip, $whitelistedIPs ) ) {
374 return true;
375 }
376 }
377
378 return false;
379 }
380
388 private function getWikiIPWhitelist( Message $msg ) {
389 $cache = ObjectCache::getMainWANInstance();
390 $cacheKey = $cache->makeKey( 'confirmedit', 'ipwhitelist' );
391
392 $cachedWhitelist = $cache->get( $cacheKey );
393 if ( $cachedWhitelist === false ) {
394 // Could not retrieve from cache so build the whitelist directly
395 // from the wikipage
396 $whitelist = $this->buildValidIPs(
397 explode( "\n", $msg->plain() )
398 );
399 // And then store it in cache for one day. This cache is cleared on
400 // modifications to the whitelist page.
401 // @see ConfirmEditHooks::onPageContentSaveComplete()
402 $cache->set( $cacheKey, $whitelist, 86400 );
403 } else {
404 // Whitelist from the cache
405 $whitelist = $cachedWhitelist;
406 }
407
408 return $whitelist;
409 }
410
422 private function buildValidIPs( array $input ) {
423 // Remove whitespace and blank lines first
424 $ips = array_map( 'trim', $input );
425 $ips = array_filter( $ips );
426
427 $validIPs = [];
428 foreach ( $ips as $ip ) {
429 if ( IP::isIPAddress( $ip ) ) {
430 $validIPs[] = $ip;
431 }
432 }
433
434 return $validIPs;
435 }
436
441 private function badLoginKey() {
442 global $wgRequest;
443 $ip = $wgRequest->getIP();
444 return wfGlobalCacheKey( 'captcha', 'badlogin', 'ip', $ip );
445 }
446
452 private function badLoginPerUserKey( $username ) {
454 return wfGlobalCacheKey( 'captcha', 'badlogin', 'user', md5( $username ) );
455 }
456
467 protected function keyMatch( $answer, $info ) {
468 return $answer == $info['answer'];
469 }
470
471 // ----------------------------------
472
479 public function captchaTriggers( $title, $action ) {
480 return $this->triggersCaptcha( $action, $title );
481 }
482
493 public function triggersCaptcha( $action, $title = null ) {
495
496 $result = false;
497 $triggers = $wgCaptchaTriggers;
498 $attributeCaptchaTriggers = ExtensionRegistry::getInstance()
500 if ( is_array( $attributeCaptchaTriggers ) ) {
501 $triggers += $attributeCaptchaTriggers;
502 }
503
504 if ( isset( $triggers[$action] ) ) {
505 $result = $triggers[$action];
506 }
507
508 if (
509 $title !== null &&
510 isset( $wgCaptchaTriggersOnNamespace[$title->getNamespace()][$action] )
511 ) {
512 $result = $wgCaptchaTriggersOnNamespace[$title->getNamespace()][$action];
513 }
514
515 return $result;
516 }
517
527 public function shouldCheck( WikiPage $page, $content, $section, $context, $oldtext = null ) {
528 if ( !$context instanceof IContextSource ) {
529 $context = RequestContext::getMain();
530 }
531
532 $request = $context->getRequest();
533 $user = $context->getUser();
534
535 if ( $this->canSkipCaptcha( $user, $context->getConfig() ) ) {
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 if ( $oldtext === null ) {
598 $oldtext = $this->loadText( $title, $section );
599 }
600 $oldLinks = $this->findLinks( $title, $oldtext );
601 $newLinks = $this->findLinks( $title, $newtext );
602 }
603
604 $unknownLinks = array_filter( $newLinks, [ $this, 'filterLink' ] );
605 $addedLinks = array_diff( $unknownLinks, $oldLinks );
606 $numLinks = count( $addedLinks );
607
608 if ( $numLinks > 0 ) {
609 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
610 $numLinks,
611 $user->getName(),
612 $title->getPrefixedText(),
613 implode( ", ", $addedLinks ) );
614 $this->action = 'addurl';
615 return true;
616 }
617 }
618
619 global $wgCaptchaRegexes;
620 if ( $newtext !== null && $wgCaptchaRegexes ) {
621 if ( !is_array( $wgCaptchaRegexes ) ) {
622 throw new UnexpectedValueException(
623 '$wgCaptchaRegexes is required to be an array, ' . gettype( $wgCaptchaRegexes ) . ' given.'
624 );
625 }
626 // Custom regex checks. Reuse $oldtext if set above.
627 if ( $oldtext === null ) {
628 $oldtext = $this->loadText( $title, $section );
629 }
630
631 foreach ( $wgCaptchaRegexes as $regex ) {
632 $newMatches = [];
633 if ( preg_match_all( $regex, $newtext, $newMatches ) ) {
634 $oldMatches = [];
635 preg_match_all( $regex, $oldtext, $oldMatches );
636
637 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
638
639 $numHits = count( $addedMatches );
640 if ( $numHits > 0 ) {
641 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
642 $numHits,
643 $regex,
644 $user->getName(),
645 $title->getPrefixedText(),
646 implode( ", ", $addedMatches ) );
647 $this->action = 'edit';
648 return true;
649 }
650 }
651 }
652 }
653
654 return false;
655 }
656
662 private function filterLink( $url ) {
663 global $wgCaptchaWhitelist;
664 static $regexes = null;
665
666 if ( $regexes === null ) {
667 $source = wfMessage( 'captcha-addurl-whitelist' )->inContentLanguage();
668
669 $regexes = $source->isDisabled()
670 ? []
671 : $this->buildRegexes( explode( "\n", $source->plain() ) );
672
673 if ( $wgCaptchaWhitelist !== false ) {
674 array_unshift( $regexes, $wgCaptchaWhitelist );
675 }
676 }
677
678 foreach ( $regexes as $regex ) {
679 if ( preg_match( $regex, $url ) ) {
680 return false;
681 }
682 }
683
684 return true;
685 }
686
693 private function buildRegexes( $lines ) {
694 # Code duplicated from the SpamBlacklist extension (r19197)
695 # and later modified.
696
697 # Strip comments and whitespace, then remove blanks
698 $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
699
700 # No lines, don't make a regex which will match everything
701 if ( count( $lines ) == 0 ) {
702 wfDebug( "No lines\n" );
703 return [];
704 } else {
705 # Make regex
706 # It's faster using the S modifier even though it will usually only be run once
707 // $regex = 'http://+[a-z0-9_\-.]*(' . implode( '|', $lines ) . ')';
708 // return '/' . str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $regex) ) . '/Si';
709 $regexes = [];
710 $regexStart = [
711 'normal' => '/^(?:https?:)?\/\/+[a-z0-9_\-.]*(?:',
712 'noprotocol' => '/^(?:',
713 ];
714 $regexEnd = [
715 'normal' => ')/Si',
716 'noprotocol' => ')/Si',
717 ];
718 $regexMax = 4096;
719 $build = [];
720 foreach ( $lines as $line ) {
721 # Extract flags from the line
722 $options = [];
723 if ( preg_match( '/^(.*?)\s*<([^<>]*)>$/', $line, $matches ) ) {
724 if ( $matches[1] === '' ) {
725 wfDebug( "Line with empty regex\n" );
726 continue;
727 }
728 $line = $matches[1];
729 $opts = preg_split( '/\s*\|\s*/', trim( $matches[2] ) );
730 foreach ( $opts as $opt ) {
731 $opt = strtolower( $opt );
732 if ( $opt == 'noprotocol' ) {
733 $options['noprotocol'] = true;
734 }
735 }
736 }
737
738 $key = isset( $options['noprotocol'] ) ? 'noprotocol' : 'normal';
739
740 // FIXME: not very robust size check, but should work. :)
741 if ( !isset( $build[$key] ) ) {
742 $build[$key] = $line;
743 } elseif ( strlen( $build[$key] ) + strlen( $line ) > $regexMax ) {
744 $regexes[] = $regexStart[$key] .
745 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build[$key] ) ) .
746 $regexEnd[$key];
747 $build[$key] = $line;
748 } else {
749 $build[$key] .= '|' . $line;
750 }
751 }
752 foreach ( $build as $key => $value ) {
753 $regexes[] = $regexStart[$key] .
754 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build[$key] ) ) .
755 $regexEnd[$key];
756 }
757 return $regexes;
758 }
759 }
760
766 private function getLinksFromTracker( $title ) {
768 // should be zero queries
769 $id = $title->getArticleID();
770 $res = $dbr->select( 'externallinks', [ 'el_to' ],
771 [ 'el_from' => $id ], __METHOD__ );
772 $links = [];
773 foreach ( $res as $row ) {
774 $links[] = $row->el_to;
775 }
776 return $links;
777 }
778
787 private function doConfirmEdit( WikiPage $page, $newtext, $section, IContextSource $context ) {
788 global $wgUser, $wgRequest;
789 $request = $context->getRequest();
790
791 // FIXME: Stop using wgRequest in other parts of ConfirmEdit so we can
792 // stop having to duplicate code for it.
793 if ( $request->getVal( 'captchaid' ) ) {
794 $request->setVal( 'wpCaptchaId', $request->getVal( 'captchaid' ) );
795 $wgRequest->setVal( 'wpCaptchaId', $request->getVal( 'captchaid' ) );
796 }
797 if ( $request->getVal( 'captchaword' ) ) {
798 $request->setVal( 'wpCaptchaWord', $request->getVal( 'captchaword' ) );
799 $wgRequest->setVal( 'wpCaptchaWord', $request->getVal( 'captchaword' ) );
800 }
801 if ( $this->shouldCheck( $page, $newtext, $section, $context ) ) {
802 return $this->passCaptchaLimitedFromRequest( $wgRequest, $wgUser );
803 } else {
804 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
805 return true;
806 }
807 }
808
819 public function confirmEditMerged( $context, $content, $status, $summary, $user, $minorEdit ) {
820 if ( !$context->canUseWikiPage() ) {
821 // we check WikiPage only
822 // try to get an appropriate title for this page
823 $title = $context->getTitle();
824 if ( $title instanceof Title ) {
825 $title = $title->getFullText();
826 } else {
827 // otherwise it's an unknown page where this function is called from
828 $title = 'unknown';
829 }
830 // log this error, it could be a problem in another extension,
831 // edits should always have a WikiPage if
832 // they go through EditFilterMergedContent.
833 wfDebug( __METHOD__ . ': Skipped ConfirmEdit check: No WikiPage for title ' . $title );
834 return true;
835 }
836 $page = $context->getWikiPage();
837 if ( !$this->doConfirmEdit( $page, $content, false, $context ) ) {
839 $status->apiHookResult = [];
840 // give an error message for the user to know, what goes wrong here.
841 // this can't be done for addurl trigger, because this requires one "free" save
842 // for the user, which we don't know, when he did it.
843 if ( $this->action === 'edit' ) {
844 $status->fatal(
845 new RawMessage(
846 Html::element(
847 'div',
848 [ 'class' => 'errorbox' ],
849 $context->msg( 'captcha-edit-fail' )->text()
850 )
851 )
852 );
853 }
854 $this->addCaptchaAPI( $status->apiHookResult );
855 $page->ConfirmEdit_ActivateCaptcha = true;
856 return false;
857 }
858 return true;
859 }
860
868 public function needCreateAccountCaptcha( User $creatingUser = null ) {
869 global $wgUser;
870 $creatingUser = $creatingUser ?: $wgUser;
871
873 if ( $this->canSkipCaptcha( $creatingUser,
874 \MediaWiki\MediaWikiServices::getInstance()->getMainConfig() ) ) {
875 return false;
876 }
877 return true;
878 }
879 return false;
880 }
881
891 public function confirmEmailUser( $from, $to, $subject, $text, &$error ) {
892 global $wgUser, $wgRequest;
893
895 if ( $this->canSkipCaptcha( $wgUser,
896 \MediaWiki\MediaWikiServices::getInstance()->getMainConfig() ) ) {
897 return true;
898 }
899
900 if ( defined( 'MW_API' ) ) {
901 # API mode
902 # Asking for captchas in the API is really silly
903 $error = Status::newFatal( 'captcha-disabledinapi' );
904 return false;
905 }
906 $this->trigger = "{$wgUser->getName()} sending email";
907 if ( !$this->passCaptchaLimitedFromRequest( $wgRequest, $wgUser ) ) {
908 $error = Status::newFatal( 'captcha-sendemail-fail' );
909 return false;
910 }
911 }
912 return true;
913 }
914
919 protected function isAPICaptchaModule( $module ) {
920 return $module instanceof ApiEditPage;
921 }
922
929 public function apiGetAllowedParams( &$module, &$params, $flags ) {
930 if ( $this->isAPICaptchaModule( $module ) ) {
931 $params['captchaword'] = [
932 ApiBase::PARAM_HELP_MSG => 'captcha-apihelp-param-captchaword',
933 ];
934 $params['captchaid'] = [
935 ApiBase::PARAM_HELP_MSG => 'captcha-apihelp-param-captchaid',
936 ];
937 }
938
939 return true;
940 }
941
951 list( $index, $word ) = $this->getCaptchaParamsFromRequest( $request );
952 return $this->passCaptchaLimited( $index, $word, $user );
953 }
954
960 $index = $request->getVal( 'wpCaptchaId' );
961 $word = $request->getVal( 'wpCaptchaWord' );
962 return [ $index, $word ];
963 }
964
975 public function passCaptchaLimited( $index, $word, User $user ) {
976 // don't increase pingLimiter here, just check, if CAPTCHA limit exceeded
977 if ( $user->pingLimiter( 'badcaptcha', 0 ) ) {
978 // for debugging add an proper error message, the user just see an false captcha error message
979 $this->log( 'User reached RateLimit, preventing action' );
980 return false;
981 }
982
983 if ( $this->passCaptcha( $index, $word ) ) {
984 return true;
985 }
986
987 // captcha was not solved: increase limit and return false
988 $user->pingLimiter( 'badcaptcha' );
989 return false;
990 }
991
999 public function passCaptchaFromRequest( WebRequest $request, User $user ) {
1000 list( $index, $word ) = $this->getCaptchaParamsFromRequest( $request );
1001 return $this->passCaptcha( $index, $word );
1002 }
1003
1011 protected function passCaptcha( $index, $word ) {
1012 // Don't check the same CAPTCHA twice in one session,
1013 // if the CAPTCHA was already checked - Bug T94276
1014 if ( isset( $this->captchaSolved ) ) {
1015 return $this->captchaSolved;
1016 }
1017
1018 $info = $this->retrieveCaptcha( $index );
1019 if ( $info ) {
1020 if ( $this->keyMatch( $word, $info ) ) {
1021 $this->log( "passed" );
1022 $this->clearCaptcha( $index );
1023 $this->captchaSolved = true;
1024 return true;
1025 } else {
1026 $this->clearCaptcha( $index );
1027 $this->log( "bad form input" );
1028 $this->captchaSolved = false;
1029 return false;
1030 }
1031 } else {
1032 $this->log( "new captcha session" );
1033 return false;
1034 }
1035 }
1036
1041 protected function log( $message ) {
1042 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
1043 }
1044
1056 public function storeCaptcha( $info ) {
1057 if ( !isset( $info['index'] ) ) {
1058 // Assign random index if we're not udpating
1059 $info['index'] = strval( mt_rand() );
1060 }
1061 CaptchaStore::get()->store( $info['index'], $info );
1062 return $info['index'];
1063 }
1064
1070 public function retrieveCaptcha( $index ) {
1071 return CaptchaStore::get()->retrieve( $index );
1072 }
1073
1079 public function clearCaptcha( $index ) {
1080 CaptchaStore::get()->clear( $index );
1081 }
1082
1091 private function loadText( $title, $section, $flags = Revision::READ_LATEST ) {
1092 global $wgParser;
1093
1094 $rev = Revision::newFromTitle( $title, false, $flags );
1095 if ( is_null( $rev ) ) {
1096 return "";
1097 }
1098
1099 $content = $rev->getContent();
1100 $text = ContentHandler::getContentText( $content );
1101 if ( $section !== '' ) {
1102 return $wgParser->getSection( $text, $section );
1103 }
1104
1105 return $text;
1106 }
1107
1114 private function findLinks( $title, $text ) {
1115 global $wgParser, $wgUser;
1116
1117 $options = new ParserOptions();
1118 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
1119 $out = $wgParser->parse( $text, $title, $options );
1120
1121 return array_keys( $out->getExternalLinks() );
1122 }
1123
1127 public function showHelp() {
1128 global $wgOut;
1129 $wgOut->setPageTitle( wfMessage( 'captchahelp-title' )->text() );
1130 $wgOut->addWikiMsg( 'captchahelp-text' );
1131 if ( CaptchaStore::get()->cookiesNeeded() ) {
1132 $wgOut->addWikiMsg( 'captchahelp-cookies-needed' );
1133 }
1134 }
1135
1140 $captchaData = $this->getCaptcha();
1141 $id = $this->storeCaptcha( $captchaData );
1142 return new CaptchaAuthenticationRequest( $id, $captchaData );
1143 }
1144
1152 public function onAuthChangeFormFields(
1154 ) {
1155 $req = AuthenticationRequest::getRequestByClass( $requests,
1156 CaptchaAuthenticationRequest::class );
1157 if ( !$req ) {
1158 return;
1159 }
1160
1161 $formDescriptor['captchaWord'] = [
1162 'label-message' => null,
1163 'autocomplete' => false,
1164 'persistent' => false,
1165 'required' => true,
1166 ] + $formDescriptor['captchaWord'];
1167 }
1168
1176 public function canSkipCaptcha( $user, Config $config ) {
1177 $allowConfirmEmail = $config->get( 'AllowConfirmedEmail' );
1178
1179 if ( $user->isAllowed( 'skipcaptcha' ) ) {
1180 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
1181 return true;
1182 }
1183
1184 if ( $this->isIPWhitelisted() ) {
1185 wfDebug( "ConfirmEdit: user IP is whitelisted" );
1186 return true;
1187 }
1188
1189 if ( $allowConfirmEmail && $user->isEmailConfirmed() ) {
1190 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
1191 return true;
1192 }
1193
1194 return false;
1195 }
1196}
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
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.
wfGlobalCacheKey(... $args)
Make a cache key with database-agnostic prefix.
$wgOut
Definition Setup.php:880
$wgParser
Definition Setup.php:886
if(! $wgDBerrorLogTZ) $wgRequest
Definition Setup.php:728
$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:160
plain()
Returns the message text as-is, only parameters are substituted.
Definition Message.php:965
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 newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
Definition Revision.php:137
Demo CAPTCHA (not for production usage) and base class for real CAPTCHAs.
getMessage( $action)
Show a message asking the user to enter a captcha on edit The result will be treated as wiki text.
buildRegexes( $lines)
Build regex from whitelist.
findLinks( $title, $text)
Extract a list of all recognized HTTP links in the text.
isIPWhitelisted()
Check if the current IP is allowed to skip captchas.
isBadLoginTriggered()
Check if a bad login has already been registered for this IP address.
addFormToOutput(OutputPage $out, $tabIndex=1)
Uses getFormInformation() to get the CAPTCHA form and adds it to the given OutputPage object.
retrieveCaptcha( $index)
Fetch this session's captcha info.
static $messagePrefix
log( $message)
Log the status and any triggering info for debugging or statistics.
isAPICaptchaModule( $module)
loadText( $title, $section, $flags=Revision::READ_LATEST)
Retrieve the current version of the page or section being edited...
triggersCaptcha( $action, $title=null)
Checks, whether the passed action should trigger a CAPTCHA.
keyMatch( $answer, $info)
Check if the submitted form matches the captcha session data provided by the plugin when the form was...
passCaptchaFromRequest(WebRequest $request, User $user)
Given a required captcha run, test form input for correct input on the open session.
getCaptchaInfo( $captchaData, $id)
showEditFormFields(&$editPage, &$out)
Show error message for missing or incorrect captcha on EditPage.
getError()
Return the error from the last passCaptcha* call.
editShowCaptcha( $editPage)
Insert the captcha prompt into an edit form.
needCreateAccountCaptcha(User $creatingUser=null)
Logic to check if we need to pass a captcha for the current user to create a new account,...
showHelp()
Show a page explaining what this wacky thing is.
badLoginPerUserKey( $username)
Cache key for badloginPerUser checks.
badLoginKey()
Internal cache key for badlogin checks.
filterLink( $url)
Filter callback function for URL whitelisting.
injectEmailUser(&$form)
Inject whazawhoo @fixme if multiple thingies insert a header, could break.
getLinksFromTracker( $title)
Load external links from the externallinks table.
string $trigger
Used in log messages.
getFormInformation( $tabIndex=1)
Insert a captcha prompt into the edit form.
string $action
Used to select the right message.
confirmEditMerged( $context, $content, $status, $summary, $user, $minorEdit)
An efficient edit filter callback based on the text after section merging.
buildValidIPs(array $input)
From a list of unvalidated input, get all the valid IP addresses and IP ranges from it.
apiGetAllowedParams(&$module, &$params, $flags)
isBadLoginPerUserTriggered( $u)
Is the per-user captcha triggered?
confirmEmailUser( $from, $to, $subject, $text, &$error)
Check the captcha on Special:EmailUser.
passCaptchaLimited( $index, $word, User $user)
Checks, if the user reached the amount of false CAPTCHAs and give him some vacation or run self::pass...
passCaptchaLimitedFromRequest(WebRequest $request, User $user)
Checks, if the user reached the amount of false CAPTCHAs and give him some vacation or run self::pass...
addFormInformationToOutput(OutputPage $out, array $formInformation)
Processes the given $formInformation array and adds the options (see getFormInformation()) to the giv...
setAction( $action)
getWikiIPWhitelist(Message $msg)
Get the on-wiki IP whitelist stored in [[MediaWiki:Captcha-ip-whitelist]] page from cache if possible...
storeCaptcha( $info)
Generate a captcha session ID and save the info in PHP's session storage.
canSkipCaptcha( $user, Config $config)
Check whether the user provided / IP making the request is allowed to skip captchas.
increaseBadLoginCounter( $username)
Increase bad login counter after a failed login.
captchaTriggers( $title, $action)
clearCaptcha( $index)
Clear out existing captcha info from the session, to ensure it can't be reused.
passCaptcha( $index, $word)
Given a required captcha run, test form input for correct input on the open session.
getCaptchaParamsFromRequest(WebRequest $request)
shouldCheck(WikiPage $page, $content, $section, $context, $oldtext=null)
addCaptchaAPI(&$resultArr)
doConfirmEdit(WikiPage $page, $newtext, $section, IContextSource $context)
Backend function for confirmEditMerged()
setTrigger( $trigger)
getCaptcha()
Returns an array with 'question' and 'answer' keys.
describeCaptchaType()
Describes the captcha type for API clients.
boolean null $captchaSolved
Was the CAPTCHA already passed and if yes, with which result?
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
Modify the appearance of the captcha field.
resetBadLoginCounter( $username)
Reset bad login counter after a successful login.
Represents a title within MediaWiki.
Definition Title.php:40
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:48
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
Definition User.php:1244
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:45
$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
this hook is for auditing only $req
Definition hooks.txt:979
namespace being checked & $result
Definition hooks.txt:2340
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:2843
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:855
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 use $formDescriptor instead & $formDescriptor
Definition hooks.txt:2157
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:1999
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:2848
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 use $formDescriptor instead 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
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:273
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:782
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. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header '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:1032
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:3070
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:1779
const CONTENT_MODEL_WIKITEXT
Definition Defines.php:244
Interface for configuration instances.
Definition Config.php:28
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
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
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$source
A helper class for throttling authentication attempts.
$content
if(is_array($mode)) switch( $mode) $input
const DB_REPLICA
Definition defines.php:25
$lines
Definition router.php:61
$params