5 function getCaptcha() {
6 $a = mt_rand( 0, 100 );
9 /* Minus sign is used in the question. UTF-8,
10 since the api uses text/plain, not text/html */
11 $op = mt_rand( 0, 1 ) ? '+' : '−';
13 // No space before and after $op, to ensure correct
16 $answer = ( $op == '+' ) ? ( $a + $b ) : ( $a - $b );
17 return array( 'question' => $test, 'answer' => $answer );
20 function addCaptchaAPI( &$resultArr ) {
21 $captcha = $this->getCaptcha();
22 $index = $this->storeCaptcha( $captcha );
23 $resultArr['captcha']['type'] = 'simple';
24 $resultArr['captcha']['mime'] = 'text/plain';
25 $resultArr['captcha']['id'] = $index;
26 $resultArr['captcha']['question'] = $captcha['question'];
30 * Insert a captcha prompt into the edit form.
31 * This sample implementation generates a simple arithmetic operation;
32 * it would be easy to defeat by machine.
39 $captcha = $this->getCaptcha();
40 $index = $this->storeCaptcha( $captcha );
42 return "<p><label for=\"wpCaptchaWord\">{$captcha['question']}</label> = " .
43 Xml::element( 'input', array(
44 'name' => 'wpCaptchaWord',
45 'id' => 'wpCaptchaWord',
46 'tabindex' => 1 ) ) . // tab in before the edit textarea
48 Xml::element( 'input', array(
50 'name' => 'wpCaptchaId',
51 'id' => 'wpCaptchaId',
52 'value' => $index ) );
56 * Insert the captcha prompt into an edit form.
57 * @param OutputPage $out
59 function editCallback( &$out ) {
60 $out->addWikiText( $this->getMessage( $this->action ) );
61 $out->addHTML( $this->getForm() );
65 * Show a message asking the user to enter a captcha on edit
66 * The result will be treated as wiki text
68 * @param $action Action being performed
71 function getMessage( $action ) {
72 $name = 'captcha-' . $action;
73 $text = wfMsg( $name );
74 # Obtain a more tailored message, if possible, otherwise, fall back to
75 # the default for edits
76 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
81 * @fixme if multiple thingies insert a header, could break
82 * @param $form HTMLForm
83 * @return bool true to keep running callbacks
85 function injectEmailUser( &$form ) {
86 global $wgCaptchaTriggers, $wgOut, $wgUser;
87 if ( $wgCaptchaTriggers['sendemail'] ) {
88 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
89 wfDebug( "ConfirmEdit: user group allows skipping captcha on email sending\n" );
93 "<div class='captcha'>" .
94 $wgOut->parse( $this->getMessage( 'sendemail' ) ) .
103 * @fixme if multiple thingies insert a header, could break
104 * @param QuickTemplate $template
105 * @return bool true to keep running callbacks
107 function injectUserCreate( &$template ) {
108 global $wgCaptchaTriggers, $wgOut, $wgUser;
109 if ( $wgCaptchaTriggers['createaccount'] ) {
110 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
111 wfDebug( "ConfirmEdit: user group allows skipping captcha on account creation\n" );
114 $template->set( 'header',
115 "<div class='captcha'>" .
116 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
124 * Inject a captcha into the user login form after a failed
125 * password attempt as a speedbump for mass attacks.
126 * @fixme if multiple thingies insert a header, could break
127 * @param $template QuickTemplate
128 * @return bool true to keep running callbacks
130 function injectUserLogin( &$template ) {
131 if ( $this->isBadLoginTriggered() ) {
133 $template->set( 'header',
134 "<div class='captcha'>" .
135 $wgOut->parse( $this->getMessage( 'badlogin' ) ) .
143 * When a bad login attempt is made, increment an expiring counter
144 * in the memcache cloud. Later checks for this may trigger a
145 * captcha display to prevent too many hits from the same place.
147 * @param string $password
148 * @param int $retval authentication return value
149 * @return bool true to keep running callbacks
151 function triggerUserLogin( $user, $password, $retval ) {
152 global $wgCaptchaTriggers, $wgCaptchaBadLoginExpiration, $wgMemc;
153 if ( $retval == LoginForm::WRONG_PASS && $wgCaptchaTriggers['badlogin'] ) {
154 $key = $this->badLoginKey();
155 $count = $wgMemc->get( $key );
157 $wgMemc->add( $key, 0, $wgCaptchaBadLoginExpiration );
159 $count = $wgMemc->incr( $key );
165 * Check if a bad login has already been registered for this
166 * IP address. If so, require a captcha.
170 function isBadLoginTriggered() {
171 global $wgMemc, $wgCaptchaTriggers, $wgCaptchaBadLoginAttempts;
172 return $wgCaptchaTriggers['badlogin'] && intval( $wgMemc->get( $this->badLoginKey() ) ) >= $wgCaptchaBadLoginAttempts;
176 * Check if the IP is allowed to skip captchas
178 function isIPWhitelisted() {
179 global $wgCaptchaWhitelistIP;
181 if ( $wgCaptchaWhitelistIP ) {
184 // Compat: WebRequest::getIP is only available since MW 1.19.
185 $ip = method_exists( $wgRequest, 'getIP' ) ? $wgRequest->getIP() : wfGetIP();
187 foreach ( $wgCaptchaWhitelistIP as $range ) {
188 if ( IP::isInRange( $ip, $range ) ) {
197 * Internal cache key for badlogin checks.
201 function badLoginKey() {
203 // Compat: WebRequest::getIP is only available since MW 1.19.
204 $ip = method_exists( $wgRequest, 'getIP' ) ? $wgRequest->getIP() : wfGetIP();
205 return wfMemcKey( 'captcha', 'badlogin', 'ip', $ip );
209 * Check if the submitted form matches the captcha session data provided
210 * by the plugin when the form was generated.
214 * @param string $answer
218 function keyMatch( $answer, $info ) {
219 return $answer == $info['answer'];
222 // ----------------------------------
225 * @param EditPage $editPage
226 * @param string $action (edit/create/addurl...)
227 * @return bool true if action triggers captcha on editPage's namespace
229 function captchaTriggers( &$editPage, $action ) {
230 global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
231 // Special config for this NS?
232 if ( isset( $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action] ) )
233 return $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action];
235 return ( !empty( $wgCaptchaTriggers[$action] ) ); // Default
239 * @param EditPage $editPage
240 * @param string $newtext
241 * @param string $section
242 * @return bool true if the captcha should run
244 function shouldCheck( &$editPage, $newtext, $section, $merged = false ) {
246 $title = $editPage->mArticle->getTitle();
249 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
250 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
253 if ( $this->isIPWhitelisted() )
257 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
258 if ( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
259 $wgUser->isEmailConfirmed() ) {
260 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
264 if ( $this->captchaTriggers( $editPage, 'edit' ) ) {
265 // Check on all edits
267 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
269 $title->getPrefixedText() );
270 $this->action = 'edit';
271 wfDebug( "ConfirmEdit: checking all edits...\n" );
275 if ( $this->captchaTriggers( $editPage, 'create' ) && !$editPage->mTitle->exists() ) {
276 // Check if creating a page
278 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
280 $title->getPrefixedText() );
281 $this->action = 'create';
282 wfDebug( "ConfirmEdit: checking on page creation...\n" );
286 if ( $this->captchaTriggers( $editPage, 'addurl' ) ) {
287 // Only check edits that add URLs
289 // Get links from the database
290 $oldLinks = $this->getLinksFromTracker( $title );
291 // Share a parse operation with Article::doEdit()
292 $editInfo = $editPage->mArticle->prepareTextForEdit( $newtext );
293 $newLinks = array_keys( $editInfo->output->getExternalLinks() );
295 // Get link changes in the slowest way known to man
296 $oldtext = $this->loadText( $editPage, $section );
297 $oldLinks = $this->findLinks( $editPage, $oldtext );
298 $newLinks = $this->findLinks( $editPage, $newtext );
301 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
302 $addedLinks = array_diff( $unknownLinks, $oldLinks );
303 $numLinks = count( $addedLinks );
305 if ( $numLinks > 0 ) {
307 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
310 $title->getPrefixedText(),
311 implode( ", ", $addedLinks ) );
312 $this->action = 'addurl';
317 global $wgCaptchaRegexes;
318 if ( $wgCaptchaRegexes ) {
319 // Custom regex checks
320 $oldtext = $this->loadText( $editPage, $section );
322 foreach ( $wgCaptchaRegexes as $regex ) {
323 $newMatches = array();
324 if ( preg_match_all( $regex, $newtext, $newMatches ) ) {
325 $oldMatches = array();
326 preg_match_all( $regex, $oldtext, $oldMatches );
328 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
330 $numHits = count( $addedMatches );
331 if ( $numHits > 0 ) {
333 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
337 $title->getPrefixedText(),
338 implode( ", ", $addedMatches ) );
339 $this->action = 'edit';
350 * Filter callback function for URL whitelisting
351 * @param string url to check
352 * @return bool true if unknown, false if whitelisted
355 function filterLink( $url ) {
356 global $wgCaptchaWhitelist;
357 $source = wfMsgForContent( 'captcha-addurl-whitelist' );
359 $whitelist = wfEmptyMsg( 'captcha-addurl-whitelist', $source )
361 : $this->buildRegexes( explode( "\n", $source ) );
363 $cwl = $wgCaptchaWhitelist !== false ? preg_match( $wgCaptchaWhitelist, $url ) : false;
364 $wl = $whitelist !== false ? preg_match( $whitelist, $url ) : false;
366 return !( $cwl || $wl );
370 * Build regex from whitelist
371 * @param string lines from [[MediaWiki:Captcha-addurl-whitelist]]
372 * @return string Regex or bool false if whitelist is empty
375 function buildRegexes( $lines ) {
376 # Code duplicated from the SpamBlacklist extension (r19197)
378 # Strip comments and whitespace, then remove blanks
379 $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
381 # No lines, don't make a regex which will match everything
382 if ( count( $lines ) == 0 ) {
383 wfDebug( "No lines\n" );
387 # It's faster using the S modifier even though it will usually only be run once
388 // $regex = 'http://+[a-z0-9_\-.]*(' . implode( '|', $lines ) . ')';
389 // return '/' . str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $regex) ) . '/Si';
391 $regexStart = '/^https?:\/\/+[a-z0-9_\-.]*(';
395 foreach ( $lines as $line ) {
396 // FIXME: not very robust size check, but should work. :)
397 if ( $build === false ) {
399 } elseif ( strlen( $build ) + strlen( $line ) > $regexMax ) {
400 $regexes .= $regexStart .
401 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build ) ) .
405 $build .= '|' . $line;
408 if ( $build !== false ) {
409 $regexes .= $regexStart .
410 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build ) ) .
418 * Load external links from the externallinks table
419 * @param $title Title
422 function getLinksFromTracker( $title ) {
423 $dbr = wfGetDB( DB_SLAVE );
424 $id = $title->getArticleID(); // should be zero queries
425 $res = $dbr->select( 'externallinks', array( 'el_to' ),
426 array( 'el_from' => $id ), __METHOD__ );
428 foreach ( $res as $row ) {
429 $links[] = $row->el_to;
435 * Backend function for confirmEdit() and confirmEditAPI()
436 * @return bool false if the CAPTCHA is rejected, true otherwise
438 private function doConfirmEdit( $editPage, $newtext, $section, $merged = false ) {
440 if ( $wgRequest->getVal( 'captchaid' ) ) {
441 $wgRequest->setVal( 'wpCaptchaId', $wgRequest->getVal( 'captchaid' ) );
443 if ( $wgRequest->getVal( 'captchaword' ) ) {
444 $wgRequest->setVal( 'wpCaptchaWord', $wgRequest->getVal( 'captchaword' ) );
446 if ( $this->shouldCheck( $editPage, $newtext, $section, $merged ) ) {
447 return $this->passCaptcha();
449 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
455 * The main callback run on edit attempts.
456 * @param EditPage $editPage
457 * @param string $newtext
458 * @param string $section
459 * @param bool $merged
460 * @return bool true to continue saving, false to abort and show a captcha form
462 function confirmEdit( $editPage, $newtext, $section, $merged = false ) {
463 if ( defined( 'MW_API' ) ) {
465 # The CAPTCHA was already checked and approved
468 if ( !$this->doConfirmEdit( $editPage, $newtext, $section, $merged ) ) {
469 $editPage->showEditForm( array( &$this, 'editCallback' ) );
476 * A more efficient edit filter callback based on the text after section merging
477 * @param EditPage $editPage
478 * @param string $newtext
480 function confirmEditMerged( $editPage, $newtext ) {
481 return $this->confirmEdit( $editPage, $newtext, false, true );
484 function confirmEditAPI( $editPage, $newtext, &$resultArr ) {
485 if ( !$this->doConfirmEdit( $editPage, $newtext, false, false ) ) {
486 $this->addCaptchaAPI( $resultArr );
494 * Hook for user creation form submissions.
496 * @param string $message
497 * @return bool true to continue, false to abort user creation
499 function confirmUserCreate( $u, &$message ) {
500 global $wgCaptchaTriggers, $wgUser;
501 if ( $wgCaptchaTriggers['createaccount'] ) {
502 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
503 wfDebug( "ConfirmEdit: user group allows skipping captcha on account creation\n" );
506 if ( $this->isIPWhitelisted() )
509 $this->trigger = "new account '" . $u->getName() . "'";
510 if ( !$this->passCaptcha() ) {
511 $message = wfMsg( 'captcha-createaccount-fail' );
519 * Hook for user login form submissions.
521 * @param string $message
522 * @return bool true to continue, false to abort user creation
524 function confirmUserLogin( $u, $pass, &$retval ) {
525 if ( $this->isBadLoginTriggered() ) {
526 if ( $this->isIPWhitelisted() )
529 $this->trigger = "post-badlogin login '" . $u->getName() . "'";
530 if ( !$this->passCaptcha() ) {
531 // Emulate a bad-password return to confuse the shit out of attackers
532 $retval = LoginForm::WRONG_PASS;
540 * Check the captcha on Special:EmailUser
541 * @param $from MailAddress
542 * @param $to MailAddress
543 * @param $subject String
544 * @param $text String
545 * @param $error String reference
546 * @return Bool true to continue saving, false to abort and show a captcha form
548 function confirmEmailUser( $from, $to, $subject, $text, &$error ) {
549 global $wgCaptchaTriggers, $wgUser;
550 if ( $wgCaptchaTriggers['sendemail'] ) {
551 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
552 wfDebug( "ConfirmEdit: user group allows skipping captcha on email sending\n" );
555 if ( $this->isIPWhitelisted() )
558 if ( defined( 'MW_API' ) ) {
560 # Asking for captchas in the API is really silly
561 $error = wfMsg( 'captcha-disabledinapi' );
564 $this->trigger = "{$wgUser->getName()} sending email";
565 if ( !$this->passCaptcha() ) {
566 $error = wfMsg( 'captcha-sendemail-fail' );
574 * @param $module ApiBase
575 * @param $params array
578 public function APIGetAllowedParams( &$module, &$params ) {
579 if ( !$module instanceof ApiEditPage ) {
582 $params['captchaword'] = null;
583 $params['captchaid'] = null;
589 * @param $module ApiBae
593 public function APIGetParamDescription( &$module, &$desc ) {
594 if ( !$module instanceof ApiEditPage ) {
597 $desc['captchaid'] = 'CAPTCHA ID from previous request';
598 $desc['captchaword'] = 'Answer to the CAPTCHA';
604 * Given a required captcha run, test form input for correct
605 * input on the open session.
606 * @return bool if passed, false if failed or new session
608 function passCaptcha() {
609 $info = $this->retrieveCaptcha();
612 if ( $this->keyMatch( $wgRequest->getVal( 'wpCaptchaWord' ), $info ) ) {
613 $this->log( "passed" );
614 $this->clearCaptcha( $info );
617 $this->clearCaptcha( $info );
618 $this->log( "bad form input" );
622 $this->log( "new captcha session" );
628 * Log the status and any triggering info for debugging or statistics
629 * @param string $message
631 function log( $message ) {
632 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
636 * Generate a captcha session ID and save the info in PHP's session storage.
637 * (Requires the user to have cookies enabled to get through the captcha.)
639 * A random ID is used so legit users can make edits in multiple tabs or
640 * windows without being unnecessarily hobbled by a serial order requirement.
641 * Pass the returned id value into the edit form as wpCaptchaId.
643 * @param array $info data to store
644 * @return string captcha ID key
646 function storeCaptcha( $info ) {
647 if ( !isset( $info['index'] ) ) {
648 // Assign random index if we're not udpating
649 $info['index'] = strval( mt_rand() );
651 CaptchaStore::get()->store( $info['index'], $info );
652 return $info['index'];
656 * Fetch this session's captcha info.
657 * @return mixed array of info, or false if missing
659 function retrieveCaptcha() {
661 $index = $wgRequest->getVal( 'wpCaptchaId' );
662 return CaptchaStore::get()->retrieve( $index );
666 * Clear out existing captcha info from the session, to ensure
667 * it can't be reused.
669 function clearCaptcha( $info ) {
670 CaptchaStore::get()->clear( $info['index'] );
674 * Retrieve the current version of the page or section being edited...
675 * @param EditPage $editPage
676 * @param string $section
680 function loadText( $editPage, $section ) {
681 $rev = Revision::newFromTitle( $editPage->mTitle );
682 if ( is_null( $rev ) ) {
685 $text = $rev->getText();
686 if ( $section != '' ) {
688 return $wgParser->getSection( $text, $section );
696 * Extract a list of all recognized HTTP links in the text.
697 * @param string $text
698 * @return array of strings
700 function findLinks( &$editpage, $text ) {
701 global $wgParser, $wgUser;
703 $options = new ParserOptions();
704 $text = $wgParser->preSaveTransform( $text, $editpage->mTitle, $wgUser, $options );
705 $out = $wgParser->parse( $text, $editpage->mTitle, $options );
707 return array_keys( $out->getExternalLinks() );
711 * Show a page explaining what this wacky thing is.
713 function showHelp() {
715 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
716 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
717 if ( CaptchaStore::get()->cookiesNeeded() ) {
718 $wgOut->addWikiText( wfMsg( 'captchahelp-cookies-needed' ) );