3 class ConfirmEditHooks {
4 static function getInstance() {
5 global $wgCaptcha, $wgCaptchaClass, $wgExtensionMessagesFiles;
9 wfLoadExtensionMessages( 'ConfirmEdit' );
10 if ( isset( $wgExtensionMessagesFiles[$wgCaptchaClass] ) ) {
11 wfLoadExtensionMessages( $wgCaptchaClass );
13 $wgCaptcha = new $wgCaptchaClass;
18 static function confirmEdit( &$editPage, $newtext, $section ) {
19 return self::getInstance()->confirmEdit( $editPage, $newtext, $section );
22 static function confirmEditMerged( &$editPage, $newtext ) {
23 return self::getInstance()->confirmEditMerged( $editPage, $newtext );
26 static function injectUserCreate( &$template ) {
27 return self::getInstance()->injectUserCreate( $template );
30 static function confirmUserCreate( $u, &$message ) {
31 return self::getInstance()->confirmUserCreate( $u, $message );
34 static function triggerUserLogin( $user, $password, $retval ) {
35 return self::getInstance()->triggerUserLogin( $user, $password, $retval );
38 static function injectUserLogin( &$template ) {
39 return self::getInstance()->injectUserLogin( $template );
42 static function confirmUserLogin( $u, $pass, &$retval ) {
43 return self::getInstance()->confirmUserLogin( $u, $pass, $retval );
47 class CaptchaSpecialPage extends UnlistedSpecialPage {
48 function execute( $par ) {
50 $instance = ConfirmEditHooks::getInstance();
53 return $instance->showImage();
56 return $instance->showHelp();
63 function SimpleCaptcha() {
64 global $wgCaptchaStorageClass;
65 $this->storage = new $wgCaptchaStorageClass;
69 * Insert a captcha prompt into the edit form.
70 * This sample implementation generates a simple arithmetic operation;
71 * it would be easy to defeat by machine.
80 $op = mt_rand(0, 1) ? '+' : '-';
83 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
85 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
87 return "<p><label for=\"wpCaptchaWord\">$test</label> = " .
88 wfElement( 'input', array(
89 'name' => 'wpCaptchaWord',
90 'id' => 'wpCaptchaWord',
91 'tabindex' => 1 ) ) . // tab in before the edit textarea
93 wfElement( 'input', array(
95 'name' => 'wpCaptchaId',
96 'id' => 'wpCaptchaId',
97 'value' => $index ) );
101 * Insert the captcha prompt into an edit form.
102 * @param OutputPage $out
104 function editCallback( &$out ) {
105 $out->addWikiText( $this->getMessage( $this->action ) );
106 $out->addHTML( $this->getForm() );
110 * Show a message asking the user to enter a captcha on edit
111 * The result will be treated as wiki text
113 * @param $action Action being performed
116 function getMessage( $action ) {
117 $name = 'captcha-' . $action;
118 $text = wfMsg( $name );
119 # Obtain a more tailored message, if possible, otherwise, fall back to
120 # the default for edits
121 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
126 * @fixme if multiple thingies insert a header, could break
127 * @param SimpleTemplate $template
128 * @return bool true to keep running callbacks
130 function injectUserCreate( &$template ) {
131 global $wgCaptchaTriggers, $wgOut;
132 if( $wgCaptchaTriggers['createaccount'] ) {
133 $template->set( 'header',
134 "<div class='captcha'>" .
135 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
143 * Inject a captcha into the user login form after a failed
144 * password attempt as a speedbump for mass attacks.
145 * @fixme if multiple thingies insert a header, could break
146 * @param SimpleTemplate $template
147 * @return bool true to keep running callbacks
149 function injectUserLogin( &$template ) {
150 if( $this->isBadLoginTriggered() ) {
152 $template->set( 'header',
153 "<div class='captcha'>" .
154 $wgOut->parse( $this->getMessage( 'badlogin' ) ) .
162 * When a bad login attempt is made, increment an expiring counter
163 * in the memcache cloud. Later checks for this may trigger a
164 * captcha display to prevent too many hits from the same place.
166 * @param string $password
167 * @param int $retval authentication return value
168 * @return bool true to keep running callbacks
170 function triggerUserLogin( $user, $password, $retval ) {
171 global $wgCaptchaTriggers, $wgCaptchaBadLoginExpiration, $wgMemc;
172 if( $retval == LoginForm::WRONG_PASS && $wgCaptchaTriggers['badlogin'] ) {
173 $key = $this->badLoginKey();
174 $count = $wgMemc->get( $key );
176 $wgMemc->add( $key, 0, $wgCaptchaBadLoginExpiration );
178 $count = $wgMemc->incr( $key );
184 * Check if a bad login has already been registered for this
185 * IP address. If so, require a captcha.
189 function isBadLoginTriggered() {
191 return intval( $wgMemc->get( $this->badLoginKey() ) ) > 0;
195 * Internal cache key for badlogin checks.
199 function badLoginKey() {
200 return wfMemcKey( 'captcha', 'badlogin', 'ip', wfGetIP() );
204 * Check if the submitted form matches the captcha session data provided
205 * by the plugin when the form was generated.
209 * @param WebRequest $request
213 function keyMatch( $request, $info ) {
214 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
217 // ----------------------------------
220 * @param EditPage $editPage
221 * @param string $action (edit/create/addurl...)
222 * @return bool true if action triggers captcha on editPage's namespace
224 function captchaTriggers( &$editPage, $action) {
225 global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
226 //Special config for this NS?
227 if (isset( $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action] ) )
228 return $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action];
230 return ( !empty( $wgCaptchaTriggers[$action] ) ); //Default
235 * @param EditPage $editPage
236 * @param string $newtext
237 * @param string $section
238 * @return bool true if the captcha should run
240 function shouldCheck( &$editPage, $newtext, $section, $merged = false ) {
242 $title = $editPage->mArticle->getTitle();
245 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
246 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
249 global $wgCaptchaWhitelistIP;
250 if( !empty( $wgCaptchaWhitelistIP ) ) {
252 foreach ( $wgCaptchaWhitelistIP as $range ) {
253 if ( IP::isInRange( $ip, $range ) ) {
260 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
261 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
262 $wgUser->isEmailConfirmed() ) {
263 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
267 if( $this->captchaTriggers( $editPage, 'edit' ) ) {
268 // Check on all edits
270 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
272 $title->getPrefixedText() );
273 $this->action = 'edit';
274 wfDebug( "ConfirmEdit: checking all edits...\n" );
278 if( $this->captchaTriggers( $editPage, 'create' ) && !$editPage->mTitle->exists() ) {
279 //Check if creating a page
281 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
283 $title->getPrefixedText() );
284 $this->action = 'create';
285 wfDebug( "ConfirmEdit: checking on page creation...\n" );
289 if( $this->captchaTriggers( $editPage, 'addurl' ) ) {
290 // Only check edits that add URLs
292 // Get links from the database
293 $oldLinks = $this->getLinksFromTracker( $title );
294 // Share a parse operation with Article::doEdit()
295 $editInfo = $editPage->mArticle->prepareTextForEdit( $newtext );
296 $newLinks = array_keys( $editInfo->output->getExternalLinks() );
298 // Get link changes in the slowest way known to man
299 $oldtext = $this->loadText( $editPage, $section );
300 $oldLinks = $this->findLinks( $oldtext );
301 $newLinks = $this->findLinks( $newtext );
304 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
305 $addedLinks = array_diff( $unknownLinks, $oldLinks );
306 $numLinks = count( $addedLinks );
308 if( $numLinks > 0 ) {
310 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
313 $title->getPrefixedText(),
314 implode( ", ", $addedLinks ) );
315 $this->action = 'addurl';
320 global $wgCaptchaRegexes;
321 if( !empty( $wgCaptchaRegexes ) ) {
322 // Custom regex checks
323 $oldtext = $this->loadText( $editPage, $section );
325 foreach( $wgCaptchaRegexes as $regex ) {
326 $newMatches = array();
327 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
328 $oldMatches = array();
329 preg_match_all( $regex, $oldtext, $oldMatches );
331 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
333 $numHits = count( $addedMatches );
336 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
340 $title->getPrefixedText(),
341 implode( ", ", $addedMatches ) );
342 $this->action = 'edit';
353 * Filter callback function for URL whitelisting
354 * @param string url to check
355 * @return bool true if unknown, false if whitelisted
358 function filterLink( $url ) {
359 global $wgCaptchaWhitelist;
360 $source = wfMsgForContent( 'captcha-addurl-whitelist' );
362 $whitelist = wfEmptyMsg( 'captcha-addurl-whitelist', $source )
364 : $this->buildRegexes( explode( "\n", $source ) );
366 $cwl = $wgCaptchaWhitelist !== false ? preg_match( $wgCaptchaWhitelist, $url ) : false;
367 $wl = $whitelist !== false ? preg_match( $whitelist, $url ) : false;
369 return !( $cwl || $wl );
373 * Build regex from whitelist
374 * @param string lines from [[MediaWiki:Captcha-addurl-whitelist]]
375 * @return string Regex or bool false if whitelist is empty
378 function buildRegexes( $lines ) {
379 # Code duplicated from the SpamBlacklist extension (r19197)
381 # Strip comments and whitespace, then remove blanks
382 $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
384 # No lines, don't make a regex which will match everything
385 if ( count( $lines ) == 0 ) {
386 wfDebug( "No lines\n" );
390 # It's faster using the S modifier even though it will usually only be run once
391 //$regex = 'http://+[a-z0-9_\-.]*(' . implode( '|', $lines ) . ')';
392 //return '/' . str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $regex) ) . '/Si';
394 $regexStart = '/http:\/\/+[a-z0-9_\-.]*(';
398 foreach( $lines as $line ) {
399 // FIXME: not very robust size check, but should work. :)
400 if( $build === false ) {
402 } elseif( strlen( $build ) + strlen( $line ) > $regexMax ) {
403 $regexes .= $regexStart .
404 str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $build) ) .
408 $build .= '|' . $line;
411 if( $build !== false ) {
412 $regexes .= $regexStart .
413 str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $build) ) .
421 * Load external links from the externallinks table
423 function getLinksFromTracker( $title ) {
424 $dbr =& wfGetDB( DB_SLAVE );
425 $id = $title->getArticleId(); // should be zero queries
426 $res = $dbr->select( 'externallinks', array( 'el_to' ),
427 array( 'el_from' => $id ), __METHOD__ );
429 while ( $row = $dbr->fetchObject( $res ) ) {
430 $links[] = $row->el_to;
436 * The main callback run on edit attempts.
437 * @param EditPage $editPage
438 * @param string $newtext
439 * @param string $section
440 * @param bool true to continue saving, false to abort and show a captcha form
442 function confirmEdit( &$editPage, $newtext, $section, $merged = false ) {
443 if( $this->shouldCheck( $editPage, $newtext, $section, $merged ) ) {
444 if( $this->passCaptcha() ) {
447 $editPage->showEditForm( array( &$this, 'editCallback' ) );
451 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
457 * A more efficient edit filter callback based on the text after section merging
458 * @param EditPage $editPage
459 * @param string $newtext
461 function confirmEditMerged( &$editPage, $newtext ) {
462 return $this->confirmEdit( $editPage, $newtext, false, true );
466 * Hook for user creation form submissions.
468 * @param string $message
469 * @return bool true to continue, false to abort user creation
471 function confirmUserCreate( $u, &$message ) {
472 global $wgCaptchaTriggers;
473 if( $wgCaptchaTriggers['createaccount'] ) {
474 $this->trigger = "new account '" . $u->getName() . "'";
475 if( !$this->passCaptcha() ) {
476 $message = wfMsg( 'captcha-createaccount-fail' );
484 * Hook for user login form submissions.
486 * @param string $message
487 * @return bool true to continue, false to abort user creation
489 function confirmUserLogin( $u, $pass, &$retval ) {
490 if( $this->isBadLoginTriggered() ) {
491 $this->trigger = "post-badlogin login '" . $u->getName() . "'";
492 if( !$this->passCaptcha() ) {
493 $message = wfMsg( 'captcha-badlogin-fail' );
494 // Emulate a bad-password return to confuse the shit out of attackers
495 $retval = LoginForm::WRONG_PASS;
503 * Given a required captcha run, test form input for correct
504 * input on the open session.
505 * @return bool if passed, false if failed or new session
507 function passCaptcha() {
508 $info = $this->retrieveCaptcha();
511 if( $this->keyMatch( $wgRequest, $info ) ) {
512 $this->log( "passed" );
513 $this->clearCaptcha( $info );
516 $this->clearCaptcha( $info );
517 $this->log( "bad form input" );
521 $this->log( "new captcha session" );
527 * Log the status and any triggering info for debugging or statistics
528 * @param string $message
530 function log( $message ) {
531 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
535 * Generate a captcha session ID and save the info in PHP's session storage.
536 * (Requires the user to have cookies enabled to get through the captcha.)
538 * A random ID is used so legit users can make edits in multiple tabs or
539 * windows without being unnecessarily hobbled by a serial order requirement.
540 * Pass the returned id value into the edit form as wpCaptchaId.
542 * @param array $info data to store
543 * @return string captcha ID key
545 function storeCaptcha( $info ) {
546 if( !isset( $info['index'] ) ) {
547 // Assign random index if we're not udpating
548 $info['index'] = strval( mt_rand() );
550 $this->storage->store( $info['index'], $info );
551 return $info['index'];
555 * Fetch this session's captcha info.
556 * @return mixed array of info, or false if missing
558 function retrieveCaptcha() {
560 $index = $wgRequest->getVal( 'wpCaptchaId' );
561 return $this->storage->retrieve( $index );
565 * Clear out existing captcha info from the session, to ensure
566 * it can't be reused.
568 function clearCaptcha( $info ) {
569 $this->storage->clear( $info['index'] );
573 * Retrieve the current version of the page or section being edited...
574 * @param EditPage $editPage
575 * @param string $section
579 function loadText( $editPage, $section ) {
580 $rev = Revision::newFromTitle( $editPage->mTitle );
581 if( is_null( $rev ) ) {
584 $text = $rev->getText();
585 if( $section != '' ) {
586 return Article::getSection( $text, $section );
594 * Extract a list of all recognized HTTP links in the text.
595 * @param string $text
596 * @return array of strings
598 function findLinks( $text ) {
599 global $wgParser, $wgTitle, $wgUser;
601 $options = new ParserOptions();
602 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
603 $out = $wgParser->parse( $text, $wgTitle, $options );
605 return array_keys( $out->getExternalLinks() );
609 * Show a page explaining what this wacky thing is.
611 function showHelp() {
612 global $wgOut, $ceAllowConfirmedEmail;
613 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
614 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
615 if ( $this->storage->cookiesNeeded() ) {
616 $wgOut->addWikiText( wfMsg( 'captchahelp-cookies-needed' ) );
622 class CaptchaSessionStore {
623 function store( $index, $info ) {
624 $_SESSION['captcha' . $info['index']] = $info;
627 function retrieve( $index ) {
628 if( isset( $_SESSION['captcha' . $index] ) ) {
629 return $_SESSION['captcha' . $index];
635 function clear( $index ) {
636 unset( $_SESSION['captcha' . $index] );
639 function cookiesNeeded() {
644 class CaptchaCacheStore {
645 function store( $index, $info ) {
646 global $wgMemc, $wgCaptchaSessionExpiration;
647 $wgMemc->set( wfMemcKey( 'captcha', $index ), $info,
648 $wgCaptchaSessionExpiration );
651 function retrieve( $index ) {
653 $info = $wgMemc->get( wfMemcKey( 'captcha', $index ) );
661 function clear( $index ) {
663 $wgMemc->delete( wfMemcKey( 'captcha', $index ) );
666 function cookiesNeeded() {