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
27 * @subpackage Extensions
30 if ( defined( 'MEDIAWIKI' ) ) {
32 global $wgExtensionFunctions, $wgGroupPermissions;
34 $wgExtensionFunctions[] = 'ceSetup';
36 # Internationalisation file
37 require_once( 'ConfirmEdit.i18n.php' );
40 * The 'skipcaptcha' permission key can be given out to
41 * let known-good users perform triggering actions without
42 * having to go through the captcha.
44 * By default, sysops and registered bot accounts will be
45 * able to skip, while others have to go through it.
47 $wgGroupPermissions['*' ]['skipcaptcha'] = false;
48 $wgGroupPermissions['user' ]['skipcaptcha'] = false;
49 $wgGroupPermissions['autoconfirmed']['skipcaptcha'] = false;
50 $wgGroupPermissions['bot' ]['skipcaptcha'] = true; // registered bots
51 $wgGroupPermissions['sysop' ]['skipcaptcha'] = true;
53 global $wgCaptcha, $wgCaptchaClass, $wgCaptchaTriggers;
55 $wgCaptchaClass = 'SimpleCaptcha';
58 * Currently the captcha works only for page edits.
60 * If the 'edit' trigger is on, *every* edit will trigger the captcha.
61 * This may be useful for protecting against vandalbot attacks.
63 * If using the default 'addurl' trigger, the captcha will trigger on
64 * edits that include URLs that aren't in the current version of the page.
65 * This should catch automated linkspammers without annoying people when
66 * they make more typical edits.
68 $wgCaptchaTriggers = array();
69 $wgCaptchaTriggers['edit'] = false; // Would check on every edit
70 $wgCaptchaTriggers['addurl'] = true; // Check on edits that add URLs
71 $wgCaptchaTriggers['createaccount'] = true; // Special:Userlogin&type=signup
75 * Allow users who have confirmed their e-mail addresses to post
76 * URL links without being harassed by the captcha.
78 global $ceAllowConfirmedEmail;
79 $ceAllowConfirmedEmail = false;
82 * Regex to whitelist URLs to known-good sites...
84 * $wgCaptchaWhitelist = '#^https?://([a-z0-9-]+\\.)?(wikimedia|wikipedia)\.org/#i';
85 * @fixme Use the 'spam-whitelist' thingy instead?
87 $wgCaptchaWhitelist = false;
90 * Additional regexes to check for. Use full regexes; can match things
91 * other than URLs such as junk edits.
93 * If the new version matches one and the old version doesn't,
94 * toss up the captcha screen.
96 * @fixme Add a message for local admins to add items as well.
98 $wgCaptchaRegexes = array();
100 /** Register special page */
101 global $wgSpecialPages;
102 $wgSpecialPages['Captcha'] = array( /*class*/ 'SpecialPage', /*name*/'Captcha', /*restriction*/ '',
103 /*listed*/ false, /*function*/ false, /*file*/ false );
106 * Set up message strings for captcha utilities.
110 global $wgMessageCache, $wgConfirmEditMessages;
111 foreach( $wgConfirmEditMessages as $lang => $messages )
112 $wgMessageCache->addMessages( $messages, $lang );
114 global $wgHooks, $wgCaptcha, $wgCaptchaClass, $wgSpecialPages;
115 $wgCaptcha = new $wgCaptchaClass();
116 $wgHooks['EditFilter'][] = array( &$wgCaptcha, 'confirmEdit' );
118 $wgHooks['UserCreateForm'][] = array( &$wgCaptcha, 'injectUserCreate' );
119 $wgHooks['AbortNewAccount'][] = array( &$wgCaptcha, 'confirmUserCreate' );
123 * Entry point for Special:Captcha
125 function wfSpecialCaptcha( $par = null ) {
129 return $wgCaptcha->showImage();
132 return $wgCaptcha->showHelp();
136 class SimpleCaptcha {
138 * Insert a captcha prompt into the edit form.
139 * This sample implementation generates a simple arithmetic operation;
140 * it would be easy to defeat by machine.
144 * @return string HTML
147 $a = mt_rand(0, 100);
149 $op = mt_rand(0, 1) ? '+' : '-';
152 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
154 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
156 return "<p><label for=\"wpCaptchaWord\">$test</label> = " .
157 wfElement( 'input', array(
158 'name' => 'wpCaptchaWord',
159 'id' => 'wpCaptchaWord',
160 'tabindex' => 1 ) ) . // tab in before the edit textarea
162 wfElement( 'input', array(
164 'name' => 'wpCaptchaId',
165 'id' => 'wpCaptchaId',
166 'value' => $index ) );
170 * Insert the captcha prompt into an edit form.
171 * @param OutputPage $out
173 function editCallback( &$out ) {
174 $out->addWikiText( $this->getMessage( 'edit' ) );
175 $out->addHTML( $this->getForm() );
179 * Show a message asking the user to enter a captcha on edit
180 * The result will be treated as wiki text
182 * @param $action Action being performed
185 function getMessage( $action ) {
186 $name = 'captcha-' . $action;
187 $text = wfMsg( $name );
188 # Obtain a more tailored message, if possible, otherwise, fall back to
189 # the default for edits
190 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
195 * @fixme if multiple thingies insert a header, could break
196 * @param SimpleTemplate $template
197 * @return bool true to keep running callbacks
199 function injectUserCreate( &$template ) {
200 global $wgCaptchaTriggers, $wgOut;
201 if( $wgCaptchaTriggers['createaccount'] ) {
202 $template->set( 'header',
203 "<div class='captcha'>" .
204 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
212 * Check if the submitted form matches the captcha session data provided
213 * by the plugin when the form was generated.
217 * @param WebRequest $request
221 function keyMatch( $request, $info ) {
222 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
225 // ----------------------------------
228 * @param EditPage $editPage
229 * @param string $newtext
230 * @param string $section
231 * @return bool true if the captcha should run
233 function shouldCheck( &$editPage, $newtext, $section ) {
237 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
238 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
242 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
243 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
244 $wgUser->isEmailConfirmed() ) {
245 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
249 global $wgCaptchaTriggers;
250 if( !empty( $wgCaptchaTriggers['edit'] ) ) {
251 // Check on all edits
252 global $wgUser, $wgTitle;
253 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
255 $wgTitle->getPrefixedText() );
256 wfDebug( "ConfirmEdit: checking all edits...\n" );
260 if( !empty( $wgCaptchaTriggers['addurl'] ) ) {
261 // Only check edits that add URLs
262 $oldtext = $this->loadText( $editPage, $section );
264 $oldLinks = $this->findLinks( $oldtext );
265 $newLinks = $this->findLinks( $newtext );
266 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
268 $addedLinks = array_diff( $unknownLinks, $oldLinks );
269 $numLinks = count( $addedLinks );
271 if( $numLinks > 0 ) {
272 global $wgUser, $wgTitle;
273 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
276 $wgTitle->getPrefixedText(),
277 implode( ", ", $addedLinks ) );
282 global $wgCaptchaRegexes;
283 if( !empty( $wgCaptchaRegexes ) ) {
284 // Custom regex checks
285 $oldtext = $this->loadText( $editPage, $section );
287 foreach( $wgCaptchaRegexes as $regex ) {
288 $newMatches = array();
289 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
290 $oldMatches = array();
291 preg_match_all( $regex, $oldtext, $oldMatches );
293 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
295 $numHits = count( $addedMatches );
297 global $wgUser, $wgTitle;
298 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
302 $wgTitle->getPrefixedText(),
303 implode( ", ", $addedMatches ) );
314 * Filter callback function for URL whitelisting
315 * @return bool true if unknown, false if whitelisted
318 function filterLink( $url ) {
319 global $wgCaptchaWhitelist;
320 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
324 * The main callback run on edit attempts.
325 * @param EditPage $editPage
326 * @param string $newtext
327 * @param string $section
328 * @param bool true to continue saving, false to abort and show a captcha form
330 function confirmEdit( &$editPage, $newtext, $section ) {
331 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
332 if( $this->passCaptcha() ) {
335 $editPage->showEditForm( array( &$this, 'editCallback' ) );
339 wfDebug( "ConfirmEdit: no new links.\n" );
345 * Hook for user creation form submissions.
347 * @param string $message
348 * @return bool true to continue, false to abort user creation
350 function confirmUserCreate( $u, &$message ) {
351 global $wgCaptchaTriggers;
352 if( $wgCaptchaTriggers['createaccount'] ) {
353 $this->trigger = "new account '" . $u->getName() . "'";
354 if( !$this->passCaptcha() ) {
355 $message = wfMsg( 'captcha-createaccount-fail' );
363 * Given a required captcha run, test form input for correct
364 * input on the open session.
365 * @return bool if passed, false if failed or new session
367 function passCaptcha() {
368 $info = $this->retrieveCaptcha();
371 if( $this->keyMatch( $wgRequest, $info ) ) {
372 $this->log( "passed" );
373 $this->clearCaptcha( $info );
376 $this->clearCaptcha( $info );
377 $this->log( "bad form input" );
381 $this->log( "new captcha session" );
387 * Log the status and any triggering info for debugging or statistics
388 * @param string $message
390 function log( $message ) {
391 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
395 * Generate a captcha session ID and save the info in PHP's session storage.
396 * (Requires the user to have cookies enabled to get through the captcha.)
398 * A random ID is used so legit users can make edits in multiple tabs or
399 * windows without being unnecessarily hobbled by a serial order requirement.
400 * Pass the returned id value into the edit form as wpCaptchaId.
402 * @param array $info data to store
403 * @return string captcha ID key
405 function storeCaptcha( $info ) {
406 if( !isset( $info['index'] ) ) {
407 // Assign random index if we're not udpating
408 $info['index'] = strval( mt_rand() );
410 $_SESSION['captcha' . $info['index']] = $info;
411 return $info['index'];
415 * Fetch this session's captcha info.
416 * @return mixed array of info, or false if missing
418 function retrieveCaptcha() {
420 $index = $wgRequest->getVal( 'wpCaptchaId' );
421 if( isset( $_SESSION['captcha' . $index] ) ) {
422 return $_SESSION['captcha' . $index];
429 * Clear out existing captcha info from the session, to ensure
430 * it can't be reused.
432 function clearCaptcha( $info ) {
433 unset( $_SESSION['captcha' . $info['index']] );
437 * Retrieve the current version of the page or section being edited...
438 * @param EditPage $editPage
439 * @param string $section
443 function loadText( $editPage, $section ) {
444 $rev = Revision::newFromTitle( $editPage->mTitle );
445 if( is_null( $rev ) ) {
448 $text = $rev->getText();
449 if( $section != '' ) {
450 return Article::getSection( $text, $section );
458 * Extract a list of all recognized HTTP links in the text.
459 * @param string $text
460 * @return array of strings
462 function findLinks( $text ) {
463 global $wgParser, $wgTitle, $wgUser;
465 $options = new ParserOptions();
466 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
467 $out = $wgParser->parse( $text, $wgTitle, $options );
469 return array_keys( $out->getExternalLinks() );
473 * Show a page explaining what this wacky thing is.
475 function showHelp() {
476 global $wgOut, $ceAllowConfirmedEmail;
477 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
478 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
483 } # End invocation guard