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 confirmEditAPI( &$editPage, $newtext, &$resultArr ) {
27 return self::getInstance()->confirmEditAPI( $editPage, $newtext, $resultArr );
30 static function injectUserCreate( &$template ) {
31 return self::getInstance()->injectUserCreate( $template );
34 static function confirmUserCreate( $u, &$message ) {
35 return self::getInstance()->confirmUserCreate( $u, $message );
38 static function triggerUserLogin( $user, $password, $retval ) {
39 return self::getInstance()->triggerUserLogin( $user, $password, $retval );
42 static function injectUserLogin( &$template ) {
43 return self::getInstance()->injectUserLogin( $template );
46 static function confirmUserLogin( $u, $pass, &$retval ) {
47 return self::getInstance()->confirmUserLogin( $u, $pass, $retval );
51 class CaptchaSpecialPage extends UnlistedSpecialPage {
52 function execute( $par ) {
54 $instance = ConfirmEditHooks::getInstance();
57 if ( method_exists( $instance, 'showImage' ) )
58 return $instance->showImage();
61 return $instance->showHelp();
67 function SimpleCaptcha() {
68 global $wgCaptchaStorageClass;
69 $this->storage = new $wgCaptchaStorageClass;
72 function getCaptcha() {
73 $a = mt_rand( 0, 100 );
74 $b = mt_rand( 0, 10 );
75 $op = mt_rand( 0, 1 ) ? '+' : '-';
78 $answer = ( $op == '+' ) ? ( $a + $b ) : ( $a - $b );
79 return array( 'question' => $test, 'answer' => $answer );
82 function addCaptchaAPI( &$resultArr ) {
83 $captcha = $this->getCaptcha();
84 $index = $this->storeCaptcha( $captcha );
85 $resultArr['captcha']['type'] = 'simple';
86 $resultArr['captcha']['mime'] = 'text/plain';
87 $resultArr['captcha']['id'] = $index;
88 $resultArr['captcha']['question'] = $captcha['question'];
92 * Insert a captcha prompt into the edit form.
93 * This sample implementation generates a simple arithmetic operation;
94 * it would be easy to defeat by machine.
101 $captcha = $this->getCaptcha();
102 $index = $this->storeCaptcha( $captcha );
104 return "<p><label for=\"wpCaptchaWord\">{$captcha['question']}</label> = " .
105 Xml::element( 'input', array(
106 'name' => 'wpCaptchaWord',
107 'id' => 'wpCaptchaWord',
108 'tabindex' => 1 ) ) . // tab in before the edit textarea
110 Xml::element( 'input', array(
112 'name' => 'wpCaptchaId',
113 'id' => 'wpCaptchaId',
114 'value' => $index ) );
118 * Insert the captcha prompt into an edit form.
119 * @param OutputPage $out
121 function editCallback( &$out ) {
122 $out->addWikiText( $this->getMessage( $this->action ) );
123 $out->addHTML( $this->getForm() );
127 * Show a message asking the user to enter a captcha on edit
128 * The result will be treated as wiki text
130 * @param $action Action being performed
133 function getMessage( $action ) {
134 $name = 'captcha-' . $action;
135 $text = wfMsg( $name );
136 # Obtain a more tailored message, if possible, otherwise, fall back to
137 # the default for edits
138 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
143 * @fixme if multiple thingies insert a header, could break
144 * @param SimpleTemplate $template
145 * @return bool true to keep running callbacks
147 function injectUserCreate( &$template ) {
148 global $wgCaptchaTriggers, $wgOut, $wgUser;
149 if ( $wgCaptchaTriggers['createaccount'] ) {
150 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
151 wfDebug( "ConfirmEdit: user group allows skipping captcha on account creation\n" );
154 $template->set( 'header',
155 "<div class='captcha'>" .
156 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
164 * Inject a captcha into the user login form after a failed
165 * password attempt as a speedbump for mass attacks.
166 * @fixme if multiple thingies insert a header, could break
167 * @param SimpleTemplate $template
168 * @return bool true to keep running callbacks
170 function injectUserLogin( &$template ) {
171 if ( $this->isBadLoginTriggered() ) {
173 $template->set( 'header',
174 "<div class='captcha'>" .
175 $wgOut->parse( $this->getMessage( 'badlogin' ) ) .
183 * When a bad login attempt is made, increment an expiring counter
184 * in the memcache cloud. Later checks for this may trigger a
185 * captcha display to prevent too many hits from the same place.
187 * @param string $password
188 * @param int $retval authentication return value
189 * @return bool true to keep running callbacks
191 function triggerUserLogin( $user, $password, $retval ) {
192 global $wgCaptchaTriggers, $wgCaptchaBadLoginExpiration, $wgMemc;
193 if ( $retval == LoginForm::WRONG_PASS && $wgCaptchaTriggers['badlogin'] ) {
194 $key = $this->badLoginKey();
195 $count = $wgMemc->get( $key );
197 $wgMemc->add( $key, 0, $wgCaptchaBadLoginExpiration );
199 $count = $wgMemc->incr( $key );
205 * Check if a bad login has already been registered for this
206 * IP address. If so, require a captcha.
210 function isBadLoginTriggered() {
211 global $wgMemc, $wgCaptchaBadLoginAttempts;
212 return intval( $wgMemc->get( $this->badLoginKey() ) ) >= $wgCaptchaBadLoginAttempts;
216 * Check if the IP is allowed to skip captchas
218 function isIPWhitelisted() {
219 global $wgCaptchaWhitelistIP;
220 if ( $wgCaptchaWhitelistIP ) {
222 foreach ( $wgCaptchaWhitelistIP as $range ) {
223 if ( IP::isInRange( $ip, $range ) ) {
232 * Internal cache key for badlogin checks.
236 function badLoginKey() {
237 return wfMemcKey( 'captcha', 'badlogin', 'ip', wfGetIP() );
241 * Check if the submitted form matches the captcha session data provided
242 * by the plugin when the form was generated.
246 * @param string $answer
250 function keyMatch( $answer, $info ) {
251 return $answer == $info['answer'];
254 // ----------------------------------
257 * @param EditPage $editPage
258 * @param string $action (edit/create/addurl...)
259 * @return bool true if action triggers captcha on editPage's namespace
261 function captchaTriggers( &$editPage, $action ) {
262 global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
263 // Special config for this NS?
264 if ( isset( $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action] ) )
265 return $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action];
267 return ( !empty( $wgCaptchaTriggers[$action] ) ); // Default
271 * @param EditPage $editPage
272 * @param string $newtext
273 * @param string $section
274 * @return bool true if the captcha should run
276 function shouldCheck( &$editPage, $newtext, $section, $merged = false ) {
278 $title = $editPage->mArticle->getTitle();
281 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
282 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
285 if ( $this->isIPWhitelisted() )
289 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
290 if ( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
291 $wgUser->isEmailConfirmed() ) {
292 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
296 if ( $this->captchaTriggers( $editPage, 'edit' ) ) {
297 // Check on all edits
299 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
301 $title->getPrefixedText() );
302 $this->action = 'edit';
303 wfDebug( "ConfirmEdit: checking all edits...\n" );
307 if ( $this->captchaTriggers( $editPage, 'create' ) && !$editPage->mTitle->exists() ) {
308 // Check if creating a page
310 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
312 $title->getPrefixedText() );
313 $this->action = 'create';
314 wfDebug( "ConfirmEdit: checking on page creation...\n" );
318 if ( $this->captchaTriggers( $editPage, 'addurl' ) ) {
319 // Only check edits that add URLs
321 // Get links from the database
322 $oldLinks = $this->getLinksFromTracker( $title );
323 // Share a parse operation with Article::doEdit()
324 $editInfo = $editPage->mArticle->prepareTextForEdit( $newtext );
325 $newLinks = array_keys( $editInfo->output->getExternalLinks() );
327 // Get link changes in the slowest way known to man
328 $oldtext = $this->loadText( $editPage, $section );
329 $oldLinks = $this->findLinks( $editPage, $oldtext );
330 $newLinks = $this->findLinks( $editPage, $newtext );
333 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
334 $addedLinks = array_diff( $unknownLinks, $oldLinks );
335 $numLinks = count( $addedLinks );
337 if ( $numLinks > 0 ) {
339 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
342 $title->getPrefixedText(),
343 implode( ", ", $addedLinks ) );
344 $this->action = 'addurl';
349 global $wgCaptchaRegexes;
350 if ( $wgCaptchaRegexes ) {
351 // Custom regex checks
352 $oldtext = $this->loadText( $editPage, $section );
354 foreach ( $wgCaptchaRegexes as $regex ) {
355 $newMatches = array();
356 if ( preg_match_all( $regex, $newtext, $newMatches ) ) {
357 $oldMatches = array();
358 preg_match_all( $regex, $oldtext, $oldMatches );
360 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
362 $numHits = count( $addedMatches );
363 if ( $numHits > 0 ) {
365 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
369 $title->getPrefixedText(),
370 implode( ", ", $addedMatches ) );
371 $this->action = 'edit';
382 * Filter callback function for URL whitelisting
383 * @param string url to check
384 * @return bool true if unknown, false if whitelisted
387 function filterLink( $url ) {
388 global $wgCaptchaWhitelist;
389 $source = wfMsgForContent( 'captcha-addurl-whitelist' );
391 $whitelist = wfEmptyMsg( 'captcha-addurl-whitelist', $source )
393 : $this->buildRegexes( explode( "\n", $source ) );
395 $cwl = $wgCaptchaWhitelist !== false ? preg_match( $wgCaptchaWhitelist, $url ) : false;
396 $wl = $whitelist !== false ? preg_match( $whitelist, $url ) : false;
398 return !( $cwl || $wl );
402 * Build regex from whitelist
403 * @param string lines from [[MediaWiki:Captcha-addurl-whitelist]]
404 * @return string Regex or bool false if whitelist is empty
407 function buildRegexes( $lines ) {
408 # Code duplicated from the SpamBlacklist extension (r19197)
410 # Strip comments and whitespace, then remove blanks
411 $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
413 # No lines, don't make a regex which will match everything
414 if ( count( $lines ) == 0 ) {
415 wfDebug( "No lines\n" );
419 # It's faster using the S modifier even though it will usually only be run once
420 // $regex = 'http://+[a-z0-9_\-.]*(' . implode( '|', $lines ) . ')';
421 // return '/' . str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $regex) ) . '/Si';
423 $regexStart = '/^https?:\/\/+[a-z0-9_\-.]*(';
427 foreach ( $lines as $line ) {
428 // FIXME: not very robust size check, but should work. :)
429 if ( $build === false ) {
431 } elseif ( strlen( $build ) + strlen( $line ) > $regexMax ) {
432 $regexes .= $regexStart .
433 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build ) ) .
437 $build .= '|' . $line;
440 if ( $build !== false ) {
441 $regexes .= $regexStart .
442 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build ) ) .
450 * Load external links from the externallinks table
452 function getLinksFromTracker( $title ) {
453 $dbr =& wfGetDB( DB_SLAVE );
454 $id = $title->getArticleId(); // should be zero queries
455 $res = $dbr->select( 'externallinks', array( 'el_to' ),
456 array( 'el_from' => $id ), __METHOD__ );
458 while ( $row = $dbr->fetchObject( $res ) ) {
459 $links[] = $row->el_to;
465 * Backend function for confirmEdit() and confirmEditAPI()
466 * @return bool false if the CAPTCHA is rejected, true otherwise
468 private function doConfirmEdit( $editPage, $newtext, $section, $merged = false ) {
469 if ( $this->shouldCheck( $editPage, $newtext, $section, $merged ) ) {
470 if ( $this->passCaptcha() ) {
476 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
482 * The main callback run on edit attempts.
483 * @param EditPage $editPage
484 * @param string $newtext
485 * @param string $section
486 * @param bool $merged
487 * @return bool true to continue saving, false to abort and show a captcha form
489 function confirmEdit( $editPage, $newtext, $section, $merged = false ) {
490 if ( defined( 'MW_API' ) ) {
492 # The CAPTCHA was already checked and approved
495 if ( !$this->doConfirmEdit( $editPage, $newtext, $section, $merged ) ) {
496 $editPage->showEditForm( array( &$this, 'editCallback' ) );
503 * A more efficient edit filter callback based on the text after section merging
504 * @param EditPage $editPage
505 * @param string $newtext
507 function confirmEditMerged( $editPage, $newtext ) {
508 return $this->confirmEdit( $editPage, $newtext, false, true );
512 function confirmEditAPI( &$editPage, $newtext, &$resultArr ) {
513 if ( !$this->doConfirmEdit( $editPage, $newtext, false, false ) ) {
514 $this->addCaptchaAPI( $resultArr );
521 * Hook for user creation form submissions.
523 * @param string $message
524 * @return bool true to continue, false to abort user creation
526 function confirmUserCreate( $u, &$message ) {
527 global $wgCaptchaTriggers, $wgUser;
528 if ( $wgCaptchaTriggers['createaccount'] ) {
529 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
530 wfDebug( "ConfirmEdit: user group allows skipping captcha on account creation\n" );
533 if ( $this->isIPWhitelisted() )
536 $this->trigger = "new account '" . $u->getName() . "'";
537 if ( !$this->passCaptcha() ) {
538 $message = wfMsg( 'captcha-createaccount-fail' );
546 * Hook for user login form submissions.
548 * @param string $message
549 * @return bool true to continue, false to abort user creation
551 function confirmUserLogin( $u, $pass, &$retval ) {
552 if ( $this->isBadLoginTriggered() ) {
553 if ( $this->isIPWhitelisted() )
556 $this->trigger = "post-badlogin login '" . $u->getName() . "'";
557 if ( !$this->passCaptcha() ) {
558 $message = wfMsg( 'captcha-badlogin-fail' );
559 // Emulate a bad-password return to confuse the shit out of attackers
560 $retval = LoginForm::WRONG_PASS;
568 * Given a required captcha run, test form input for correct
569 * input on the open session.
570 * @return bool if passed, false if failed or new session
572 function passCaptcha() {
573 $info = $this->retrieveCaptcha();
576 if ( $this->keyMatch( $wgRequest->getVal( 'wpCaptchaWord' ), $info ) ) {
577 $this->log( "passed" );
578 $this->clearCaptcha( $info );
581 $this->clearCaptcha( $info );
582 $this->log( "bad form input" );
586 $this->log( "new captcha session" );
592 * Log the status and any triggering info for debugging or statistics
593 * @param string $message
595 function log( $message ) {
596 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
600 * Generate a captcha session ID and save the info in PHP's session storage.
601 * (Requires the user to have cookies enabled to get through the captcha.)
603 * A random ID is used so legit users can make edits in multiple tabs or
604 * windows without being unnecessarily hobbled by a serial order requirement.
605 * Pass the returned id value into the edit form as wpCaptchaId.
607 * @param array $info data to store
608 * @return string captcha ID key
610 function storeCaptcha( $info ) {
611 if ( !isset( $info['index'] ) ) {
612 // Assign random index if we're not udpating
613 $info['index'] = strval( mt_rand() );
615 $this->storage->store( $info['index'], $info );
616 return $info['index'];
620 * Fetch this session's captcha info.
621 * @return mixed array of info, or false if missing
623 function retrieveCaptcha() {
625 $index = $wgRequest->getVal( 'wpCaptchaId' );
626 return $this->storage->retrieve( $index );
630 * Clear out existing captcha info from the session, to ensure
631 * it can't be reused.
633 function clearCaptcha( $info ) {
634 $this->storage->clear( $info['index'] );
638 * Retrieve the current version of the page or section being edited...
639 * @param EditPage $editPage
640 * @param string $section
644 function loadText( $editPage, $section ) {
645 $rev = Revision::newFromTitle( $editPage->mTitle );
646 if ( is_null( $rev ) ) {
649 $text = $rev->getText();
650 if ( $section != '' ) {
651 return Article::getSection( $text, $section );
659 * Extract a list of all recognized HTTP links in the text.
660 * @param string $text
661 * @return array of strings
663 function findLinks( &$editpage, $text ) {
664 global $wgParser, $wgUser;
666 $options = new ParserOptions();
667 $text = $wgParser->preSaveTransform( $text, $editpage->mTitle, $wgUser, $options );
668 $out = $wgParser->parse( $text, $editpage->mTitle, $options );
670 return array_keys( $out->getExternalLinks() );
674 * Show a page explaining what this wacky thing is.
676 function showHelp() {
677 global $wgOut, $ceAllowConfirmedEmail;
678 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
679 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
680 if ( $this->storage->cookiesNeeded() ) {
681 $wgOut->addWikiText( wfMsg( 'captchahelp-cookies-needed' ) );
686 class CaptchaSessionStore {
687 function store( $index, $info ) {
688 $_SESSION['captcha' . $info['index']] = $info;
691 function retrieve( $index ) {
692 if ( isset( $_SESSION['captcha' . $index] ) ) {
693 return $_SESSION['captcha' . $index];
699 function clear( $index ) {
700 unset( $_SESSION['captcha' . $index] );
703 function cookiesNeeded() {
708 class CaptchaCacheStore {
709 function store( $index, $info ) {
710 global $wgMemc, $wgCaptchaSessionExpiration;
711 $wgMemc->set( wfMemcKey( 'captcha', $index ), $info,
712 $wgCaptchaSessionExpiration );
715 function retrieve( $index ) {
717 $info = $wgMemc->get( wfMemcKey( 'captcha', $index ) );
725 function clear( $index ) {
727 $wgMemc->delete( wfMemcKey( 'captcha', $index ) );
730 function cookiesNeeded() {