4 * Experimental captcha plugin framework.
5 * Not intended as a real production captcha system; derived classes
6 * can extend the base to produce their fancy images in place of the
7 * text-based test output here.
9 * Copyright (C) 2005, 2006 Brion Vibber <brion@pobox.com>
10 * http://www.mediawiki.org/
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 * http://www.gnu.org/copyleft/gpl.html
27 * @addtogroup Extensions
30 if ( defined( 'MEDIAWIKI' ) ) {
32 global $wgExtensionFunctions, $wgGroupPermissions;
34 $wgExtensionFunctions[] = 'ceSetup';
35 $wgExtensionCredits['other'][] = array(
36 'name' => 'ConfirmEdit',
37 'author' => 'Brion Vibber',
38 'url' => 'http://www.mediawiki.org/wiki/Extension:ConfirmEdit',
39 'description' => 'Simple captcha implementation',
42 # Internationalisation file
43 require_once( 'ConfirmEdit.i18n.php' );
46 * The 'skipcaptcha' permission key can be given out to
47 * let known-good users perform triggering actions without
48 * having to go through the captcha.
50 * By default, sysops and registered bot accounts will be
51 * able to skip, while others have to go through it.
53 $wgGroupPermissions['*' ]['skipcaptcha'] = false;
54 $wgGroupPermissions['user' ]['skipcaptcha'] = false;
55 $wgGroupPermissions['autoconfirmed']['skipcaptcha'] = false;
56 $wgGroupPermissions['bot' ]['skipcaptcha'] = true; // registered bots
57 $wgGroupPermissions['sysop' ]['skipcaptcha'] = true;
59 global $wgCaptcha, $wgCaptchaClass, $wgCaptchaTriggers;
61 $wgCaptchaClass = 'SimpleCaptcha';
64 * Actions which can trigger a captcha
66 * If the 'edit' trigger is on, *every* edit will trigger the captcha.
67 * This may be useful for protecting against vandalbot attacks.
69 * If using the default 'addurl' trigger, the captcha will trigger on
70 * edits that include URLs that aren't in the current version of the page.
71 * This should catch automated linkspammers without annoying people when
72 * they make more typical edits.
74 * The captcha code should not use $wgCaptchaTriggers, but CaptchaTriggers()
75 * which also takes into account per namespace triggering.
77 $wgCaptchaTriggers = array();
78 $wgCaptchaTriggers['edit'] = false; // Would check on every edit
79 $wgCaptchaTriggers['create'] = false; // Check on page creation.
80 $wgCaptchaTriggers['addurl'] = true; // Check on edits that add URLs
81 $wgCaptchaTriggers['createaccount'] = true; // Special:Userlogin&type=signup
82 $wgCaptchaTriggers['badlogin'] = true; // Special:Userlogin after failure
85 * You may wish to apply special rules for captcha triggering on some namespaces.
86 * $wgCaptchaTriggersOnNamespace[<namespace id>][<trigger>] forces an always on /
87 * always off configuration with that trigger for the given namespace.
88 * Leave unset to use the global options ($wgCaptchaTriggers).
90 * Shall not be used with 'createaccount' (it is not checked).
92 $wgCaptchaTriggersOnNamespace = array();
95 #$wgCaptchaTriggersOnNamespace[NS_TALK]['create'] = false; //Allow creation of talk pages without captchas.
96 #$wgCaptchaTriggersOnNamespace[NS_PROJECT]['edit'] = true; //Show captcha whenever editing Project pages.
99 * Indicate how to store per-session data required to match up the
100 * internal captcha data with the editor.
102 * 'CaptchaSessionStore' uses PHP's session storage, which is cookie-based
103 * and may fail for anons with cookies disabled.
105 * 'CaptchaCacheStore' uses $wgMemc, which avoids the cookie dependency
106 * but may be fragile depending on cache configuration.
108 global $wgCaptchaStorageClass;
109 $wgCaptchaStorageClass = 'CaptchaSessionStore';
112 * Number of seconds a captcha session should last in the data cache
113 * before expiring when managing through CaptchaCacheStore class.
115 * Default is a half hour.
117 global $wgCaptchaSessionExpiration;
118 $wgCaptchaSessionExpiration = 30 * 60;
121 * Number of seconds after a bad login that a captcha will be shown to
122 * that client on the login form to slow down password-guessing bots.
124 * Has no effect if 'badlogin' is disabled in $wgCaptchaTriggers or
125 * if there is not a caching engine enabled.
127 * Default is five minutes.
129 global $wgCaptchaBadLoginExpiration;
130 $wgCaptchaBadLoginExpiration = 5 * 60;
133 * Allow users who have confirmed their e-mail addresses to post
134 * URL links without being harassed by the captcha.
136 global $ceAllowConfirmedEmail;
137 $ceAllowConfirmedEmail = false;
140 * Regex to whitelist URLs to known-good sites...
142 * $wgCaptchaWhitelist = '#^https?://([a-z0-9-]+\\.)?(wikimedia|wikipedia)\.org/#i';
143 * @fixme Use the 'spam-whitelist' thingy instead?
145 $wgCaptchaWhitelist = false;
148 * Additional regexes to check for. Use full regexes; can match things
149 * other than URLs such as junk edits.
151 * If the new version matches one and the old version doesn't,
152 * toss up the captcha screen.
154 * @fixme Add a message for local admins to add items as well.
156 $wgCaptchaRegexes = array();
158 /** Register special page */
159 global $wgSpecialPages;
160 $wgSpecialPages['Captcha'] = array( /*class*/ 'SpecialPage', /*name*/'Captcha', /*restriction*/ '',
161 /*listed*/ false, /*function*/ false, /*file*/ false );
164 * Set up message strings for captcha utilities.
168 global $wgMessageCache, $wgConfirmEditMessages;
169 foreach( $wgConfirmEditMessages as $lang => $messages )
170 $wgMessageCache->addMessages( $messages, $lang );
172 global $wgHooks, $wgCaptcha, $wgCaptchaClass, $wgSpecialPages;
173 $wgCaptcha = new $wgCaptchaClass();
174 $wgHooks['EditFilter'][] = array( &$wgCaptcha, 'confirmEdit' );
176 $wgHooks['UserCreateForm'][] = array( &$wgCaptcha, 'injectUserCreate' );
177 $wgHooks['AbortNewAccount'][] = array( &$wgCaptcha, 'confirmUserCreate' );
179 $wgHooks['LoginAuthenticateAudit'][] = array( &$wgCaptcha, 'triggerUserLogin' );
180 $wgHooks['UserLoginForm'][] = array( &$wgCaptcha, 'injectUserLogin' );
181 $wgHooks['AbortLogin'][] = array( &$wgCaptcha, 'confirmUserLogin' );
185 * Entry point for Special:Captcha
187 function wfSpecialCaptcha( $par = null ) {
191 return $wgCaptcha->showImage();
194 return $wgCaptcha->showHelp();
198 class SimpleCaptcha {
199 function SimpleCaptcha() {
200 global $wgCaptchaStorageClass;
201 $this->storage = new $wgCaptchaStorageClass;
205 * Insert a captcha prompt into the edit form.
206 * This sample implementation generates a simple arithmetic operation;
207 * it would be easy to defeat by machine.
211 * @return string HTML
214 $a = mt_rand(0, 100);
216 $op = mt_rand(0, 1) ? '+' : '-';
219 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
221 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
223 return "<p><label for=\"wpCaptchaWord\">$test</label> = " .
224 wfElement( 'input', array(
225 'name' => 'wpCaptchaWord',
226 'id' => 'wpCaptchaWord',
227 'tabindex' => 1 ) ) . // tab in before the edit textarea
229 wfElement( 'input', array(
231 'name' => 'wpCaptchaId',
232 'id' => 'wpCaptchaId',
233 'value' => $index ) );
237 * Insert the captcha prompt into an edit form.
238 * @param OutputPage $out
240 function editCallback( &$out ) {
241 $out->addWikiText( $this->getMessage( $this->action ) );
242 $out->addHTML( $this->getForm() );
246 * Show a message asking the user to enter a captcha on edit
247 * The result will be treated as wiki text
249 * @param $action Action being performed
252 function getMessage( $action ) {
253 $name = 'captcha-' . $action;
254 $text = wfMsg( $name );
255 # Obtain a more tailored message, if possible, otherwise, fall back to
256 # the default for edits
257 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
262 * @fixme if multiple thingies insert a header, could break
263 * @param SimpleTemplate $template
264 * @return bool true to keep running callbacks
266 function injectUserCreate( &$template ) {
267 global $wgCaptchaTriggers, $wgOut;
268 if( $wgCaptchaTriggers['createaccount'] ) {
269 $template->set( 'header',
270 "<div class='captcha'>" .
271 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
279 * Inject a captcha into the user login form after a failed
280 * password attempt as a speedbump for mass attacks.
281 * @fixme if multiple thingies insert a header, could break
282 * @param SimpleTemplate $template
283 * @return bool true to keep running callbacks
285 function injectUserLogin( &$template ) {
286 if( $this->isBadLoginTriggered() ) {
288 $template->set( 'header',
289 "<div class='captcha'>" .
290 $wgOut->parse( $this->getMessage( 'badlogin' ) ) .
298 * When a bad login attempt is made, increment an expiring counter
299 * in the memcache cloud. Later checks for this may trigger a
300 * captcha display to prevent too many hits from the same place.
302 * @param string $password
303 * @param int $retval authentication return value
304 * @return bool true to keep running callbacks
306 function triggerUserLogin( $user, $password, $retval ) {
307 global $wgCaptchaTriggers, $wgCaptchaBadLoginExpiration, $wgMemc;
308 if( $retval == LoginForm::WRONG_PASS && $wgCaptchaTriggers['badlogin'] ) {
309 $key = $this->badLoginKey();
310 $count = $wgMemc->get( $key );
312 $wgMemc->add( $key, 0, $wgCaptchaBadLoginExpiration );
314 $count = $wgMemc->incr( $key );
320 * Check if a bad login has already been registered for this
321 * IP address. If so, require a captcha.
325 function isBadLoginTriggered() {
327 return intval( $wgMemc->get( $this->badLoginKey() ) ) > 0;
331 * Internal cache key for badlogin checks.
335 function badLoginKey() {
336 return wfMemcKey( 'captcha', 'badlogin', 'ip', wfGetIP() );
340 * Check if the submitted form matches the captcha session data provided
341 * by the plugin when the form was generated.
345 * @param WebRequest $request
349 function keyMatch( $request, $info ) {
350 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
353 // ----------------------------------
356 * @param EditPage $editPage
357 * @param string $action (edit/create/addurl...)
358 * @return bool true if action triggers captcha on editPage's namespace
360 function captchaTriggers( &$editPage, $action) {
361 global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
362 //Special config for this NS?
363 if (isset( $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action] ) )
364 return $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action];
366 return ( !empty( $wgCaptchaTriggers[$action] ) ); //Default
371 * @param EditPage $editPage
372 * @param string $newtext
373 * @param string $section
374 * @return bool true if the captcha should run
376 function shouldCheck( &$editPage, $newtext, $section ) {
380 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
381 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
385 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
386 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
387 $wgUser->isEmailConfirmed() ) {
388 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
392 if( $this->captchaTriggers( $editPage, 'edit' ) ) {
393 // Check on all edits
394 global $wgUser, $wgTitle;
395 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
397 $wgTitle->getPrefixedText() );
398 $this->action = 'edit';
399 wfDebug( "ConfirmEdit: checking all edits...\n" );
403 if( $this->captchaTriggers( $editPage, 'create' ) && !$editPage->mTitle->exists() ) {
404 //Check if creating a page
405 global $wgUser, $wgTitle;
406 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
408 $wgTitle->getPrefixedText() );
409 $this->action = 'create';
410 wfDebug( "ConfirmEdit: checking on page creation...\n" );
414 if( $this->captchaTriggers( $editPage, 'addurl' ) ) {
415 // Only check edits that add URLs
416 $oldtext = $this->loadText( $editPage, $section );
418 $oldLinks = $this->findLinks( $oldtext );
419 $newLinks = $this->findLinks( $newtext );
420 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
422 $addedLinks = array_diff( $unknownLinks, $oldLinks );
423 $numLinks = count( $addedLinks );
425 if( $numLinks > 0 ) {
426 global $wgUser, $wgTitle;
427 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
430 $wgTitle->getPrefixedText(),
431 implode( ", ", $addedLinks ) );
432 $this->action = 'addurl';
437 global $wgCaptchaRegexes;
438 if( !empty( $wgCaptchaRegexes ) ) {
439 // Custom regex checks
440 $oldtext = $this->loadText( $editPage, $section );
442 foreach( $wgCaptchaRegexes as $regex ) {
443 $newMatches = array();
444 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
445 $oldMatches = array();
446 preg_match_all( $regex, $oldtext, $oldMatches );
448 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
450 $numHits = count( $addedMatches );
452 global $wgUser, $wgTitle;
453 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
457 $wgTitle->getPrefixedText(),
458 implode( ", ", $addedMatches ) );
459 $this->action = 'edit';
470 * Filter callback function for URL whitelisting
471 * @return bool true if unknown, false if whitelisted
474 function filterLink( $url ) {
475 global $wgCaptchaWhitelist;
476 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
480 * The main callback run on edit attempts.
481 * @param EditPage $editPage
482 * @param string $newtext
483 * @param string $section
484 * @param bool true to continue saving, false to abort and show a captcha form
486 function confirmEdit( &$editPage, $newtext, $section ) {
487 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
488 if( $this->passCaptcha() ) {
491 $editPage->showEditForm( array( &$this, 'editCallback' ) );
495 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
501 * Hook for user creation form submissions.
503 * @param string $message
504 * @return bool true to continue, false to abort user creation
506 function confirmUserCreate( $u, &$message ) {
507 global $wgCaptchaTriggers;
508 if( $wgCaptchaTriggers['createaccount'] ) {
509 $this->trigger = "new account '" . $u->getName() . "'";
510 if( !$this->passCaptcha() ) {
511 $message = wfMsg( 'captcha-createaccount-fail' );
519 * Hook for user login form submissions.
521 * @param string $message
522 * @return bool true to continue, false to abort user creation
524 function confirmUserLogin( $u, $pass, &$retval ) {
525 if( $this->isBadLoginTriggered() ) {
526 $this->trigger = "post-badlogin login '" . $u->getName() . "'";
527 if( !$this->passCaptcha() ) {
528 $message = wfMsg( 'captcha-badlogin-fail' );
529 // Emulate a bad-password return to confuse the shit out of attackers
530 $retval = LoginForm::WRONG_PASS;
538 * Given a required captcha run, test form input for correct
539 * input on the open session.
540 * @return bool if passed, false if failed or new session
542 function passCaptcha() {
543 $info = $this->retrieveCaptcha();
546 if( $this->keyMatch( $wgRequest, $info ) ) {
547 $this->log( "passed" );
548 $this->clearCaptcha( $info );
551 $this->clearCaptcha( $info );
552 $this->log( "bad form input" );
556 $this->log( "new captcha session" );
562 * Log the status and any triggering info for debugging or statistics
563 * @param string $message
565 function log( $message ) {
566 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
570 * Generate a captcha session ID and save the info in PHP's session storage.
571 * (Requires the user to have cookies enabled to get through the captcha.)
573 * A random ID is used so legit users can make edits in multiple tabs or
574 * windows without being unnecessarily hobbled by a serial order requirement.
575 * Pass the returned id value into the edit form as wpCaptchaId.
577 * @param array $info data to store
578 * @return string captcha ID key
580 function storeCaptcha( $info ) {
581 if( !isset( $info['index'] ) ) {
582 // Assign random index if we're not udpating
583 $info['index'] = strval( mt_rand() );
585 $this->storage->store( $info['index'], $info );
586 return $info['index'];
590 * Fetch this session's captcha info.
591 * @return mixed array of info, or false if missing
593 function retrieveCaptcha() {
595 $index = $wgRequest->getVal( 'wpCaptchaId' );
596 return $this->storage->retrieve( $index );
600 * Clear out existing captcha info from the session, to ensure
601 * it can't be reused.
603 function clearCaptcha( $info ) {
604 $this->storage->clear( $info['index'] );
608 * Retrieve the current version of the page or section being edited...
609 * @param EditPage $editPage
610 * @param string $section
614 function loadText( $editPage, $section ) {
615 $rev = Revision::newFromTitle( $editPage->mTitle );
616 if( is_null( $rev ) ) {
619 $text = $rev->getText();
620 if( $section != '' ) {
621 return Article::getSection( $text, $section );
629 * Extract a list of all recognized HTTP links in the text.
630 * @param string $text
631 * @return array of strings
633 function findLinks( $text ) {
634 global $wgParser, $wgTitle, $wgUser;
636 $options = new ParserOptions();
637 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
638 $out = $wgParser->parse( $text, $wgTitle, $options );
640 return array_keys( $out->getExternalLinks() );
644 * Show a page explaining what this wacky thing is.
646 function showHelp() {
647 global $wgOut, $ceAllowConfirmedEmail;
648 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
649 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
650 if ( $this->storage->cookiesNeeded() ) {
651 $wgOut->addWikiText( wfMsg( 'captchahelp-cookies-needed' ) );
657 class CaptchaSessionStore {
658 function store( $index, $info ) {
659 $_SESSION['captcha' . $info['index']] = $info;
662 function retrieve( $index ) {
663 if( isset( $_SESSION['captcha' . $index] ) ) {
664 return $_SESSION['captcha' . $index];
670 function clear( $index ) {
671 unset( $_SESSION['captcha' . $index] );
674 function cookiesNeeded() {
679 class CaptchaCacheStore {
680 function store( $index, $info ) {
681 global $wgMemc, $wgCaptchaSessionExpiration;
682 $wgMemc->set( wfMemcKey( 'captcha', $index ), $info,
683 $wgCaptchaSessionExpiration );
686 function retrieve( $index ) {
688 $info = $wgMemc->get( wfMemcKey( 'captcha', $index ) );
696 function clear( $index ) {
698 $wgMemc->delete( wfMemcKey( 'captcha', $index ) );
701 function cookiesNeeded() {
706 } # End invocation guard