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://meta.wikimedia.org/wiki/ConfirmEdit_extension',
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
84 * You may wish to apply special rules for captcha triggering on some namespaces.
85 * $wgCaptchaTriggersOnNamespace[<namespace id>][<trigger>] forces an always on /
86 * always off configuration with that trigger for the given namespace.
87 * Leave unset to use the global options ($wgCaptchaTriggers).
89 * Shall not be used with 'createaccount' (it is not checked).
91 $wgCaptchaTriggersOnNamespace = array();
94 #$wgCaptchaTriggersOnNamespace[NS_TALK]['create'] = false; //Allow creation of talk pages without captchas.
95 #$wgCaptchaTriggersOnNamespace[NS_PROJECT]['edit'] = true; //Show captcha whenever editing Project pages.
98 * Indicate how to store per-session data required to match up the
99 * internal captcha data with the editor.
101 * 'CaptchaSessionStore' uses PHP's session storage, which is cookie-based
102 * and may fail for anons with cookies disabled.
104 * 'CaptchaCacheStore' uses $wgMemc, which avoids the cookie dependency
105 * but may be fragile depending on cache configuration.
107 global $wgCaptchaStorageClass;
108 $wgCaptchaStorageClass = 'CaptchaSessionStore';
111 * Number of sections a captcha session should last in the data cache
112 * before expiring when managing through CaptchaCacheStore class.
114 * Default is a half hour.
116 global $wgCaptchaSessionExpiration;
117 $wgCaptchaSessionExpiration = 30 * 60;
120 * Allow users who have confirmed their e-mail addresses to post
121 * URL links without being harassed by the captcha.
123 global $ceAllowConfirmedEmail;
124 $ceAllowConfirmedEmail = false;
127 * Regex to whitelist URLs to known-good sites...
129 * $wgCaptchaWhitelist = '#^https?://([a-z0-9-]+\\.)?(wikimedia|wikipedia)\.org/#i';
130 * @fixme Use the 'spam-whitelist' thingy instead?
132 $wgCaptchaWhitelist = false;
135 * Additional regexes to check for. Use full regexes; can match things
136 * other than URLs such as junk edits.
138 * If the new version matches one and the old version doesn't,
139 * toss up the captcha screen.
141 * @fixme Add a message for local admins to add items as well.
143 $wgCaptchaRegexes = array();
145 /** Register special page */
146 global $wgSpecialPages;
147 $wgSpecialPages['Captcha'] = array( /*class*/ 'SpecialPage', /*name*/'Captcha', /*restriction*/ '',
148 /*listed*/ false, /*function*/ false, /*file*/ false );
151 * Set up message strings for captcha utilities.
155 global $wgMessageCache, $wgConfirmEditMessages;
156 foreach( $wgConfirmEditMessages as $lang => $messages )
157 $wgMessageCache->addMessages( $messages, $lang );
159 global $wgHooks, $wgCaptcha, $wgCaptchaClass, $wgSpecialPages;
160 $wgCaptcha = new $wgCaptchaClass();
161 $wgHooks['EditFilter'][] = array( &$wgCaptcha, 'confirmEdit' );
163 $wgHooks['UserCreateForm'][] = array( &$wgCaptcha, 'injectUserCreate' );
164 $wgHooks['AbortNewAccount'][] = array( &$wgCaptcha, 'confirmUserCreate' );
168 * Entry point for Special:Captcha
170 function wfSpecialCaptcha( $par = null ) {
174 return $wgCaptcha->showImage();
177 return $wgCaptcha->showHelp();
181 class SimpleCaptcha {
182 function SimpleCaptcha() {
183 global $wgCaptchaStorageClass;
184 $this->storage = new $wgCaptchaStorageClass;
188 * Insert a captcha prompt into the edit form.
189 * This sample implementation generates a simple arithmetic operation;
190 * it would be easy to defeat by machine.
194 * @return string HTML
197 $a = mt_rand(0, 100);
199 $op = mt_rand(0, 1) ? '+' : '-';
202 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
204 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
206 return "<p><label for=\"wpCaptchaWord\">$test</label> = " .
207 wfElement( 'input', array(
208 'name' => 'wpCaptchaWord',
209 'id' => 'wpCaptchaWord',
210 'tabindex' => 1 ) ) . // tab in before the edit textarea
212 wfElement( 'input', array(
214 'name' => 'wpCaptchaId',
215 'id' => 'wpCaptchaId',
216 'value' => $index ) );
220 * Insert the captcha prompt into an edit form.
221 * @param OutputPage $out
223 function editCallback( &$out ) {
224 $out->addWikiText( $this->getMessage( $this->action ) );
225 $out->addHTML( $this->getForm() );
229 * Show a message asking the user to enter a captcha on edit
230 * The result will be treated as wiki text
232 * @param $action Action being performed
235 function getMessage( $action ) {
236 $name = 'captcha-' . $action;
237 $text = wfMsg( $name );
238 # Obtain a more tailored message, if possible, otherwise, fall back to
239 # the default for edits
240 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
245 * @fixme if multiple thingies insert a header, could break
246 * @param SimpleTemplate $template
247 * @return bool true to keep running callbacks
249 function injectUserCreate( &$template ) {
250 global $wgCaptchaTriggers, $wgOut;
251 if( $wgCaptchaTriggers['createaccount'] ) {
252 $template->set( 'header',
253 "<div class='captcha'>" .
254 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
262 * Check if the submitted form matches the captcha session data provided
263 * by the plugin when the form was generated.
267 * @param WebRequest $request
271 function keyMatch( $request, $info ) {
272 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
275 // ----------------------------------
278 * @param EditPage $editPage
279 * @param string $action (edit/create/addurl...)
280 * @return bool true if action triggers captcha on editPage's namespace
282 function captchaTriggers( &$editPage, $action) {
283 global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
284 //Special config for this NS?
285 if (isset( $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action] ) )
286 return $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action];
288 return ( !empty( $wgCaptchaTriggers[$action] ) ); //Default
293 * @param EditPage $editPage
294 * @param string $newtext
295 * @param string $section
296 * @return bool true if the captcha should run
298 function shouldCheck( &$editPage, $newtext, $section ) {
302 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
303 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
307 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
308 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
309 $wgUser->isEmailConfirmed() ) {
310 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
314 if( $this->captchaTriggers( $editPage, 'edit' ) ) {
315 // Check on all edits
316 global $wgUser, $wgTitle;
317 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
319 $wgTitle->getPrefixedText() );
320 $this->action = 'edit';
321 wfDebug( "ConfirmEdit: checking all edits...\n" );
325 if( $this->captchaTriggers( $editPage, 'create' ) && !$editPage->mTitle->exists() ) {
326 //Check if creating a page
327 global $wgUser, $wgTitle;
328 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
330 $wgTitle->getPrefixedText() );
331 $this->action = 'create';
332 wfDebug( "ConfirmEdit: checking on page creation...\n" );
336 if( $this->captchaTriggers( $editPage, 'addurl' ) ) {
337 // Only check edits that add URLs
338 $oldtext = $this->loadText( $editPage, $section );
340 $oldLinks = $this->findLinks( $oldtext );
341 $newLinks = $this->findLinks( $newtext );
342 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
344 $addedLinks = array_diff( $unknownLinks, $oldLinks );
345 $numLinks = count( $addedLinks );
347 if( $numLinks > 0 ) {
348 global $wgUser, $wgTitle;
349 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
352 $wgTitle->getPrefixedText(),
353 implode( ", ", $addedLinks ) );
354 $this->action = 'addurl';
359 global $wgCaptchaRegexes;
360 if( !empty( $wgCaptchaRegexes ) ) {
361 // Custom regex checks
362 $oldtext = $this->loadText( $editPage, $section );
364 foreach( $wgCaptchaRegexes as $regex ) {
365 $newMatches = array();
366 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
367 $oldMatches = array();
368 preg_match_all( $regex, $oldtext, $oldMatches );
370 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
372 $numHits = count( $addedMatches );
374 global $wgUser, $wgTitle;
375 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
379 $wgTitle->getPrefixedText(),
380 implode( ", ", $addedMatches ) );
381 $this->action = 'edit';
392 * Filter callback function for URL whitelisting
393 * @return bool true if unknown, false if whitelisted
396 function filterLink( $url ) {
397 global $wgCaptchaWhitelist;
398 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
402 * The main callback run on edit attempts.
403 * @param EditPage $editPage
404 * @param string $newtext
405 * @param string $section
406 * @param bool true to continue saving, false to abort and show a captcha form
408 function confirmEdit( &$editPage, $newtext, $section ) {
409 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
410 if( $this->passCaptcha() ) {
413 $editPage->showEditForm( array( &$this, 'editCallback' ) );
417 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
423 * Hook for user creation form submissions.
425 * @param string $message
426 * @return bool true to continue, false to abort user creation
428 function confirmUserCreate( $u, &$message ) {
429 global $wgCaptchaTriggers;
430 if( $wgCaptchaTriggers['createaccount'] ) {
431 $this->trigger = "new account '" . $u->getName() . "'";
432 if( !$this->passCaptcha() ) {
433 $message = wfMsg( 'captcha-createaccount-fail' );
441 * Given a required captcha run, test form input for correct
442 * input on the open session.
443 * @return bool if passed, false if failed or new session
445 function passCaptcha() {
446 $info = $this->retrieveCaptcha();
449 if( $this->keyMatch( $wgRequest, $info ) ) {
450 $this->log( "passed" );
451 $this->clearCaptcha( $info );
454 $this->clearCaptcha( $info );
455 $this->log( "bad form input" );
459 $this->log( "new captcha session" );
465 * Log the status and any triggering info for debugging or statistics
466 * @param string $message
468 function log( $message ) {
469 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
473 * Generate a captcha session ID and save the info in PHP's session storage.
474 * (Requires the user to have cookies enabled to get through the captcha.)
476 * A random ID is used so legit users can make edits in multiple tabs or
477 * windows without being unnecessarily hobbled by a serial order requirement.
478 * Pass the returned id value into the edit form as wpCaptchaId.
480 * @param array $info data to store
481 * @return string captcha ID key
483 function storeCaptcha( $info ) {
484 if( !isset( $info['index'] ) ) {
485 // Assign random index if we're not udpating
486 $info['index'] = strval( mt_rand() );
488 $this->storage->store( $info['index'], $info );
489 return $info['index'];
493 * Fetch this session's captcha info.
494 * @return mixed array of info, or false if missing
496 function retrieveCaptcha() {
498 $index = $wgRequest->getVal( 'wpCaptchaId' );
499 return $this->storage->retrieve( $index );
503 * Clear out existing captcha info from the session, to ensure
504 * it can't be reused.
506 function clearCaptcha( $info ) {
507 $this->storage->clear( $info['index'] );
511 * Retrieve the current version of the page or section being edited...
512 * @param EditPage $editPage
513 * @param string $section
517 function loadText( $editPage, $section ) {
518 $rev = Revision::newFromTitle( $editPage->mTitle );
519 if( is_null( $rev ) ) {
522 $text = $rev->getText();
523 if( $section != '' ) {
524 return Article::getSection( $text, $section );
532 * Extract a list of all recognized HTTP links in the text.
533 * @param string $text
534 * @return array of strings
536 function findLinks( $text ) {
537 global $wgParser, $wgTitle, $wgUser;
539 $options = new ParserOptions();
540 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
541 $out = $wgParser->parse( $text, $wgTitle, $options );
543 return array_keys( $out->getExternalLinks() );
547 * Show a page explaining what this wacky thing is.
549 function showHelp() {
550 global $wgOut, $ceAllowConfirmedEmail;
551 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
552 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
557 class CaptchaSessionStore {
558 function store( $index, $info ) {
559 $_SESSION['captcha' . $info['index']] = $info;
562 function retrieve( $index ) {
563 if( isset( $_SESSION['captcha' . $index] ) ) {
564 return $_SESSION['captcha' . $index];
570 function clear( $index ) {
571 unset( $_SESSION['captcha' . $index] );
575 class CaptchaCacheStore {
576 function store( $index, $info ) {
577 global $wgMemc, $wgCaptchaSessionExpiration;
578 $wgMemc->set( wfMemcKey( 'captcha', $index ), $info,
579 $wgCaptchaSessionExpiration );
582 function retrieve( $index ) {
584 $info = $wgMemc->get( wfMemcKey( 'captcha', $index ) );
592 function clear( $index ) {
594 $wgMemc->delete( wfMemcKey( 'captcha', $index ) );
598 } # End invocation guard