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() )
287 if ( $editPage->allowBlankSummary )
290 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
291 if ( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
292 $wgUser->isEmailConfirmed() ) {
293 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
297 if ( $this->captchaTriggers( $editPage, 'edit' ) ) {
298 // Check on all edits
300 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
302 $title->getPrefixedText() );
303 $this->action = 'edit';
304 wfDebug( "ConfirmEdit: checking all edits...\n" );
308 if ( $this->captchaTriggers( $editPage, 'create' ) && !$editPage->mTitle->exists() ) {
309 // Check if creating a page
311 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
313 $title->getPrefixedText() );
314 $this->action = 'create';
315 wfDebug( "ConfirmEdit: checking on page creation...\n" );
319 if ( $this->captchaTriggers( $editPage, 'addurl' ) ) {
320 // Only check edits that add URLs
322 // Get links from the database
323 $oldLinks = $this->getLinksFromTracker( $title );
324 // Share a parse operation with Article::doEdit()
325 $editInfo = $editPage->mArticle->prepareTextForEdit( $newtext );
326 $newLinks = array_keys( $editInfo->output->getExternalLinks() );
328 // Get link changes in the slowest way known to man
329 $oldtext = $this->loadText( $editPage, $section );
330 $oldLinks = $this->findLinks( $editPage, $oldtext );
331 $newLinks = $this->findLinks( $editPage, $newtext );
334 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
335 $addedLinks = array_diff( $unknownLinks, $oldLinks );
336 $numLinks = count( $addedLinks );
338 if ( $numLinks > 0 ) {
340 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
343 $title->getPrefixedText(),
344 implode( ", ", $addedLinks ) );
345 $this->action = 'addurl';
350 global $wgCaptchaRegexes;
351 if ( $wgCaptchaRegexes ) {
352 // Custom regex checks
353 $oldtext = $this->loadText( $editPage, $section );
355 foreach ( $wgCaptchaRegexes as $regex ) {
356 $newMatches = array();
357 if ( preg_match_all( $regex, $newtext, $newMatches ) ) {
358 $oldMatches = array();
359 preg_match_all( $regex, $oldtext, $oldMatches );
361 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
363 $numHits = count( $addedMatches );
364 if ( $numHits > 0 ) {
366 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
370 $title->getPrefixedText(),
371 implode( ", ", $addedMatches ) );
372 $this->action = 'edit';
383 * Filter callback function for URL whitelisting
384 * @param string url to check
385 * @return bool true if unknown, false if whitelisted
388 function filterLink( $url ) {
389 global $wgCaptchaWhitelist;
390 $source = wfMsgForContent( 'captcha-addurl-whitelist' );
392 $whitelist = wfEmptyMsg( 'captcha-addurl-whitelist', $source )
394 : $this->buildRegexes( explode( "\n", $source ) );
396 $cwl = $wgCaptchaWhitelist !== false ? preg_match( $wgCaptchaWhitelist, $url ) : false;
397 $wl = $whitelist !== false ? preg_match( $whitelist, $url ) : false;
399 return !( $cwl || $wl );
403 * Build regex from whitelist
404 * @param string lines from [[MediaWiki:Captcha-addurl-whitelist]]
405 * @return string Regex or bool false if whitelist is empty
408 function buildRegexes( $lines ) {
409 # Code duplicated from the SpamBlacklist extension (r19197)
411 # Strip comments and whitespace, then remove blanks
412 $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
414 # No lines, don't make a regex which will match everything
415 if ( count( $lines ) == 0 ) {
416 wfDebug( "No lines\n" );
420 # It's faster using the S modifier even though it will usually only be run once
421 // $regex = 'http://+[a-z0-9_\-.]*(' . implode( '|', $lines ) . ')';
422 // return '/' . str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $regex) ) . '/Si';
424 $regexStart = '/^https?:\/\/+[a-z0-9_\-.]*(';
428 foreach ( $lines as $line ) {
429 // FIXME: not very robust size check, but should work. :)
430 if ( $build === false ) {
432 } elseif ( strlen( $build ) + strlen( $line ) > $regexMax ) {
433 $regexes .= $regexStart .
434 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build ) ) .
438 $build .= '|' . $line;
441 if ( $build !== false ) {
442 $regexes .= $regexStart .
443 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build ) ) .
451 * Load external links from the externallinks table
453 function getLinksFromTracker( $title ) {
454 $dbr =& wfGetDB( DB_SLAVE );
455 $id = $title->getArticleId(); // should be zero queries
456 $res = $dbr->select( 'externallinks', array( 'el_to' ),
457 array( 'el_from' => $id ), __METHOD__ );
459 while ( $row = $dbr->fetchObject( $res ) ) {
460 $links[] = $row->el_to;
466 * Backend function for confirmEdit() and confirmEditAPI()
467 * @return bool false if the CAPTCHA is rejected, true otherwise
469 private function doConfirmEdit( $editPage, $newtext, $section, $merged = false ) {
470 if ( $this->shouldCheck( $editPage, $newtext, $section, $merged ) ) {
471 if ( $this->passCaptcha() ) {
477 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
483 * The main callback run on edit attempts.
484 * @param EditPage $editPage
485 * @param string $newtext
486 * @param string $section
487 * @param bool $merged
488 * @return bool true to continue saving, false to abort and show a captcha form
490 function confirmEdit( $editPage, $newtext, $section, $merged = false ) {
491 if ( defined( 'MW_API' ) ) {
493 # The CAPTCHA was already checked and approved
496 if ( !$this->doConfirmEdit( $editPage, $newtext, $section, $merged ) ) {
497 $editPage->showEditForm( array( &$this, 'editCallback' ) );
504 * A more efficient edit filter callback based on the text after section merging
505 * @param EditPage $editPage
506 * @param string $newtext
508 function confirmEditMerged( $editPage, $newtext ) {
509 return $this->confirmEdit( $editPage, $newtext, false, true );
513 function confirmEditAPI( &$editPage, $newtext, &$resultArr ) {
514 if ( !$this->doConfirmEdit( $editPage, $newtext, false, false ) ) {
515 $this->addCaptchaAPI( $resultArr );
522 * Hook for user creation form submissions.
524 * @param string $message
525 * @return bool true to continue, false to abort user creation
527 function confirmUserCreate( $u, &$message ) {
528 global $wgCaptchaTriggers, $wgUser;
529 if ( $wgCaptchaTriggers['createaccount'] ) {
530 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
531 wfDebug( "ConfirmEdit: user group allows skipping captcha on account creation\n" );
534 if ( $this->isIPWhitelisted() )
537 $this->trigger = "new account '" . $u->getName() . "'";
538 if ( !$this->passCaptcha() ) {
539 $message = wfMsg( 'captcha-createaccount-fail' );
547 * Hook for user login form submissions.
549 * @param string $message
550 * @return bool true to continue, false to abort user creation
552 function confirmUserLogin( $u, $pass, &$retval ) {
553 if ( $this->isBadLoginTriggered() ) {
554 if ( $this->isIPWhitelisted() )
557 $this->trigger = "post-badlogin login '" . $u->getName() . "'";
558 if ( !$this->passCaptcha() ) {
559 $message = wfMsg( 'captcha-badlogin-fail' );
560 // Emulate a bad-password return to confuse the shit out of attackers
561 $retval = LoginForm::WRONG_PASS;
569 * Given a required captcha run, test form input for correct
570 * input on the open session.
571 * @return bool if passed, false if failed or new session
573 function passCaptcha() {
574 $info = $this->retrieveCaptcha();
577 if ( $this->keyMatch( $wgRequest->getVal( 'wpCaptchaWord' ), $info ) ) {
578 $this->log( "passed" );
579 $this->clearCaptcha( $info );
582 $this->clearCaptcha( $info );
583 $this->log( "bad form input" );
587 $this->log( "new captcha session" );
593 * Log the status and any triggering info for debugging or statistics
594 * @param string $message
596 function log( $message ) {
597 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
601 * Generate a captcha session ID and save the info in PHP's session storage.
602 * (Requires the user to have cookies enabled to get through the captcha.)
604 * A random ID is used so legit users can make edits in multiple tabs or
605 * windows without being unnecessarily hobbled by a serial order requirement.
606 * Pass the returned id value into the edit form as wpCaptchaId.
608 * @param array $info data to store
609 * @return string captcha ID key
611 function storeCaptcha( $info ) {
612 if ( !isset( $info['index'] ) ) {
613 // Assign random index if we're not udpating
614 $info['index'] = strval( mt_rand() );
616 $this->storage->store( $info['index'], $info );
617 return $info['index'];
621 * Fetch this session's captcha info.
622 * @return mixed array of info, or false if missing
624 function retrieveCaptcha() {
626 $index = $wgRequest->getVal( 'wpCaptchaId' );
627 return $this->storage->retrieve( $index );
631 * Clear out existing captcha info from the session, to ensure
632 * it can't be reused.
634 function clearCaptcha( $info ) {
635 $this->storage->clear( $info['index'] );
639 * Retrieve the current version of the page or section being edited...
640 * @param EditPage $editPage
641 * @param string $section
645 function loadText( $editPage, $section ) {
646 $rev = Revision::newFromTitle( $editPage->mTitle );
647 if ( is_null( $rev ) ) {
650 $text = $rev->getText();
651 if ( $section != '' ) {
652 return Article::getSection( $text, $section );
660 * Extract a list of all recognized HTTP links in the text.
661 * @param string $text
662 * @return array of strings
664 function findLinks( &$editpage, $text ) {
665 global $wgParser, $wgUser;
667 $options = new ParserOptions();
668 $text = $wgParser->preSaveTransform( $text, $editpage->mTitle, $wgUser, $options );
669 $out = $wgParser->parse( $text, $editpage->mTitle, $options );
671 return array_keys( $out->getExternalLinks() );
675 * Show a page explaining what this wacky thing is.
677 function showHelp() {
678 global $wgOut, $ceAllowConfirmedEmail;
679 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
680 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
681 if ( $this->storage->cookiesNeeded() ) {
682 $wgOut->addWikiText( wfMsg( 'captchahelp-cookies-needed' ) );
687 class CaptchaSessionStore {
688 function store( $index, $info ) {
689 $_SESSION['captcha' . $info['index']] = $info;
692 function retrieve( $index ) {
693 if ( isset( $_SESSION['captcha' . $index] ) ) {
694 return $_SESSION['captcha' . $index];
700 function clear( $index ) {
701 unset( $_SESSION['captcha' . $index] );
704 function cookiesNeeded() {
709 class CaptchaCacheStore {
710 function store( $index, $info ) {
711 global $wgMemc, $wgCaptchaSessionExpiration;
712 $wgMemc->set( wfMemcKey( 'captcha', $index ), $info,
713 $wgCaptchaSessionExpiration );
716 function retrieve( $index ) {
718 $info = $wgMemc->get( wfMemcKey( 'captcha', $index ) );
726 function clear( $index ) {
728 $wgMemc->delete( wfMemcKey( 'captcha', $index ) );
731 function cookiesNeeded() {