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 $key => $value ) {
112 $wgMessageCache->addMessages( $wgConfirmEditMessages[$key], $key );
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( wfMsg( "captcha-short" ) );
176 $out->addHTML( $this->getForm() );
181 * @fixme if multiple thingies insert a header, could break
182 * @param SimpleTemplate $template
183 * @return bool true to keep running callbacks
185 function injectUserCreate( &$template ) {
186 global $wgCaptchaTriggers, $wgOut;
187 if( $wgCaptchaTriggers['createaccount'] ) {
188 $template->set( 'header',
189 "<div class='captcha'>" .
190 $wgOut->parse( wfMsg( 'captcha-createaccount' ) ) .
198 * Check if the submitted form matches the captcha session data provided
199 * by the plugin when the form was generated.
203 * @param WebRequest $request
207 function keyMatch( $request, $info ) {
208 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
211 // ----------------------------------
214 * @param EditPage $editPage
215 * @param string $newtext
216 * @param string $section
217 * @return bool true if the captcha should run
219 function shouldCheck( &$editPage, $newtext, $section ) {
223 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
224 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
228 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
229 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
230 $wgUser->isEmailConfirmed() ) {
231 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
235 global $wgCaptchaTriggers;
236 if( !empty( $wgCaptchaTriggers['edit'] ) ) {
237 // Check on all edits
238 global $wgUser, $wgTitle;
239 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
241 $wgTitle->getPrefixedText() );
242 wfDebug( "ConfirmEdit: checking all edits...\n" );
246 if( !empty( $wgCaptchaTriggers['addurl'] ) ) {
247 // Only check edits that add URLs
248 $oldtext = $this->loadText( $editPage, $section );
250 $oldLinks = $this->findLinks( $oldtext );
251 $newLinks = $this->findLinks( $newtext );
252 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
254 $addedLinks = array_diff( $unknownLinks, $oldLinks );
255 $numLinks = count( $addedLinks );
257 if( $numLinks > 0 ) {
258 global $wgUser, $wgTitle;
259 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
262 $wgTitle->getPrefixedText(),
263 implode( ", ", $addedLinks ) );
268 global $wgCaptchaRegexes;
269 if( !empty( $wgCaptchaRegexes ) ) {
270 // Custom regex checks
271 $oldtext = $this->loadText( $editPage, $section );
273 foreach( $wgCaptchaRegexes as $regex ) {
274 $newMatches = array();
275 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
276 $oldMatches = array();
277 preg_match_all( $regex, $oldtext, $oldMatches );
279 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
281 $numHits = count( $addedMatches );
283 global $wgUser, $wgTitle;
284 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
288 $wgTitle->getPrefixedText(),
289 implode( ", ", $addedMatches ) );
300 * Filter callback function for URL whitelisting
301 * @return bool true if unknown, false if whitelisted
304 function filterLink( $url ) {
305 global $wgCaptchaWhitelist;
306 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
310 * The main callback run on edit attempts.
311 * @param EditPage $editPage
312 * @param string $newtext
313 * @param string $section
314 * @param bool true to continue saving, false to abort and show a captcha form
316 function confirmEdit( &$editPage, $newtext, $section ) {
317 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
318 if( $this->passCaptcha() ) {
321 $editPage->showEditForm( array( &$this, 'editCallback' ) );
325 wfDebug( "ConfirmEdit: no new links.\n" );
331 * Hook for user creation form submissions.
333 * @param string $message
334 * @return bool true to continue, false to abort user creation
336 function confirmUserCreate( $u, &$message ) {
337 global $wgCaptchaTriggers;
338 if( $wgCaptchaTriggers['createaccount'] ) {
339 $this->trigger = "new account '" . $u->getName() . "'";
340 if( !$this->passCaptcha() ) {
341 $message = wfMsg( 'captcha-createaccount-fail' );
349 * Given a required captcha run, test form input for correct
350 * input on the open session.
351 * @return bool if passed, false if failed or new session
353 function passCaptcha() {
354 $info = $this->retrieveCaptcha();
357 if( $this->keyMatch( $wgRequest, $info ) ) {
358 $this->log( "passed" );
359 $this->clearCaptcha( $info );
362 $this->clearCaptcha( $info );
363 $this->log( "bad form input" );
367 $this->log( "new captcha session" );
373 * Log the status and any triggering info for debugging or statistics
374 * @param string $message
376 function log( $message ) {
377 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
381 * Generate a captcha session ID and save the info in PHP's session storage.
382 * (Requires the user to have cookies enabled to get through the captcha.)
384 * A random ID is used so legit users can make edits in multiple tabs or
385 * windows without being unnecessarily hobbled by a serial order requirement.
386 * Pass the returned id value into the edit form as wpCaptchaId.
388 * @param array $info data to store
389 * @return string captcha ID key
391 function storeCaptcha( $info ) {
392 if( !isset( $info['index'] ) ) {
393 // Assign random index if we're not udpating
394 $info['index'] = strval( mt_rand() );
396 $_SESSION['captcha' . $info['index']] = $info;
397 return $info['index'];
401 * Fetch this session's captcha info.
402 * @return mixed array of info, or false if missing
404 function retrieveCaptcha() {
406 $index = $wgRequest->getVal( 'wpCaptchaId' );
407 if( isset( $_SESSION['captcha' . $index] ) ) {
408 return $_SESSION['captcha' . $index];
415 * Clear out existing captcha info from the session, to ensure
416 * it can't be reused.
418 function clearCaptcha( $info ) {
419 unset( $_SESSION['captcha' . $info['index']] );
423 * Retrieve the current version of the page or section being edited...
424 * @param EditPage $editPage
425 * @param string $section
429 function loadText( $editPage, $section ) {
430 $rev = Revision::newFromTitle( $editPage->mTitle );
431 if( is_null( $rev ) ) {
434 $text = $rev->getText();
435 if( $section != '' ) {
436 return Article::getSection( $text, $section );
444 * Extract a list of all recognized HTTP links in the text.
445 * @param string $text
446 * @return array of strings
448 function findLinks( $text ) {
449 $regex = '/((?:' . HTTP_PROTOCOLS . ')' . EXT_LINK_URL_CLASS . '+)/';
451 if( preg_match_all( $regex, $text, $matches, PREG_PATTERN_ORDER ) ) {
459 * Show a page explaining what this wacky thing is.
461 function showHelp() {
462 global $wgOut, $ceAllowConfirmedEmail;
463 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
464 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
469 } # End invocation guard