3 * Experimental captcha plugin framework.
4 * Not intended as a real production captcha system; derived classes
5 * can extend the base to produce their fancy images in place of the
6 * text-based test output here.
8 * Copyright (C) 2005, 2006 Brion Vibber <brion@pobox.com>
9 * http://www.mediawiki.org/
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 * http://www.gnu.org/copyleft/gpl.html
26 * @addtogroup Extensions
29 if ( defined( 'MEDIAWIKI' ) ) {
31 global $wgExtensionFunctions, $wgGroupPermissions;
33 $wgExtensionFunctions[] = 'ceSetup';
34 $wgExtensionCredits['other'][] = array(
35 'name' => 'ConfirmEdit',
36 'author' => 'Brion Vibber',
37 'url' => 'http://meta.wikimedia.org/wiki/ConfirmEdit_extension',
38 'description' => 'Simple captcha implementation',
41 # Internationalisation file
42 require_once( 'ConfirmEdit.i18n.php' );
45 * The 'skipcaptcha' permission key can be given out to
46 * let known-good users perform triggering actions without
47 * having to go through the captcha.
49 * By default, sysops and registered bot accounts will be
50 * able to skip, while others have to go through it.
52 $wgGroupPermissions['*' ]['skipcaptcha'] = false;
53 $wgGroupPermissions['user' ]['skipcaptcha'] = false;
54 $wgGroupPermissions['autoconfirmed']['skipcaptcha'] = false;
55 $wgGroupPermissions['bot' ]['skipcaptcha'] = true; // registered bots
56 $wgGroupPermissions['sysop' ]['skipcaptcha'] = true;
58 global $wgCaptcha, $wgCaptchaClass, $wgCaptchaTriggers;
60 $wgCaptchaClass = 'SimpleCaptcha';
63 * Currently the captcha works only for page edits.
65 * If the 'edit' trigger is on, *every* edit will trigger the captcha.
66 * This may be useful for protecting against vandalbot attacks.
68 * If using the default 'addurl' trigger, the captcha will trigger on
69 * edits that include URLs that aren't in the current version of the page.
70 * This should catch automated linkspammers without annoying people when
71 * they make more typical edits.
73 $wgCaptchaTriggers = array();
74 $wgCaptchaTriggers['edit'] = false; // Would check on every edit
75 $wgCaptchaTriggers['addurl'] = true; // Check on edits that add URLs
76 $wgCaptchaTriggers['createaccount'] = true; // Special:Userlogin&type=signup
80 * Allow users who have confirmed their e-mail addresses to post
81 * URL links without being harassed by the captcha.
83 global $ceAllowConfirmedEmail;
84 $ceAllowConfirmedEmail = false;
87 * Regex to whitelist URLs to known-good sites...
89 * $wgCaptchaWhitelist = '#^https?://([a-z0-9-]+\\.)?(wikimedia|wikipedia)\.org/#i';
90 * @fixme Use the 'spam-whitelist' thingy instead?
92 $wgCaptchaWhitelist = false;
95 * Additional regexes to check for. Use full regexes; can match things
96 * other than URLs such as junk edits.
98 * If the new version matches one and the old version doesn't,
99 * toss up the captcha screen.
101 * @fixme Add a message for local admins to add items as well.
103 $wgCaptchaRegexes = array();
105 /** Register special page */
106 global $wgSpecialPages;
107 $wgSpecialPages['Captcha'] = array( /*class*/ 'SpecialPage', /*name*/'Captcha', /*restriction*/ '',
108 /*listed*/ false, /*function*/ false, /*file*/ false );
111 * Set up message strings for captcha utilities.
115 global $wgMessageCache, $wgConfirmEditMessages;
116 foreach( $wgConfirmEditMessages as $lang => $messages )
117 $wgMessageCache->addMessages( $messages, $lang );
119 global $wgHooks, $wgCaptcha, $wgCaptchaClass, $wgSpecialPages;
120 $wgCaptcha = new $wgCaptchaClass();
121 $wgHooks['EditFilter'][] = array( &$wgCaptcha, 'confirmEdit' );
123 $wgHooks['UserCreateForm'][] = array( &$wgCaptcha, 'injectUserCreate' );
124 $wgHooks['AbortNewAccount'][] = array( &$wgCaptcha, 'confirmUserCreate' );
128 * Entry point for Special:Captcha
130 function wfSpecialCaptcha( $par = null ) {
134 return $wgCaptcha->showImage();
137 return $wgCaptcha->showHelp();
141 class SimpleCaptcha {
143 * Insert a captcha prompt into the edit form.
144 * This sample implementation generates a simple arithmetic operation;
145 * it would be easy to defeat by machine.
149 * @return string HTML
152 $a = mt_rand(0, 100);
154 $op = mt_rand(0, 1) ? '+' : '-';
157 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
159 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
161 return "<p><label for=\"wpCaptchaWord\">$test</label> = " .
162 wfElement( 'input', array(
163 'name' => 'wpCaptchaWord',
164 'id' => 'wpCaptchaWord',
165 'tabindex' => 1 ) ) . // tab in before the edit textarea
167 wfElement( 'input', array(
169 'name' => 'wpCaptchaId',
170 'id' => 'wpCaptchaId',
171 'value' => $index ) );
175 * Insert the captcha prompt into an edit form.
176 * @param OutputPage $out
178 function editCallback( &$out ) {
179 $out->addWikiText( $this->getMessage( 'edit' ) );
180 $out->addHTML( $this->getForm() );
184 * Show a message asking the user to enter a captcha on edit
185 * The result will be treated as wiki text
187 * @param $action Action being performed
190 function getMessage( $action ) {
191 $name = 'captcha-' . $action;
192 $text = wfMsg( $name );
193 # Obtain a more tailored message, if possible, otherwise, fall back to
194 # the default for edits
195 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
200 * @fixme if multiple thingies insert a header, could break
201 * @param SimpleTemplate $template
202 * @return bool true to keep running callbacks
204 function injectUserCreate( &$template ) {
205 global $wgCaptchaTriggers, $wgOut;
206 if( $wgCaptchaTriggers['createaccount'] ) {
207 $template->set( 'header',
208 "<div class='captcha'>" .
209 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
217 * Check if the submitted form matches the captcha session data provided
218 * by the plugin when the form was generated.
222 * @param WebRequest $request
226 function keyMatch( $request, $info ) {
227 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
230 // ----------------------------------
233 * @param EditPage $editPage
234 * @param string $newtext
235 * @param string $section
236 * @return bool true if the captcha should run
238 function shouldCheck( &$editPage, $newtext, $section ) {
242 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
243 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
247 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
248 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
249 $wgUser->isEmailConfirmed() ) {
250 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
254 global $wgCaptchaTriggers;
255 if( !empty( $wgCaptchaTriggers['edit'] ) ) {
256 // Check on all edits
257 global $wgUser, $wgTitle;
258 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
260 $wgTitle->getPrefixedText() );
261 wfDebug( "ConfirmEdit: checking all edits...\n" );
265 if( !empty( $wgCaptchaTriggers['addurl'] ) ) {
266 // Only check edits that add URLs
267 $oldtext = $this->loadText( $editPage, $section );
269 $oldLinks = $this->findLinks( $oldtext );
270 $newLinks = $this->findLinks( $newtext );
271 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
273 $addedLinks = array_diff( $unknownLinks, $oldLinks );
274 $numLinks = count( $addedLinks );
276 if( $numLinks > 0 ) {
277 global $wgUser, $wgTitle;
278 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
281 $wgTitle->getPrefixedText(),
282 implode( ", ", $addedLinks ) );
287 global $wgCaptchaRegexes;
288 if( !empty( $wgCaptchaRegexes ) ) {
289 // Custom regex checks
290 $oldtext = $this->loadText( $editPage, $section );
292 foreach( $wgCaptchaRegexes as $regex ) {
293 $newMatches = array();
294 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
295 $oldMatches = array();
296 preg_match_all( $regex, $oldtext, $oldMatches );
298 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
300 $numHits = count( $addedMatches );
302 global $wgUser, $wgTitle;
303 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
307 $wgTitle->getPrefixedText(),
308 implode( ", ", $addedMatches ) );
319 * Filter callback function for URL whitelisting
320 * @return bool true if unknown, false if whitelisted
323 function filterLink( $url ) {
324 global $wgCaptchaWhitelist;
325 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
329 * The main callback run on edit attempts.
330 * @param EditPage $editPage
331 * @param string $newtext
332 * @param string $section
333 * @param bool true to continue saving, false to abort and show a captcha form
335 function confirmEdit( &$editPage, $newtext, $section ) {
336 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
337 if( $this->passCaptcha() ) {
340 $editPage->showEditForm( array( &$this, 'editCallback' ) );
344 wfDebug( "ConfirmEdit: no new links.\n" );
350 * Hook for user creation form submissions.
352 * @param string $message
353 * @return bool true to continue, false to abort user creation
355 function confirmUserCreate( $u, &$message ) {
356 global $wgCaptchaTriggers;
357 if( $wgCaptchaTriggers['createaccount'] ) {
358 $this->trigger = "new account '" . $u->getName() . "'";
359 if( !$this->passCaptcha() ) {
360 $message = wfMsg( 'captcha-createaccount-fail' );
368 * Given a required captcha run, test form input for correct
369 * input on the open session.
370 * @return bool if passed, false if failed or new session
372 function passCaptcha() {
373 $info = $this->retrieveCaptcha();
376 if( $this->keyMatch( $wgRequest, $info ) ) {
377 $this->log( "passed" );
378 $this->clearCaptcha( $info );
381 $this->clearCaptcha( $info );
382 $this->log( "bad form input" );
386 $this->log( "new captcha session" );
392 * Log the status and any triggering info for debugging or statistics
393 * @param string $message
395 function log( $message ) {
396 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
400 * Generate a captcha session ID and save the info in PHP's session storage.
401 * (Requires the user to have cookies enabled to get through the captcha.)
403 * A random ID is used so legit users can make edits in multiple tabs or
404 * windows without being unnecessarily hobbled by a serial order requirement.
405 * Pass the returned id value into the edit form as wpCaptchaId.
407 * @param array $info data to store
408 * @return string captcha ID key
410 function storeCaptcha( $info ) {
411 if( !isset( $info['index'] ) ) {
412 // Assign random index if we're not udpating
413 $info['index'] = strval( mt_rand() );
415 $_SESSION['captcha' . $info['index']] = $info;
416 return $info['index'];
420 * Fetch this session's captcha info.
421 * @return mixed array of info, or false if missing
423 function retrieveCaptcha() {
425 $index = $wgRequest->getVal( 'wpCaptchaId' );
426 if( isset( $_SESSION['captcha' . $index] ) ) {
427 return $_SESSION['captcha' . $index];
434 * Clear out existing captcha info from the session, to ensure
435 * it can't be reused.
437 function clearCaptcha( $info ) {
438 unset( $_SESSION['captcha' . $info['index']] );
442 * Retrieve the current version of the page or section being edited...
443 * @param EditPage $editPage
444 * @param string $section
448 function loadText( $editPage, $section ) {
449 $rev = Revision::newFromTitle( $editPage->mTitle );
450 if( is_null( $rev ) ) {
453 $text = $rev->getText();
454 if( $section != '' ) {
455 return Article::getSection( $text, $section );
463 * Extract a list of all recognized HTTP links in the text.
464 * @param string $text
465 * @return array of strings
467 function findLinks( $text ) {
468 global $wgParser, $wgTitle, $wgUser;
470 $options = new ParserOptions();
471 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
472 $out = $wgParser->parse( $text, $wgTitle, $options );
474 return array_keys( $out->getExternalLinks() );
478 * Show a page explaining what this wacky thing is.
480 function showHelp() {
481 global $wgOut, $ceAllowConfirmedEmail;
482 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
483 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
488 } # End invocation guard