4 function getCaptcha() {
5 $a = mt_rand( 0, 100 );
8 /* Minus sign is used in the question. UTF-8,
9 since the api uses text/plain, not text/html */
10 $op = mt_rand( 0, 1 ) ? '+' : '−';
12 // No space before and after $op, to ensure correct
15 $answer = ( $op == '+' ) ? ( $a + $b ) : ( $a - $b );
16 return array( 'question' => $test, 'answer' => $answer );
19 function addCaptchaAPI( &$resultArr ) {
20 $captcha = $this->getCaptcha();
21 $index = $this->storeCaptcha( $captcha );
22 $resultArr['captcha']['type'] = 'simple';
23 $resultArr['captcha']['mime'] = 'text/plain';
24 $resultArr['captcha']['id'] = $index;
25 $resultArr['captcha']['question'] = $captcha['question'];
29 * Insert a captcha prompt into the edit form.
30 * This sample implementation generates a simple arithmetic operation;
31 * it would be easy to defeat by machine.
38 $captcha = $this->getCaptcha();
39 $index = $this->storeCaptcha( $captcha );
41 return "<p><label for=\"wpCaptchaWord\">{$captcha['question']}</label> = " .
42 Xml::element( 'input', array(
43 'name' => 'wpCaptchaWord',
44 'id' => 'wpCaptchaWord',
45 'tabindex' => 1 ) ) . // tab in before the edit textarea
47 Xml::element( 'input', array(
49 'name' => 'wpCaptchaId',
50 'id' => 'wpCaptchaId',
51 'value' => $index ) );
55 * Insert the captcha prompt into an edit form.
56 * @param OutputPage $out
58 function editCallback( &$out ) {
59 $out->addWikiText( $this->getMessage( $this->action ) );
60 $out->addHTML( $this->getForm() );
64 * Show a message asking the user to enter a captcha on edit
65 * The result will be treated as wiki text
67 * @param $action string Action being performed
70 function getMessage( $action ) {
71 $name = 'captcha-' . $action;
72 $text = wfMessage( $name )->text();
73 # Obtain a more tailored message, if possible, otherwise, fall back to
74 # the default for edits
75 return wfMessage( $name, $text )->isDisabled() ? wfMessage( 'captcha-edit' )->text() : $text;
80 * @fixme if multiple thingies insert a header, could break
81 * @param $form HTMLForm
82 * @return bool true to keep running callbacks
84 function injectEmailUser( &$form ) {
85 global $wgCaptchaTriggers, $wgOut, $wgUser;
86 if ( $wgCaptchaTriggers['sendemail'] ) {
87 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
88 wfDebug( "ConfirmEdit: user group allows skipping captcha on email sending\n" );
92 "<div class='captcha'>" .
93 $wgOut->parse( $this->getMessage( 'sendemail' ) ) .
102 * @fixme if multiple thingies insert a header, could break
103 * @param QuickTemplate $template
104 * @return bool true to keep running callbacks
106 function injectUserCreate( &$template ) {
107 global $wgCaptchaTriggers, $wgOut, $wgUser;
108 if ( $wgCaptchaTriggers['createaccount'] ) {
109 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
110 wfDebug( "ConfirmEdit: user group allows skipping captcha on account creation\n" );
113 $template->set( 'header',
114 "<div class='captcha'>" .
115 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
123 * Inject a captcha into the user login form after a failed
124 * password attempt as a speedbump for mass attacks.
125 * @fixme if multiple thingies insert a header, could break
126 * @param $template QuickTemplate
127 * @return bool true to keep running callbacks
129 function injectUserLogin( &$template ) {
130 if ( $this->isBadLoginTriggered() ) {
132 $template->set( 'header',
133 "<div class='captcha'>" .
134 $wgOut->parse( $this->getMessage( 'badlogin' ) ) .
142 * When a bad login attempt is made, increment an expiring counter
143 * in the memcache cloud. Later checks for this may trigger a
144 * captcha display to prevent too many hits from the same place.
146 * @param string $password
147 * @param int $retval authentication return value
148 * @return bool true to keep running callbacks
150 function triggerUserLogin( $user, $password, $retval ) {
151 global $wgCaptchaTriggers, $wgCaptchaBadLoginExpiration, $wgMemc;
152 if ( $retval == LoginForm::WRONG_PASS && $wgCaptchaTriggers['badlogin'] ) {
153 $key = $this->badLoginKey();
154 $count = $wgMemc->get( $key );
156 $wgMemc->add( $key, 0, $wgCaptchaBadLoginExpiration );
159 $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 $ip = $wgRequest->getIP();
186 foreach ( $wgCaptchaWhitelistIP as $range ) {
187 if ( IP::isInRange( $ip, $range ) ) {
196 * Internal cache key for badlogin checks.
200 function badLoginKey() {
202 $ip = $wgRequest->getIP();
203 return wfMemcKey( 'captcha', 'badlogin', 'ip', $ip );
207 * Check if the submitted form matches the captcha session data provided
208 * by the plugin when the form was generated.
212 * @param string $answer
216 function keyMatch( $answer, $info ) {
217 return $answer == $info['answer'];
220 // ----------------------------------
223 * @param EditPage $editPage
224 * @param string $action (edit/create/addurl...)
225 * @return bool true if action triggers captcha on editPage's namespace
227 function captchaTriggers( &$editPage, $action ) {
228 global $wgCaptchaTriggers, $wgCaptchaTriggersOnNamespace;
229 // Special config for this NS?
230 if ( isset( $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action] ) )
231 return $wgCaptchaTriggersOnNamespace[$editPage->mTitle->getNamespace()][$action];
233 return ( !empty( $wgCaptchaTriggers[$action] ) ); // Default
237 * @param $editPage EditPage
238 * @param $newtext string
239 * @param $section string
240 * @param $merged bool
241 * @return bool true if the captcha should run
243 function shouldCheck( &$editPage, $newtext, $section, $merged = false ) {
245 $title = $editPage->mArticle->getTitle();
248 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
249 wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
252 if ( $this->isIPWhitelisted() )
256 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
257 if ( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
258 $wgUser->isEmailConfirmed() ) {
259 wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
263 if ( $this->captchaTriggers( $editPage, 'edit' ) ) {
264 // Check on all edits
266 $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
268 $title->getPrefixedText() );
269 $this->action = 'edit';
270 wfDebug( "ConfirmEdit: checking all edits...\n" );
274 if ( $this->captchaTriggers( $editPage, 'create' ) && !$editPage->mTitle->exists() ) {
275 // Check if creating a page
277 $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
279 $title->getPrefixedText() );
280 $this->action = 'create';
281 wfDebug( "ConfirmEdit: checking on page creation...\n" );
285 if ( $this->captchaTriggers( $editPage, 'addurl' ) ) {
286 // Only check edits that add URLs
288 // Get links from the database
289 $oldLinks = $this->getLinksFromTracker( $title );
290 // Share a parse operation with Article::doEdit()
291 $editInfo = $editPage->mArticle->prepareTextForEdit( $newtext );
292 $newLinks = array_keys( $editInfo->output->getExternalLinks() );
294 // Get link changes in the slowest way known to man
295 $oldtext = $this->loadText( $editPage, $section );
296 $oldLinks = $this->findLinks( $editPage, $oldtext );
297 $newLinks = $this->findLinks( $editPage, $newtext );
300 $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
301 $addedLinks = array_diff( $unknownLinks, $oldLinks );
302 $numLinks = count( $addedLinks );
304 if ( $numLinks > 0 ) {
306 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
309 $title->getPrefixedText(),
310 implode( ", ", $addedLinks ) );
311 $this->action = 'addurl';
316 global $wgCaptchaRegexes;
317 if ( $wgCaptchaRegexes ) {
318 // Custom regex checks. Reuse $oldtext if set above.
319 $oldtext = isset( $oldtext ) ? $oldtext : $this->loadText( $editPage, $section );
321 foreach ( $wgCaptchaRegexes as $regex ) {
322 $newMatches = array();
323 if ( preg_match_all( $regex, $newtext, $newMatches ) ) {
324 $oldMatches = array();
325 preg_match_all( $regex, $oldtext, $oldMatches );
327 $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
329 $numHits = count( $addedMatches );
330 if ( $numHits > 0 ) {
332 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
336 $title->getPrefixedText(),
337 implode( ", ", $addedMatches ) );
338 $this->action = 'edit';
349 * Filter callback function for URL whitelisting
350 * @param $url string to check
351 * @return bool true if unknown, false if whitelisted
354 function filterLink( $url ) {
355 global $wgCaptchaWhitelist;
356 $source = wfMessage( 'captcha-addurl-whitelist' )->inContentLanguage()->text();
358 $whitelist = wfMessage( 'captcha-addurl-whitelist', $source )->isDisabled()
360 : $this->buildRegexes( explode( "\n", $source ) );
362 $cwl = $wgCaptchaWhitelist !== false ? preg_match( $wgCaptchaWhitelist, $url ) : false;
363 $wl = $whitelist !== false ? preg_match( $whitelist, $url ) : false;
365 return !( $cwl || $wl );
369 * Build regex from whitelist
370 * @param $lines string from [[MediaWiki:Captcha-addurl-whitelist]]
371 * @return string Regex or bool false if whitelist is empty
374 function buildRegexes( $lines ) {
375 # Code duplicated from the SpamBlacklist extension (r19197)
377 # Strip comments and whitespace, then remove blanks
378 $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
380 # No lines, don't make a regex which will match everything
381 if ( count( $lines ) == 0 ) {
382 wfDebug( "No lines\n" );
386 # It's faster using the S modifier even though it will usually only be run once
387 // $regex = 'http://+[a-z0-9_\-.]*(' . implode( '|', $lines ) . ')';
388 // return '/' . str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $regex) ) . '/Si';
390 $regexStart = '/^https?:\/\/+[a-z0-9_\-.]*(';
394 foreach ( $lines as $line ) {
395 // FIXME: not very robust size check, but should work. :)
396 if ( $build === false ) {
398 } elseif ( strlen( $build ) + strlen( $line ) > $regexMax ) {
399 $regexes .= $regexStart .
400 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build ) ) .
404 $build .= '|' . $line;
407 if ( $build !== false ) {
408 $regexes .= $regexStart .
409 str_replace( '/', '\/', preg_replace( '|\\\*/|', '/', $build ) ) .
417 * Load external links from the externallinks table
418 * @param $title Title
421 function getLinksFromTracker( $title ) {
422 $dbr = wfGetDB( DB_SLAVE );
423 $id = $title->getArticleID(); // should be zero queries
424 $res = $dbr->select( 'externallinks', array( 'el_to' ),
425 array( 'el_from' => $id ), __METHOD__ );
427 foreach ( $res as $row ) {
428 $links[] = $row->el_to;
434 * Backend function for confirmEdit() and confirmEditAPI()
435 * @param $editPage EditPage
436 * @param $newtext string
438 * @param $merged bool
439 * @return bool false if the CAPTCHA is rejected, true otherwise
441 private function doConfirmEdit( $editPage, $newtext, $section, $merged = false ) {
443 if ( $wgRequest->getVal( 'captchaid' ) ) {
444 $wgRequest->setVal( 'wpCaptchaId', $wgRequest->getVal( 'captchaid' ) );
446 if ( $wgRequest->getVal( 'captchaword' ) ) {
447 $wgRequest->setVal( 'wpCaptchaWord', $wgRequest->getVal( 'captchaword' ) );
449 if ( $this->shouldCheck( $editPage, $newtext, $section, $merged ) ) {
450 return $this->passCaptcha();
452 wfDebug( "ConfirmEdit: no need to show captcha.\n" );
458 * The main callback run on edit attempts.
459 * @param EditPage $editPage
460 * @param string $newtext
461 * @param string $section
462 * @param bool $merged
463 * @return bool true to continue saving, false to abort and show a captcha form
465 function confirmEdit( $editPage, $newtext, $section, $merged = false ) {
466 if ( defined( 'MW_API' ) ) {
468 # The CAPTCHA was already checked and approved
471 if ( !$this->doConfirmEdit( $editPage, $newtext, $section, $merged ) ) {
472 $editPage->showEditForm( array( &$this, 'editCallback' ) );
479 * A more efficient edit filter callback based on the text after section merging
480 * @param EditPage $editPage
481 * @param string $newtext
484 function confirmEditMerged( $editPage, $newtext ) {
485 return $this->confirmEdit( $editPage, $newtext, false, true );
488 function confirmEditAPI( $editPage, $newtext, &$resultArr ) {
489 if ( !$this->doConfirmEdit( $editPage, $newtext, false, false ) ) {
490 $this->addCaptchaAPI( $resultArr );
498 * Hook for user creation form submissions.
500 * @param string $message
501 * @return bool true to continue, false to abort user creation
503 function confirmUserCreate( $u, &$message ) {
504 global $wgCaptchaTriggers, $wgUser;
505 if ( $wgCaptchaTriggers['createaccount'] ) {
506 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
507 wfDebug( "ConfirmEdit: user group allows skipping captcha on account creation\n" );
510 if ( $this->isIPWhitelisted() )
513 $this->trigger = "new account '" . $u->getName() . "'";
514 if ( !$this->passCaptcha() ) {
515 $message = wfMessage( 'captcha-createaccount-fail' )->text();
523 * Hook for user login form submissions.
527 * @return bool true to continue, false to abort user creation
529 function confirmUserLogin( $u, $pass, &$retval ) {
530 if ( $this->isBadLoginTriggered() ) {
531 if ( $this->isIPWhitelisted() )
534 $this->trigger = "post-badlogin login '" . $u->getName() . "'";
535 if ( !$this->passCaptcha() ) {
536 // Emulate a bad-password return to confuse the shit out of attackers
537 $retval = LoginForm::WRONG_PASS;
545 * Check the captcha on Special:EmailUser
546 * @param $from MailAddress
547 * @param $to MailAddress
548 * @param $subject String
549 * @param $text String
550 * @param $error String reference
551 * @return Bool true to continue saving, false to abort and show a captcha form
553 function confirmEmailUser( $from, $to, $subject, $text, &$error ) {
554 global $wgCaptchaTriggers, $wgUser;
555 if ( $wgCaptchaTriggers['sendemail'] ) {
556 if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
557 wfDebug( "ConfirmEdit: user group allows skipping captcha on email sending\n" );
560 if ( $this->isIPWhitelisted() )
563 if ( defined( 'MW_API' ) ) {
565 # Asking for captchas in the API is really silly
566 $error = wfMessage( 'captcha-disabledinapi' )->text();
569 $this->trigger = "{$wgUser->getName()} sending email";
570 if ( !$this->passCaptcha() ) {
571 $error = wfMessage( 'captcha-sendemail-fail' )->text();
579 * @param $module ApiBase
580 * @param $params array
583 public function APIGetAllowedParams( &$module, &$params ) {
584 if ( !$module instanceof ApiEditPage ) {
587 $params['captchaword'] = null;
588 $params['captchaid'] = null;
594 * @param $module ApiBase
598 public function APIGetParamDescription( &$module, &$desc ) {
599 if ( !$module instanceof ApiEditPage ) {
602 $desc['captchaid'] = 'CAPTCHA ID from previous request';
603 $desc['captchaword'] = 'Answer to the CAPTCHA';
609 * Given a required captcha run, test form input for correct
610 * input on the open session.
611 * @return bool if passed, false if failed or new session
613 function passCaptcha() {
614 $info = $this->retrieveCaptcha();
617 if ( $this->keyMatch( $wgRequest->getVal( 'wpCaptchaWord' ), $info ) ) {
618 $this->log( "passed" );
619 $this->clearCaptcha( $info );
622 $this->clearCaptcha( $info );
623 $this->log( "bad form input" );
627 $this->log( "new captcha session" );
633 * Log the status and any triggering info for debugging or statistics
634 * @param string $message
636 function log( $message ) {
637 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' . $this->trigger );
641 * Generate a captcha session ID and save the info in PHP's session storage.
642 * (Requires the user to have cookies enabled to get through the captcha.)
644 * A random ID is used so legit users can make edits in multiple tabs or
645 * windows without being unnecessarily hobbled by a serial order requirement.
646 * Pass the returned id value into the edit form as wpCaptchaId.
648 * @param array $info data to store
649 * @return string captcha ID key
651 function storeCaptcha( $info ) {
652 if ( !isset( $info['index'] ) ) {
653 // Assign random index if we're not udpating
654 $info['index'] = strval( mt_rand() );
656 CaptchaStore::get()->store( $info['index'], $info );
657 return $info['index'];
661 * Fetch this session's captcha info.
662 * @return mixed array of info, or false if missing
664 function retrieveCaptcha() {
666 $index = $wgRequest->getVal( 'wpCaptchaId' );
667 return CaptchaStore::get()->retrieve( $index );
671 * Clear out existing captcha info from the session, to ensure
672 * it can't be reused.
674 function clearCaptcha( $info ) {
675 CaptchaStore::get()->clear( $info['index'] );
679 * Retrieve the current version of the page or section being edited...
680 * @param EditPage $editPage
681 * @param string $section
685 function loadText( $editPage, $section ) {
686 $rev = Revision::newFromTitle( $editPage->mTitle, false, Revision::READ_LATEST );
687 if ( is_null( $rev ) ) {
690 $text = $rev->getText();
691 if ( $section != '' ) {
693 return $wgParser->getSection( $text, $section );
701 * Extract a list of all recognized HTTP links in the text.
702 * @param $editpage EditPage
703 * @param $text string
704 * @return array of strings
706 function findLinks( &$editpage, $text ) {
707 global $wgParser, $wgUser;
709 $options = new ParserOptions();
710 $text = $wgParser->preSaveTransform( $text, $editpage->mTitle, $wgUser, $options );
711 $out = $wgParser->parse( $text, $editpage->mTitle, $options );
713 return array_keys( $out->getExternalLinks() );
717 * Show a page explaining what this wacky thing is.
719 function showHelp() {
721 $wgOut->setPageTitle( wfMessage( 'captchahelp-title' )->text() );
722 $wgOut->addWikiMsg( 'captchahelp-text' );
723 if ( CaptchaStore::get()->cookiesNeeded() ) {
724 $wgOut->addWikiMsg( 'captchahelp-cookies-needed' );