5 function getCaptcha() {
6 $a = mt_rand( 0, 100 );
9 /* Minus sign is used in the question. UTF-8,
10 since the api uses text/plain, not text/html */
11 $op = mt_rand( 0, 1 ) ? '+' : '−';
13 // No space before and after $op, to ensure correct
16 $answer = ( $op == '+' ) ? ( $a + $b ) : ( $a - $b );
17 return array( 'question' => $test, 'answer' => $answer );
20 function addCaptchaAPI( &$resultArr ) {
21 $captcha = $this->getCaptcha();
22 $index = $this->storeCaptcha( $captcha );
23 $resultArr['captcha']['type'] = 'simple';
24 $resultArr['captcha']['mime'] = 'text/plain';
25 $resultArr['captcha']['id'] = $index;
26 $resultArr['captcha']['question'] = $captcha['question'];
30 * Insert a captcha prompt into the edit form.
31 * This sample implementation generates a simple arithmetic operation;
32 * it would be easy to defeat by machine.
39 $captcha = $this->getCaptcha();
40 $index = $this->storeCaptcha( $captcha );
42 return "<p><label for=\"wpCaptchaWord\">{$captcha['question']}</label> = " .
43 Xml::element( 'input', array(
44 'name' => 'wpCaptchaWord',
45 'id' => 'wpCaptchaWord',
46 'tabindex' => 1 ) ) . // tab in before the edit textarea
48 Xml::element( 'input', array(
50 'name' => 'wpCaptchaId',
51 'id' => 'wpCaptchaId',
52 'value' => $index ) );
56 * Insert the captcha prompt into an edit form.
57 * @param OutputPage $out
59 function editCallback( &$out ) {
60 $out->addWikiText( $this->getMessage( $this->action ) );
61 $out->addHTML( $this->getForm() );
65 * Show a message asking the user to enter a captcha on edit
66 * The result will be treated as wiki text
68 * @param $action Action being performed
71 function getMessage( $action ) {
72 $name = 'captcha-' . $action;
73 $text = wfMsg( $name );
74 # Obtain a more tailored message, if possible, otherwise, fall back to
75 # the default for edits
76 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
81 * @fixme if multiple thingies insert a header, could break
82 * @param $form HTMLForm
83 * @return bool true to keep running callbacks
85 function injectEmailUser( &$form ) {
86 global $wgCaptchaTriggers, $wgOut, $wgUser;
87 if ( $wgCaptchaTriggers['sendemail'] ) {
88 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
89 wfDebug( "ConfirmEdit: user group allows skipping captcha on email sending\n" );
93 "<div class='captcha'>" .
94 $wgOut->parse( $this->getMessage( 'sendemail' ) ) .
103 * @fixme if multiple thingies insert a header, could break
104 * @param QuickTemplate $template
105 * @return bool true to keep running callbacks
107 function injectUserCreate( &$template ) {
108 global $wgCaptchaTriggers, $wgOut, $wgUser;
109 if ( $wgCaptchaTriggers['createaccount'] ) {
110 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
111 wfDebug( "ConfirmEdit: user group allows skipping captcha on account creation\n" );
114 $template->set( 'header',
115 "<div class='captcha'>" .
116 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
124 * Inject a captcha into the user login form after a failed
125 * password attempt as a speedbump for mass attacks.
126 * @fixme if multiple thingies insert a header, could break
127 * @param $template QuickTemplate
128 * @return bool true to keep running callbacks
130 function injectUserLogin( &$template ) {
131 if ( $this->isBadLoginTriggered() ) {
133 $template->set( 'header',
134 "<div class='captcha'>" .
135 $wgOut->parse( $this->getMessage( 'badlogin' ) ) .
143 * When a bad login attempt is made, increment an expiring counter
144 * in the memcache cloud. Later checks for this may trigger a
145 * captcha display to prevent too many hits from the same place.
147 * @param string $password
148 * @param int $retval authentication return value
149 * @return bool true to keep running callbacks
151 function triggerUserLogin( $user, $password, $retval ) {
152 global $wgCaptchaTriggers, $wgCaptchaBadLoginExpiration, $wgMemc;
153 if ( $retval == LoginForm::WRONG_PASS && $wgCaptchaTriggers['badlogin'] ) {
154 $key = $this->badLoginKey();
155 $count = $wgMemc->get( $key );
157 $wgMemc->add( $key, 0, $wgCaptchaBadLoginExpiration );
159 $count = $wgMemc->incr( $key );
165 * Check if a bad login has already been registered for this
166 * IP address. If so, require a captcha.
170 function isBadLoginTriggered() {
171 global $wgMemc, $wgCaptchaTriggers, $wgCaptchaBadLoginAttempts;
172 return $wgCaptchaTriggers['badlogin'] && intval( $wgMemc->get( $this->badLoginKey() ) ) >= $wgCaptchaBadLoginAttempts;
176 * Check if the IP is allowed to skip captchas
178 function isIPWhitelisted() {
179 global $wgCaptchaWhitelistIP;
181 if ( $wgCaptchaWhitelistIP ) {
184 $ip = $wgRequest->getIP();
186 foreach ( $wgCaptchaWhitelistIP as $range ) {
187 if ( IP::isInRange( $ip, $range ) ) {
196 * Internal cache key for badlogin checks.
200 function badLoginKey() {
202 return wfMemcKey( 'captcha', 'badlogin', 'ip', $wgRequest->getIP() );
206 * Check if the submitted form matches the captcha session data provided
207 * by the plugin when the form was generated.
211 * @param string $answer
215 function keyMatch( $answer, $info ) {
216 return $answer == $info['answer'];
219 // ----------------------------------
222 * @param EditPage $editPage
223 * @param string $action (edit/create/addurl...)
224 * @return bool true if action triggers captcha on editPage's namespace
226 function captchaTriggers( &$editPage, $action ) {
227 global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
228 // Special config for this NS?
229 if ( isset( $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action] ) )
230 return $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action];
232 return ( !empty( $wgCaptchaTriggers[$action] ) ); // Default
236 * @param EditPage $editPage
237 * @param string $newtext
238 * @param string $section
239 * @return bool true if the captcha should run
241 function shouldCheck( &$editPage, $newtext, $section, $merged = false ) {
243 $title = $editPage->mArticle->getTitle();
246 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
247 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
250 if ( $this->isIPWhitelisted() )
254 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
255 if ( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
256 $wgUser->isEmailConfirmed() ) {
257 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
261 if ( $this->captchaTriggers( $editPage, 'edit' ) ) {
262 // Check on all edits
264 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
266 $title->getPrefixedText() );
267 $this->action = 'edit';
268 wfDebug( "ConfirmEdit: checking all edits...\n" );
272 if ( $this->captchaTriggers( $editPage, 'create' ) && !$editPage->mTitle->exists() ) {
273 // Check if creating a page
275 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
277 $title->getPrefixedText() );
278 $this->action = 'create';
279 wfDebug( "ConfirmEdit: checking on page creation...\n" );
283 if ( $this->captchaTriggers( $editPage, 'addurl' ) ) {
284 // Only check edits that add URLs
286 // Get links from the database
287 $oldLinks = $this->getLinksFromTracker( $title );
288 // Share a parse operation with Article::doEdit()
289 $editInfo = $editPage->mArticle->prepareTextForEdit( $newtext );
290 $newLinks = array_keys( $editInfo->output->getExternalLinks() );
292 // Get link changes in the slowest way known to man
293 $oldtext = $this->loadText( $editPage, $section );
294 $oldLinks = $this->findLinks( $editPage, $oldtext );
295 $newLinks = $this->findLinks( $editPage, $newtext );
298 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
299 $addedLinks = array_diff( $unknownLinks, $oldLinks );
300 $numLinks = count( $addedLinks );
302 if ( $numLinks > 0 ) {
304 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
307 $title->getPrefixedText(),
308 implode( ", ", $addedLinks ) );
309 $this->action = 'addurl';
314 global $wgCaptchaRegexes;
315 if ( $wgCaptchaRegexes ) {
316 // Custom regex checks
317 $oldtext = $this->loadText( $editPage, $section );
319 foreach ( $wgCaptchaRegexes as $regex ) {
320 $newMatches = array();
321 if ( preg_match_all( $regex, $newtext, $newMatches ) ) {
322 $oldMatches = array();
323 preg_match_all( $regex, $oldtext, $oldMatches );
325 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
327 $numHits = count( $addedMatches );
328 if ( $numHits > 0 ) {
330 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
334 $title->getPrefixedText(),
335 implode( ", ", $addedMatches ) );
336 $this->action = 'edit';
347 * Filter callback function for URL whitelisting
348 * @param string url to check
349 * @return bool true if unknown, false if whitelisted
352 function filterLink( $url ) {
353 global $wgCaptchaWhitelist;
354 $source = wfMsgForContent( 'captcha-addurl-whitelist' );
356 $whitelist = wfEmptyMsg( 'captcha-addurl-whitelist', $source )
358 : $this->buildRegexes( explode( "\n", $source ) );
360 $cwl = $wgCaptchaWhitelist !== false ? preg_match( $wgCaptchaWhitelist, $url ) : false;
361 $wl = $whitelist !== false ? preg_match( $whitelist, $url ) : false;
363 return !( $cwl || $wl );
367 * Build regex from whitelist
368 * @param string lines from [[MediaWiki:Captcha-addurl-whitelist]]
369 * @return string Regex or bool false if whitelist is empty
372 function buildRegexes( $lines ) {
373 # Code duplicated from the SpamBlacklist extension (r19197)
375 # Strip comments and whitespace, then remove blanks
376 $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
378 # No lines, don't make a regex which will match everything
379 if ( count( $lines ) == 0 ) {
380 wfDebug( "No lines\n" );
384 # It's faster using the S modifier even though it will usually only be run once
385 // $regex = 'http://+[a-z0-9_\-.]*(' . implode( '|', $lines ) . ')';
386 // return '/' . str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $regex) ) . '/Si';
388 $regexStart = '/^https?:\/\/+[a-z0-9_\-.]*(';
392 foreach ( $lines as $line ) {
393 // FIXME: not very robust size check, but should work. :)
394 if ( $build === false ) {
396 } elseif ( strlen( $build ) + strlen( $line ) > $regexMax ) {
397 $regexes .= $regexStart .
398 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build ) ) .
402 $build .= '|' . $line;
405 if ( $build !== false ) {
406 $regexes .= $regexStart .
407 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build ) ) .
415 * Load external links from the externallinks table
416 * @param $title Title
419 function getLinksFromTracker( $title ) {
420 $dbr = wfGetDB( DB_SLAVE );
421 $id = $title->getArticleID(); // should be zero queries
422 $res = $dbr->select( 'externallinks', array( 'el_to' ),
423 array( 'el_from' => $id ), __METHOD__ );
425 foreach ( $res as $row ) {
426 $links[] = $row->el_to;
432 * Backend function for confirmEdit() and confirmEditAPI()
433 * @return bool false if the CAPTCHA is rejected, true otherwise
435 private function doConfirmEdit( $editPage, $newtext, $section, $merged = false ) {
437 if ( $wgRequest->getVal( 'captchaid' ) ) {
438 $wgRequest->setVal( 'wpCaptchaId', $wgRequest->getVal( 'captchaid' ) );
440 if ( $wgRequest->getVal( 'captchaword' ) ) {
441 $wgRequest->setVal( 'wpCaptchaWord', $wgRequest->getVal( 'captchaword' ) );
443 if ( $this->shouldCheck( $editPage, $newtext, $section, $merged ) ) {
444 return $this->passCaptcha();
446 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
452 * The main callback run on edit attempts.
453 * @param EditPage $editPage
454 * @param string $newtext
455 * @param string $section
456 * @param bool $merged
457 * @return bool true to continue saving, false to abort and show a captcha form
459 function confirmEdit( $editPage, $newtext, $section, $merged = false ) {
460 if ( defined( 'MW_API' ) ) {
462 # The CAPTCHA was already checked and approved
465 if ( !$this->doConfirmEdit( $editPage, $newtext, $section, $merged ) ) {
466 $editPage->showEditForm( array( &$this, 'editCallback' ) );
473 * A more efficient edit filter callback based on the text after section merging
474 * @param EditPage $editPage
475 * @param string $newtext
477 function confirmEditMerged( $editPage, $newtext ) {
478 return $this->confirmEdit( $editPage, $newtext, false, true );
481 function confirmEditAPI( $editPage, $newtext, &$resultArr ) {
482 if ( !$this->doConfirmEdit( $editPage, $newtext, false, false ) ) {
483 $this->addCaptchaAPI( $resultArr );
491 * Hook for user creation form submissions.
493 * @param string $message
494 * @return bool true to continue, false to abort user creation
496 function confirmUserCreate( $u, &$message ) {
497 global $wgCaptchaTriggers, $wgUser;
498 if ( $wgCaptchaTriggers['createaccount'] ) {
499 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
500 wfDebug( "ConfirmEdit: user group allows skipping captcha on account creation\n" );
503 if ( $this->isIPWhitelisted() )
506 $this->trigger = "new account '" . $u->getName() . "'";
507 if ( !$this->passCaptcha() ) {
508 $message = wfMsg( 'captcha-createaccount-fail' );
516 * Hook for user login form submissions.
518 * @param string $message
519 * @return bool true to continue, false to abort user creation
521 function confirmUserLogin( $u, $pass, &$retval ) {
522 if ( $this->isBadLoginTriggered() ) {
523 if ( $this->isIPWhitelisted() )
526 $this->trigger = "post-badlogin login '" . $u->getName() . "'";
527 if ( !$this->passCaptcha() ) {
528 // Emulate a bad-password return to confuse the shit out of attackers
529 $retval = LoginForm::WRONG_PASS;
537 * Check the captcha on Special:EmailUser
538 * @param $from MailAddress
539 * @param $to MailAddress
540 * @param $subject String
541 * @param $text String
542 * @param $error String reference
543 * @return Bool true to continue saving, false to abort and show a captcha form
545 function confirmEmailUser( $from, $to, $subject, $text, &$error ) {
546 global $wgCaptchaTriggers, $wgUser;
547 if ( $wgCaptchaTriggers['sendemail'] ) {
548 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
549 wfDebug( "ConfirmEdit: user group allows skipping captcha on email sending\n" );
552 if ( $this->isIPWhitelisted() )
555 if ( defined( 'MW_API' ) ) {
557 # Asking for captchas in the API is really silly
558 $error = wfMsg( 'captcha-disabledinapi' );
561 $this->trigger = "{$wgUser->getName()} sending email";
562 if ( !$this->passCaptcha() ) {
563 $error = wfMsg( 'captcha-sendemail-fail' );
571 * @param $module ApiBase
572 * @param $params array
575 public function APIGetAllowedParams( &$module, &$params ) {
576 if ( !$module instanceof ApiEditPage ) {
579 $params['captchaword'] = null;
580 $params['captchaid'] = null;
586 * @param $module ApiBae
590 public function APIGetParamDescription( &$module, &$desc ) {
591 if ( !$module instanceof ApiEditPage ) {
594 $desc['captchaid'] = 'CAPTCHA ID from previous request';
595 $desc['captchaword'] = 'Answer to the CAPTCHA';
601 * Given a required captcha run, test form input for correct
602 * input on the open session.
603 * @return bool if passed, false if failed or new session
605 function passCaptcha() {
606 $info = $this->retrieveCaptcha();
609 if ( $this->keyMatch( $wgRequest->getVal( 'wpCaptchaWord' ), $info ) ) {
610 $this->log( "passed" );
611 $this->clearCaptcha( $info );
614 $this->clearCaptcha( $info );
615 $this->log( "bad form input" );
619 $this->log( "new captcha session" );
625 * Log the status and any triggering info for debugging or statistics
626 * @param string $message
628 function log( $message ) {
629 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
633 * Generate a captcha session ID and save the info in PHP's session storage.
634 * (Requires the user to have cookies enabled to get through the captcha.)
636 * A random ID is used so legit users can make edits in multiple tabs or
637 * windows without being unnecessarily hobbled by a serial order requirement.
638 * Pass the returned id value into the edit form as wpCaptchaId.
640 * @param array $info data to store
641 * @return string captcha ID key
643 function storeCaptcha( $info ) {
644 if ( !isset( $info['index'] ) ) {
645 // Assign random index if we're not udpating
646 $info['index'] = strval( mt_rand() );
648 CaptchaStore::get()->store( $info['index'], $info );
649 return $info['index'];
653 * Fetch this session's captcha info.
654 * @return mixed array of info, or false if missing
656 function retrieveCaptcha() {
658 $index = $wgRequest->getVal( 'wpCaptchaId' );
659 return CaptchaStore::get()->retrieve( $index );
663 * Clear out existing captcha info from the session, to ensure
664 * it can't be reused.
666 function clearCaptcha( $info ) {
667 CaptchaStore::get()->clear( $info['index'] );
671 * Retrieve the current version of the page or section being edited...
672 * @param EditPage $editPage
673 * @param string $section
677 function loadText( $editPage, $section ) {
678 $rev = Revision::newFromTitle( $editPage->mTitle );
679 if ( is_null( $rev ) ) {
682 $text = $rev->getText();
683 if ( $section != '' ) {
685 return $wgParser->getSection( $text, $section );
693 * Extract a list of all recognized HTTP links in the text.
694 * @param string $text
695 * @return array of strings
697 function findLinks( &$editpage, $text ) {
698 global $wgParser, $wgUser;
700 $options = new ParserOptions();
701 $text = $wgParser->preSaveTransform( $text, $editpage->mTitle, $wgUser, $options );
702 $out = $wgParser->parse( $text, $editpage->mTitle, $options );
704 return array_keys( $out->getExternalLinks() );
708 * Show a page explaining what this wacky thing is.
710 function showHelp() {
712 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
713 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
714 if ( CaptchaStore::get()->cookiesNeeded() ) {
715 $wgOut->addWikiText( wfMsg( 'captchahelp-cookies-needed' ) );