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( 'name' => 'ConfirmEdit', 'author' => 'Brion Vibber' );
37 # Internationalisation file
38 require_once( 'ConfirmEdit.i18n.php' );
41 * The 'skipcaptcha' permission key can be given out to
42 * let known-good users perform triggering actions without
43 * having to go through the captcha.
45 * By default, sysops and registered bot accounts will be
46 * able to skip, while others have to go through it.
48 $wgGroupPermissions['*' ]['skipcaptcha'] = false;
49 $wgGroupPermissions['user' ]['skipcaptcha'] = false;
50 $wgGroupPermissions['autoconfirmed']['skipcaptcha'] = false;
51 $wgGroupPermissions['bot' ]['skipcaptcha'] = true; // registered bots
52 $wgGroupPermissions['sysop' ]['skipcaptcha'] = true;
54 global $wgCaptcha, $wgCaptchaClass, $wgCaptchaTriggers;
56 $wgCaptchaClass = 'SimpleCaptcha';
59 * Currently the captcha works only for page edits.
61 * If the 'edit' trigger is on, *every* edit will trigger the captcha.
62 * This may be useful for protecting against vandalbot attacks.
64 * If using the default 'addurl' trigger, the captcha will trigger on
65 * edits that include URLs that aren't in the current version of the page.
66 * This should catch automated linkspammers without annoying people when
67 * they make more typical edits.
69 $wgCaptchaTriggers = array();
70 $wgCaptchaTriggers['edit'] = false; // Would check on every edit
71 $wgCaptchaTriggers['addurl'] = true; // Check on edits that add URLs
72 $wgCaptchaTriggers['createaccount'] = true; // Special:Userlogin&type=signup
76 * Allow users who have confirmed their e-mail addresses to post
77 * URL links without being harassed by the captcha.
79 global $ceAllowConfirmedEmail;
80 $ceAllowConfirmedEmail = false;
83 * Regex to whitelist URLs to known-good sites...
85 * $wgCaptchaWhitelist = '#^https?://([a-z0-9-]+\\.)?(wikimedia|wikipedia)\.org/#i';
86 * @fixme Use the 'spam-whitelist' thingy instead?
88 $wgCaptchaWhitelist = false;
91 * Additional regexes to check for. Use full regexes; can match things
92 * other than URLs such as junk edits.
94 * If the new version matches one and the old version doesn't,
95 * toss up the captcha screen.
97 * @fixme Add a message for local admins to add items as well.
99 $wgCaptchaRegexes = array();
101 /** Register special page */
102 global $wgSpecialPages;
103 $wgSpecialPages['Captcha'] = array( /*class*/ 'SpecialPage', /*name*/'Captcha', /*restriction*/ '',
104 /*listed*/ false, /*function*/ false, /*file*/ false );
107 * Set up message strings for captcha utilities.
111 global $wgMessageCache, $wgConfirmEditMessages;
112 foreach( $wgConfirmEditMessages as $lang => $messages )
113 $wgMessageCache->addMessages( $messages, $lang );
115 global $wgHooks, $wgCaptcha, $wgCaptchaClass, $wgSpecialPages;
116 $wgCaptcha = new $wgCaptchaClass();
117 $wgHooks['EditFilter'][] = array( &$wgCaptcha, 'confirmEdit' );
119 $wgHooks['UserCreateForm'][] = array( &$wgCaptcha, 'injectUserCreate' );
120 $wgHooks['AbortNewAccount'][] = array( &$wgCaptcha, 'confirmUserCreate' );
124 * Entry point for Special:Captcha
126 function wfSpecialCaptcha( $par = null ) {
130 return $wgCaptcha->showImage();
133 return $wgCaptcha->showHelp();
137 class SimpleCaptcha {
139 * Insert a captcha prompt into the edit form.
140 * This sample implementation generates a simple arithmetic operation;
141 * it would be easy to defeat by machine.
145 * @return string HTML
148 $a = mt_rand(0, 100);
150 $op = mt_rand(0, 1) ? '+' : '-';
153 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
155 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
157 return "<p><label for=\"wpCaptchaWord\">$test</label> = " .
158 wfElement( 'input', array(
159 'name' => 'wpCaptchaWord',
160 'id' => 'wpCaptchaWord',
161 'tabindex' => 1 ) ) . // tab in before the edit textarea
163 wfElement( 'input', array(
165 'name' => 'wpCaptchaId',
166 'id' => 'wpCaptchaId',
167 'value' => $index ) );
171 * Insert the captcha prompt into an edit form.
172 * @param OutputPage $out
174 function editCallback( &$out ) {
175 $out->addWikiText( $this->getMessage( 'edit' ) );
176 $out->addHTML( $this->getForm() );
180 * Show a message asking the user to enter a captcha on edit
181 * The result will be treated as wiki text
183 * @param $action Action being performed
186 function getMessage( $action ) {
187 $name = 'captcha-' . $action;
188 $text = wfMsg( $name );
189 # Obtain a more tailored message, if possible, otherwise, fall back to
190 # the default for edits
191 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
196 * @fixme if multiple thingies insert a header, could break
197 * @param SimpleTemplate $template
198 * @return bool true to keep running callbacks
200 function injectUserCreate( &$template ) {
201 global $wgCaptchaTriggers, $wgOut;
202 if( $wgCaptchaTriggers['createaccount'] ) {
203 $template->set( 'header',
204 "<div class='captcha'>" .
205 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
213 * Check if the submitted form matches the captcha session data provided
214 * by the plugin when the form was generated.
218 * @param WebRequest $request
222 function keyMatch( $request, $info ) {
223 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
226 // ----------------------------------
229 * @param EditPage $editPage
230 * @param string $newtext
231 * @param string $section
232 * @return bool true if the captcha should run
234 function shouldCheck( &$editPage, $newtext, $section ) {
238 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
239 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
243 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
244 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
245 $wgUser->isEmailConfirmed() ) {
246 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
250 global $wgCaptchaTriggers;
251 if( !empty( $wgCaptchaTriggers['edit'] ) ) {
252 // Check on all edits
253 global $wgUser, $wgTitle;
254 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
256 $wgTitle->getPrefixedText() );
257 wfDebug( "ConfirmEdit: checking all edits...\n" );
261 if( !empty( $wgCaptchaTriggers['addurl'] ) ) {
262 // Only check edits that add URLs
263 $oldtext = $this->loadText( $editPage, $section );
265 $oldLinks = $this->findLinks( $oldtext );
266 $newLinks = $this->findLinks( $newtext );
267 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
269 $addedLinks = array_diff( $unknownLinks, $oldLinks );
270 $numLinks = count( $addedLinks );
272 if( $numLinks > 0 ) {
273 global $wgUser, $wgTitle;
274 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
277 $wgTitle->getPrefixedText(),
278 implode( ", ", $addedLinks ) );
283 global $wgCaptchaRegexes;
284 if( !empty( $wgCaptchaRegexes ) ) {
285 // Custom regex checks
286 $oldtext = $this->loadText( $editPage, $section );
288 foreach( $wgCaptchaRegexes as $regex ) {
289 $newMatches = array();
290 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
291 $oldMatches = array();
292 preg_match_all( $regex, $oldtext, $oldMatches );
294 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
296 $numHits = count( $addedMatches );
298 global $wgUser, $wgTitle;
299 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
303 $wgTitle->getPrefixedText(),
304 implode( ", ", $addedMatches ) );
315 * Filter callback function for URL whitelisting
316 * @return bool true if unknown, false if whitelisted
319 function filterLink( $url ) {
320 global $wgCaptchaWhitelist;
321 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
325 * The main callback run on edit attempts.
326 * @param EditPage $editPage
327 * @param string $newtext
328 * @param string $section
329 * @param bool true to continue saving, false to abort and show a captcha form
331 function confirmEdit( &$editPage, $newtext, $section ) {
332 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
333 if( $this->passCaptcha() ) {
336 $editPage->showEditForm( array( &$this, 'editCallback' ) );
340 wfDebug( "ConfirmEdit: no new links.\n" );
346 * Hook for user creation form submissions.
348 * @param string $message
349 * @return bool true to continue, false to abort user creation
351 function confirmUserCreate( $u, &$message ) {
352 global $wgCaptchaTriggers;
353 if( $wgCaptchaTriggers['createaccount'] ) {
354 $this->trigger = "new account '" . $u->getName() . "'";
355 if( !$this->passCaptcha() ) {
356 $message = wfMsg( 'captcha-createaccount-fail' );
364 * Given a required captcha run, test form input for correct
365 * input on the open session.
366 * @return bool if passed, false if failed or new session
368 function passCaptcha() {
369 $info = $this->retrieveCaptcha();
372 if( $this->keyMatch( $wgRequest, $info ) ) {
373 $this->log( "passed" );
374 $this->clearCaptcha( $info );
377 $this->clearCaptcha( $info );
378 $this->log( "bad form input" );
382 $this->log( "new captcha session" );
388 * Log the status and any triggering info for debugging or statistics
389 * @param string $message
391 function log( $message ) {
392 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
396 * Generate a captcha session ID and save the info in PHP's session storage.
397 * (Requires the user to have cookies enabled to get through the captcha.)
399 * A random ID is used so legit users can make edits in multiple tabs or
400 * windows without being unnecessarily hobbled by a serial order requirement.
401 * Pass the returned id value into the edit form as wpCaptchaId.
403 * @param array $info data to store
404 * @return string captcha ID key
406 function storeCaptcha( $info ) {
407 if( !isset( $info['index'] ) ) {
408 // Assign random index if we're not udpating
409 $info['index'] = strval( mt_rand() );
411 $_SESSION['captcha' . $info['index']] = $info;
412 return $info['index'];
416 * Fetch this session's captcha info.
417 * @return mixed array of info, or false if missing
419 function retrieveCaptcha() {
421 $index = $wgRequest->getVal( 'wpCaptchaId' );
422 if( isset( $_SESSION['captcha' . $index] ) ) {
423 return $_SESSION['captcha' . $index];
430 * Clear out existing captcha info from the session, to ensure
431 * it can't be reused.
433 function clearCaptcha( $info ) {
434 unset( $_SESSION['captcha' . $info['index']] );
438 * Retrieve the current version of the page or section being edited...
439 * @param EditPage $editPage
440 * @param string $section
444 function loadText( $editPage, $section ) {
445 $rev = Revision::newFromTitle( $editPage->mTitle );
446 if( is_null( $rev ) ) {
449 $text = $rev->getText();
450 if( $section != '' ) {
451 return Article::getSection( $text, $section );
459 * Extract a list of all recognized HTTP links in the text.
460 * @param string $text
461 * @return array of strings
463 function findLinks( $text ) {
464 global $wgParser, $wgTitle, $wgUser;
466 $options = new ParserOptions();
467 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
468 $out = $wgParser->parse( $text, $wgTitle, $options );
470 return array_keys( $out->getExternalLinks() );
474 * Show a page explaining what this wacky thing is.
476 function showHelp() {
477 global $wgOut, $ceAllowConfirmedEmail;
478 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
479 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
484 } # End invocation guard