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['LoginBadPass'][] = 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 * @return bool true to keep running callbacks
305 function triggerUserLogin( $user, $password ) {
306 global $wgCaptchaTriggers, $wgCaptchaBadLoginExpiration, $wgMemc;
307 if( $wgCaptchaTriggers['badlogin'] ) {
308 $key = $this->badLoginKey();
309 $count = $wgMemc->get( $key );
311 $wgMemc->add( $key, 0, $wgCaptchaBadLoginExpiration );
313 $count = $wgMemc->incr( $key );
319 * Check if a bad login has already been registered for this
320 * IP address. If so, require a captcha.
324 function isBadLoginTriggered() {
326 return intval( $wgMemc->get( $this->badLoginKey() ) ) > 0;
330 * Internal cache key for badlogin checks.
334 function badLoginKey() {
335 return wfMemcKey( 'captcha', 'badlogin', 'ip', wfGetIP() );
339 * Check if the submitted form matches the captcha session data provided
340 * by the plugin when the form was generated.
344 * @param WebRequest $request
348 function keyMatch( $request, $info ) {
349 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
352 // ----------------------------------
355 * @param EditPage $editPage
356 * @param string $action (edit/create/addurl...)
357 * @return bool true if action triggers captcha on editPage's namespace
359 function captchaTriggers( &$editPage, $action) {
360 global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
361 //Special config for this NS?
362 if (isset( $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action] ) )
363 return $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action];
365 return ( !empty( $wgCaptchaTriggers[$action] ) ); //Default
370 * @param EditPage $editPage
371 * @param string $newtext
372 * @param string $section
373 * @return bool true if the captcha should run
375 function shouldCheck( &$editPage, $newtext, $section ) {
379 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
380 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
384 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
385 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
386 $wgUser->isEmailConfirmed() ) {
387 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
391 if( $this->captchaTriggers( $editPage, 'edit' ) ) {
392 // Check on all edits
393 global $wgUser, $wgTitle;
394 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
396 $wgTitle->getPrefixedText() );
397 $this->action = 'edit';
398 wfDebug( "ConfirmEdit: checking all edits...\n" );
402 if( $this->captchaTriggers( $editPage, 'create' ) && !$editPage->mTitle->exists() ) {
403 //Check if creating a page
404 global $wgUser, $wgTitle;
405 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
407 $wgTitle->getPrefixedText() );
408 $this->action = 'create';
409 wfDebug( "ConfirmEdit: checking on page creation...\n" );
413 if( $this->captchaTriggers( $editPage, 'addurl' ) ) {
414 // Only check edits that add URLs
415 $oldtext = $this->loadText( $editPage, $section );
417 $oldLinks = $this->findLinks( $oldtext );
418 $newLinks = $this->findLinks( $newtext );
419 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
421 $addedLinks = array_diff( $unknownLinks, $oldLinks );
422 $numLinks = count( $addedLinks );
424 if( $numLinks > 0 ) {
425 global $wgUser, $wgTitle;
426 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
429 $wgTitle->getPrefixedText(),
430 implode( ", ", $addedLinks ) );
431 $this->action = 'addurl';
436 global $wgCaptchaRegexes;
437 if( !empty( $wgCaptchaRegexes ) ) {
438 // Custom regex checks
439 $oldtext = $this->loadText( $editPage, $section );
441 foreach( $wgCaptchaRegexes as $regex ) {
442 $newMatches = array();
443 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
444 $oldMatches = array();
445 preg_match_all( $regex, $oldtext, $oldMatches );
447 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
449 $numHits = count( $addedMatches );
451 global $wgUser, $wgTitle;
452 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
456 $wgTitle->getPrefixedText(),
457 implode( ", ", $addedMatches ) );
458 $this->action = 'edit';
469 * Filter callback function for URL whitelisting
470 * @return bool true if unknown, false if whitelisted
473 function filterLink( $url ) {
474 global $wgCaptchaWhitelist;
475 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
479 * The main callback run on edit attempts.
480 * @param EditPage $editPage
481 * @param string $newtext
482 * @param string $section
483 * @param bool true to continue saving, false to abort and show a captcha form
485 function confirmEdit( &$editPage, $newtext, $section ) {
486 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
487 if( $this->passCaptcha() ) {
490 $editPage->showEditForm( array( &$this, 'editCallback' ) );
494 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
500 * Hook for user creation form submissions.
502 * @param string $message
503 * @return bool true to continue, false to abort user creation
505 function confirmUserCreate( $u, &$message ) {
506 global $wgCaptchaTriggers;
507 if( $wgCaptchaTriggers['createaccount'] ) {
508 $this->trigger = "new account '" . $u->getName() . "'";
509 if( !$this->passCaptcha() ) {
510 $message = wfMsg( 'captcha-createaccount-fail' );
518 * Hook for user login form submissions.
520 * @param string $message
521 * @return bool true to continue, false to abort user creation
523 function confirmUserLogin( $u, $pass, &$retval ) {
524 if( $this->isBadLoginTriggered() ) {
525 $this->trigger = "post-badlogin login '" . $u->getName() . "'";
526 if( !$this->passCaptcha() ) {
527 $message = wfMsg( 'captcha-badlogin-fail' );
528 // Emulate a bad-password return to confuse the shit out of attackers
529 $retval = LoginForm::WRONG_PASS;
537 * Given a required captcha run, test form input for correct
538 * input on the open session.
539 * @return bool if passed, false if failed or new session
541 function passCaptcha() {
542 $info = $this->retrieveCaptcha();
545 if( $this->keyMatch( $wgRequest, $info ) ) {
546 $this->log( "passed" );
547 $this->clearCaptcha( $info );
550 $this->clearCaptcha( $info );
551 $this->log( "bad form input" );
555 $this->log( "new captcha session" );
561 * Log the status and any triggering info for debugging or statistics
562 * @param string $message
564 function log( $message ) {
565 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
569 * Generate a captcha session ID and save the info in PHP's session storage.
570 * (Requires the user to have cookies enabled to get through the captcha.)
572 * A random ID is used so legit users can make edits in multiple tabs or
573 * windows without being unnecessarily hobbled by a serial order requirement.
574 * Pass the returned id value into the edit form as wpCaptchaId.
576 * @param array $info data to store
577 * @return string captcha ID key
579 function storeCaptcha( $info ) {
580 if( !isset( $info['index'] ) ) {
581 // Assign random index if we're not udpating
582 $info['index'] = strval( mt_rand() );
584 $this->storage->store( $info['index'], $info );
585 return $info['index'];
589 * Fetch this session's captcha info.
590 * @return mixed array of info, or false if missing
592 function retrieveCaptcha() {
594 $index = $wgRequest->getVal( 'wpCaptchaId' );
595 return $this->storage->retrieve( $index );
599 * Clear out existing captcha info from the session, to ensure
600 * it can't be reused.
602 function clearCaptcha( $info ) {
603 $this->storage->clear( $info['index'] );
607 * Retrieve the current version of the page or section being edited...
608 * @param EditPage $editPage
609 * @param string $section
613 function loadText( $editPage, $section ) {
614 $rev = Revision::newFromTitle( $editPage->mTitle );
615 if( is_null( $rev ) ) {
618 $text = $rev->getText();
619 if( $section != '' ) {
620 return Article::getSection( $text, $section );
628 * Extract a list of all recognized HTTP links in the text.
629 * @param string $text
630 * @return array of strings
632 function findLinks( $text ) {
633 global $wgParser, $wgTitle, $wgUser;
635 $options = new ParserOptions();
636 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
637 $out = $wgParser->parse( $text, $wgTitle, $options );
639 return array_keys( $out->getExternalLinks() );
643 * Show a page explaining what this wacky thing is.
645 function showHelp() {
646 global $wgOut, $ceAllowConfirmedEmail;
647 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
648 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
649 if ( $this->storage->cookiesNeeded() ) {
650 $wgOut->addWikiText( wfMsg( 'captchahelp-cookies-needed' ) );
656 class CaptchaSessionStore {
657 function store( $index, $info ) {
658 $_SESSION['captcha' . $info['index']] = $info;
661 function retrieve( $index ) {
662 if( isset( $_SESSION['captcha' . $index] ) ) {
663 return $_SESSION['captcha' . $index];
669 function clear( $index ) {
670 unset( $_SESSION['captcha' . $index] );
673 function cookiesNeeded() {
678 class CaptchaCacheStore {
679 function store( $index, $info ) {
680 global $wgMemc, $wgCaptchaSessionExpiration;
681 $wgMemc->set( wfMemcKey( 'captcha', $index ), $info,
682 $wgCaptchaSessionExpiration );
685 function retrieve( $index ) {
687 $info = $wgMemc->get( wfMemcKey( 'captcha', $index ) );
695 function clear( $index ) {
697 $wgMemc->delete( wfMemcKey( 'captcha', $index ) );
700 function cookiesNeeded() {
705 } # End invocation guard