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 if ( !function_exists( 'extAddMessages' ) ) {
38 require( dirname(__FILE__) . '/../ExtensionFunctions.php' );
40 require_once( 'ConfirmEdit.i18n.php' );
43 * The 'skipcaptcha' permission key can be given out to
44 * let known-good users perform triggering actions without
45 * having to go through the captcha.
47 * By default, sysops and registered bot accounts will be
48 * able to skip, while others have to go through it.
50 $wgGroupPermissions['*' ]['skipcaptcha'] = false;
51 $wgGroupPermissions['user' ]['skipcaptcha'] = false;
52 $wgGroupPermissions['autoconfirmed']['skipcaptcha'] = false;
53 $wgGroupPermissions['bot' ]['skipcaptcha'] = true; // registered bots
54 $wgGroupPermissions['sysop' ]['skipcaptcha'] = true;
56 global $wgCaptcha, $wgCaptchaClass, $wgCaptchaTriggers;
58 $wgCaptchaClass = 'SimpleCaptcha';
61 * Currently the captcha works only for page edits.
63 * If the 'edit' trigger is on, *every* edit will trigger the captcha.
64 * This may be useful for protecting against vandalbot attacks.
66 * If using the default 'addurl' trigger, the captcha will trigger on
67 * edits that include URLs that aren't in the current version of the page.
68 * This should catch automated linkspammers without annoying people when
69 * they make more typical edits.
71 $wgCaptchaTriggers = array();
72 $wgCaptchaTriggers['edit'] = false; // Would check on every edit
73 $wgCaptchaTriggers['addurl'] = true; // Check on edits that add URLs
74 $wgCaptchaTriggers['createaccount'] = true; // Special:Userlogin&type=signup
78 * Allow users who have confirmed their e-mail addresses to post
79 * URL links without being harassed by the captcha.
81 global $ceAllowConfirmedEmail;
82 $ceAllowConfirmedEmail = false;
85 * Regex to whitelist URLs to known-good sites...
87 * $wgCaptchaWhitelist = '#^https?://([a-z0-9-]+\\.)?(wikimedia|wikipedia)\.org/#i';
88 * @fixme Use the 'spam-whitelist' thingy instead?
90 $wgCaptchaWhitelist = false;
93 * Additional regexes to check for. Use full regexes; can match things
94 * other than URLs such as junk edits.
96 * If the new version matches one and the old version doesn't,
97 * toss up the captcha screen.
99 * @fixme Add a message for local admins to add items as well.
101 $wgCaptchaRegexes = array();
103 /** Register special page */
104 global $wgSpecialPages;
105 $wgSpecialPages['Captcha'] = array( /*class*/ 'SpecialPage', /*name*/'Captcha', false,
106 /*listed*/ false, /*function*/ false, /*file*/ false );
109 * Set up message strings for captcha utilities.
113 global $wgConfirmEditMessages;
114 extAddMessages( $wgConfirmEditMessages );
116 global $wgHooks, $wgCaptcha, $wgCaptchaClass, $wgSpecialPages;
117 $wgCaptcha = new $wgCaptchaClass();
118 $wgHooks['EditFilter'][] = array( &$wgCaptcha, 'confirmEdit' );
120 $wgHooks['UserCreateForm'][] = array( &$wgCaptcha, 'injectUserCreate' );
121 $wgHooks['AbortNewAccount'][] = array( &$wgCaptcha, 'confirmUserCreate' );
125 * Entry point for Special:Captcha
127 function wfSpecialCaptcha( $par = null ) {
131 return $wgCaptcha->showImage();
134 return $wgCaptcha->showHelp();
138 class SimpleCaptcha {
140 * Insert a captcha prompt into the edit form.
141 * This sample implementation generates a simple arithmetic operation;
142 * it would be easy to defeat by machine.
146 * @return string HTML
149 $a = mt_rand(0, 100);
151 $op = mt_rand(0, 1) ? '+' : '-';
154 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
156 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
158 return "<p><label for=\"wpCaptchaWord\">$test</label> = " .
159 wfElement( 'input', array(
160 'name' => 'wpCaptchaWord',
161 'id' => 'wpCaptchaWord',
162 'tabindex' => 1 ) ) . // tab in before the edit textarea
164 wfElement( 'input', array(
166 'name' => 'wpCaptchaId',
167 'id' => 'wpCaptchaId',
168 'value' => $index ) );
172 * Insert the captcha prompt into an edit form.
173 * @param OutputPage $out
175 function editCallback( &$out ) {
176 $out->addWikiText( wfMsg( "captcha-short" ) );
177 $out->addHTML( $this->getForm() );
182 * @fixme if multiple thingies insert a header, could break
183 * @param SimpleTemplate $template
184 * @return bool true to keep running callbacks
186 function injectUserCreate( &$template ) {
187 global $wgCaptchaTriggers, $wgOut;
188 if( $wgCaptchaTriggers['createaccount'] ) {
189 $template->set( 'header',
190 "<div class='captcha'>" .
191 $wgOut->parse( wfMsg( 'captcha-createaccount' ) ) .
199 * Check if the submitted form matches the captcha session data provided
200 * by the plugin when the form was generated.
204 * @param WebRequest $request
208 function keyMatch( $request, $info ) {
209 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
212 // ----------------------------------
215 * @param EditPage $editPage
216 * @param string $newtext
217 * @param string $section
218 * @return bool true if the captcha should run
220 function shouldCheck( &$editPage, $newtext, $section ) {
224 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
225 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
229 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
230 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
231 $wgUser->isEmailConfirmed() ) {
232 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
236 global $wgCaptchaTriggers;
237 if( !empty( $wgCaptchaTriggers['edit'] ) ) {
238 // Check on all edits
239 global $wgUser, $wgTitle;
240 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
242 $wgTitle->getPrefixedText() );
243 wfDebug( "ConfirmEdit: checking all edits...\n" );
247 if( !empty( $wgCaptchaTriggers['addurl'] ) ) {
248 // Only check edits that add URLs
249 $oldtext = $this->loadText( $editPage, $section );
251 $oldLinks = $this->findLinks( $oldtext );
252 $newLinks = $this->findLinks( $newtext );
253 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
255 $addedLinks = array_diff( $unknownLinks, $oldLinks );
256 $numLinks = count( $addedLinks );
258 if( $numLinks > 0 ) {
259 global $wgUser, $wgTitle;
260 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
263 $wgTitle->getPrefixedText(),
264 implode( ", ", $addedLinks ) );
269 global $wgCaptchaRegexes;
270 if( !empty( $wgCaptchaRegexes ) ) {
271 // Custom regex checks
272 $oldtext = $this->loadText( $editPage, $section );
274 foreach( $wgCaptchaRegexes as $regex ) {
275 $newMatches = array();
276 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
277 $oldMatches = array();
278 preg_match_all( $regex, $oldtext, $oldMatches );
280 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
282 $numHits = count( $addedMatches );
284 global $wgUser, $wgTitle;
285 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
289 $wgTitle->getPrefixedText(),
290 implode( ", ", $addedMatches ) );
301 * Filter callback function for URL whitelisting
302 * @return bool true if unknown, false if whitelisted
305 function filterLink( $url ) {
306 global $wgCaptchaWhitelist;
307 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
311 * The main callback run on edit attempts.
312 * @param EditPage $editPage
313 * @param string $newtext
314 * @param string $section
315 * @param bool true to continue saving, false to abort and show a captcha form
317 function confirmEdit( &$editPage, $newtext, $section ) {
318 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
319 if( $this->passCaptcha() ) {
322 $editPage->showEditForm( array( &$this, 'editCallback' ) );
326 wfDebug( "ConfirmEdit: no new links.\n" );
332 * Hook for user creation form submissions.
334 * @param string $message
335 * @return bool true to continue, false to abort user creation
337 function confirmUserCreate( $u, &$message ) {
338 global $wgCaptchaTriggers;
339 if( $wgCaptchaTriggers['createaccount'] ) {
340 $this->trigger = "new account '" . $u->getName() . "'";
341 if( !$this->passCaptcha() ) {
342 $message = wfMsg( 'captcha-createaccount-fail' );
350 * Given a required captcha run, test form input for correct
351 * input on the open session.
352 * @return bool if passed, false if failed or new session
354 function passCaptcha() {
355 $info = $this->retrieveCaptcha();
358 if( $this->keyMatch( $wgRequest, $info ) ) {
359 $this->log( "passed" );
360 $this->clearCaptcha( $info );
363 $this->clearCaptcha( $info );
364 $this->log( "bad form input" );
368 $this->log( "new captcha session" );
374 * Log the status and any triggering info for debugging or statistics
375 * @param string $message
377 function log( $message ) {
378 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
382 * Generate a captcha session ID and save the info in PHP's session storage.
383 * (Requires the user to have cookies enabled to get through the captcha.)
385 * A random ID is used so legit users can make edits in multiple tabs or
386 * windows without being unnecessarily hobbled by a serial order requirement.
387 * Pass the returned id value into the edit form as wpCaptchaId.
389 * @param array $info data to store
390 * @return string captcha ID key
392 function storeCaptcha( $info ) {
393 if( !isset( $info['index'] ) ) {
394 // Assign random index if we're not udpating
395 $info['index'] = strval( mt_rand() );
397 $_SESSION['captcha' . $info['index']] = $info;
398 return $info['index'];
402 * Fetch this session's captcha info.
403 * @return mixed array of info, or false if missing
405 function retrieveCaptcha() {
407 $index = $wgRequest->getVal( 'wpCaptchaId' );
408 if( isset( $_SESSION['captcha' . $index] ) ) {
409 return $_SESSION['captcha' . $index];
416 * Clear out existing captcha info from the session, to ensure
417 * it can't be reused.
419 function clearCaptcha( $info ) {
420 unset( $_SESSION['captcha' . $info['index']] );
424 * Retrieve the current version of the page or section being edited...
425 * @param EditPage $editPage
426 * @param string $section
430 function loadText( $editPage, $section ) {
431 $rev = Revision::newFromTitle( $editPage->mTitle );
432 if( is_null( $rev ) ) {
435 $text = $rev->getText();
436 if( $section != '' ) {
437 return Article::getSection( $text, $section );
445 * Extract a list of all recognized HTTP links in the text.
446 * @param string $text
447 * @return array of strings
449 function findLinks( $text ) {
450 $regex = '/((?:' . HTTP_PROTOCOLS . ')' . EXT_LINK_URL_CLASS . '+)/';
452 if( preg_match_all( $regex, $text, $matches, PREG_PATTERN_ORDER ) ) {
460 * Show a page explaining what this wacky thing is.
462 function showHelp() {
463 global $wgOut, $ceAllowConfirmedEmail;
464 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
465 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
470 } # End invocation guard