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';
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 * Currently the captcha works only for page edits.
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 $wgCaptchaTriggers = array();
75 $wgCaptchaTriggers['edit'] = false; // Would check on every edit
76 $wgCaptchaTriggers['addurl'] = true; // Check on edits that add URLs
77 $wgCaptchaTriggers['createaccount'] = true; // Special:Userlogin&type=signup
81 * Allow users who have confirmed their e-mail addresses to post
82 * URL links without being harassed by the captcha.
84 global $ceAllowConfirmedEmail;
85 $ceAllowConfirmedEmail = false;
88 * Regex to whitelist URLs to known-good sites...
90 * $wgCaptchaWhitelist = '#^https?://([a-z0-9-]+\\.)?(wikimedia|wikipedia)\.org/#i';
91 * @fixme Use the 'spam-whitelist' thingy instead?
93 $wgCaptchaWhitelist = false;
96 * Additional regexes to check for. Use full regexes; can match things
97 * other than URLs such as junk edits.
99 * If the new version matches one and the old version doesn't,
100 * toss up the captcha screen.
102 * @fixme Add a message for local admins to add items as well.
104 $wgCaptchaRegexes = array();
106 /** Register special page */
107 global $wgSpecialPages;
108 $wgSpecialPages['Captcha'] = array( /*class*/ 'SpecialPage', /*name*/'Captcha', /*restriction*/ '',
109 /*listed*/ false, /*function*/ false, /*file*/ false );
112 * Set up message strings for captcha utilities.
116 global $wgMessageCache, $wgConfirmEditMessages;
117 foreach( $wgConfirmEditMessages as $lang => $messages )
118 $wgMessageCache->addMessages( $messages, $lang );
120 global $wgHooks, $wgCaptcha, $wgCaptchaClass, $wgSpecialPages;
121 $wgCaptcha = new $wgCaptchaClass();
122 $wgHooks['EditFilter'][] = array( &$wgCaptcha, 'confirmEdit' );
124 $wgHooks['UserCreateForm'][] = array( &$wgCaptcha, 'injectUserCreate' );
125 $wgHooks['AbortNewAccount'][] = array( &$wgCaptcha, 'confirmUserCreate' );
129 * Entry point for Special:Captcha
131 function wfSpecialCaptcha( $par = null ) {
135 return $wgCaptcha->showImage();
138 return $wgCaptcha->showHelp();
142 class SimpleCaptcha {
144 * Insert a captcha prompt into the edit form.
145 * This sample implementation generates a simple arithmetic operation;
146 * it would be easy to defeat by machine.
150 * @return string HTML
153 $a = mt_rand(0, 100);
155 $op = mt_rand(0, 1) ? '+' : '-';
158 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
160 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
162 return "<p><label for=\"wpCaptchaWord\">$test</label> = " .
163 wfElement( 'input', array(
164 'name' => 'wpCaptchaWord',
165 'id' => 'wpCaptchaWord',
166 'tabindex' => 1 ) ) . // tab in before the edit textarea
168 wfElement( 'input', array(
170 'name' => 'wpCaptchaId',
171 'id' => 'wpCaptchaId',
172 'value' => $index ) );
176 * Insert the captcha prompt into an edit form.
177 * @param OutputPage $out
179 function editCallback( &$out ) {
180 $out->addWikiText( $this->getMessage( 'edit' ) );
181 $out->addHTML( $this->getForm() );
185 * Show a message asking the user to enter a captcha on edit
186 * The result will be treated as wiki text
188 * @param $action Action being performed
191 function getMessage( $action ) {
192 $name = 'captcha-' . $action;
193 $text = wfMsg( $name );
194 # Obtain a more tailored message, if possible, otherwise, fall back to
195 # the default for edits
196 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
201 * @fixme if multiple thingies insert a header, could break
202 * @param SimpleTemplate $template
203 * @return bool true to keep running callbacks
205 function injectUserCreate( &$template ) {
206 global $wgCaptchaTriggers, $wgOut;
207 if( $wgCaptchaTriggers['createaccount'] ) {
208 $template->set( 'header',
209 "<div class='captcha'>" .
210 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
218 * Check if the submitted form matches the captcha session data provided
219 * by the plugin when the form was generated.
223 * @param WebRequest $request
227 function keyMatch( $request, $info ) {
228 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
231 // ----------------------------------
234 * @param EditPage $editPage
235 * @param string $newtext
236 * @param string $section
237 * @return bool true if the captcha should run
239 function shouldCheck( &$editPage, $newtext, $section ) {
243 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
244 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
248 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
249 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
250 $wgUser->isEmailConfirmed() ) {
251 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
255 global $wgCaptchaTriggers;
256 if( !empty( $wgCaptchaTriggers['edit'] ) ) {
257 // Check on all edits
258 global $wgUser, $wgTitle;
259 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
261 $wgTitle->getPrefixedText() );
262 wfDebug( "ConfirmEdit: checking all edits...\n" );
266 if( !empty( $wgCaptchaTriggers['addurl'] ) ) {
267 // Only check edits that add URLs
268 $oldtext = $this->loadText( $editPage, $section );
270 $oldLinks = $this->findLinks( $oldtext );
271 $newLinks = $this->findLinks( $newtext );
272 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
274 $addedLinks = array_diff( $unknownLinks, $oldLinks );
275 $numLinks = count( $addedLinks );
277 if( $numLinks > 0 ) {
278 global $wgUser, $wgTitle;
279 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
282 $wgTitle->getPrefixedText(),
283 implode( ", ", $addedLinks ) );
288 global $wgCaptchaRegexes;
289 if( !empty( $wgCaptchaRegexes ) ) {
290 // Custom regex checks
291 $oldtext = $this->loadText( $editPage, $section );
293 foreach( $wgCaptchaRegexes as $regex ) {
294 $newMatches = array();
295 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
296 $oldMatches = array();
297 preg_match_all( $regex, $oldtext, $oldMatches );
299 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
301 $numHits = count( $addedMatches );
303 global $wgUser, $wgTitle;
304 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
308 $wgTitle->getPrefixedText(),
309 implode( ", ", $addedMatches ) );
320 * Filter callback function for URL whitelisting
321 * @return bool true if unknown, false if whitelisted
324 function filterLink( $url ) {
325 global $wgCaptchaWhitelist;
326 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
330 * The main callback run on edit attempts.
331 * @param EditPage $editPage
332 * @param string $newtext
333 * @param string $section
334 * @param bool true to continue saving, false to abort and show a captcha form
336 function confirmEdit( &$editPage, $newtext, $section ) {
337 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
338 if( $this->passCaptcha() ) {
341 $editPage->showEditForm( array( &$this, 'editCallback' ) );
345 wfDebug( "ConfirmEdit: no new links.\n" );
351 * Hook for user creation form submissions.
353 * @param string $message
354 * @return bool true to continue, false to abort user creation
356 function confirmUserCreate( $u, &$message ) {
357 global $wgCaptchaTriggers;
358 if( $wgCaptchaTriggers['createaccount'] ) {
359 $this->trigger = "new account '" . $u->getName() . "'";
360 if( !$this->passCaptcha() ) {
361 $message = wfMsg( 'captcha-createaccount-fail' );
369 * Given a required captcha run, test form input for correct
370 * input on the open session.
371 * @return bool if passed, false if failed or new session
373 function passCaptcha() {
374 $info = $this->retrieveCaptcha();
377 if( $this->keyMatch( $wgRequest, $info ) ) {
378 $this->log( "passed" );
379 $this->clearCaptcha( $info );
382 $this->clearCaptcha( $info );
383 $this->log( "bad form input" );
387 $this->log( "new captcha session" );
393 * Log the status and any triggering info for debugging or statistics
394 * @param string $message
396 function log( $message ) {
397 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
401 * Generate a captcha session ID and save the info in PHP's session storage.
402 * (Requires the user to have cookies enabled to get through the captcha.)
404 * A random ID is used so legit users can make edits in multiple tabs or
405 * windows without being unnecessarily hobbled by a serial order requirement.
406 * Pass the returned id value into the edit form as wpCaptchaId.
408 * @param array $info data to store
409 * @return string captcha ID key
411 function storeCaptcha( $info ) {
412 if( !isset( $info['index'] ) ) {
413 // Assign random index if we're not udpating
414 $info['index'] = strval( mt_rand() );
416 $_SESSION['captcha' . $info['index']] = $info;
417 return $info['index'];
421 * Fetch this session's captcha info.
422 * @return mixed array of info, or false if missing
424 function retrieveCaptcha() {
426 $index = $wgRequest->getVal( 'wpCaptchaId' );
427 if( isset( $_SESSION['captcha' . $index] ) ) {
428 return $_SESSION['captcha' . $index];
435 * Clear out existing captcha info from the session, to ensure
436 * it can't be reused.
438 function clearCaptcha( $info ) {
439 unset( $_SESSION['captcha' . $info['index']] );
443 * Retrieve the current version of the page or section being edited...
444 * @param EditPage $editPage
445 * @param string $section
449 function loadText( $editPage, $section ) {
450 $rev = Revision::newFromTitle( $editPage->mTitle );
451 if( is_null( $rev ) ) {
454 $text = $rev->getText();
455 if( $section != '' ) {
456 return Article::getSection( $text, $section );
464 * Extract a list of all recognized HTTP links in the text.
465 * @param string $text
466 * @return array of strings
468 function findLinks( $text ) {
469 global $wgParser, $wgTitle, $wgUser;
471 $options = new ParserOptions();
472 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
473 $out = $wgParser->parse( $text, $wgTitle, $options );
475 return array_keys( $out->getExternalLinks() );
479 * Show a page explaining what this wacky thing is.
481 function showHelp() {
482 global $wgOut, $ceAllowConfirmedEmail;
483 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
484 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
489 } # End invocation guard