a9600d711946c758f846121e68a64a5c06f732c3
[toast/cookiecaptcha.git] / ConfirmEdit_body.php
1 <?php
2
3 class ConfirmEditHooks {
4         static function getInstance() {
5                 global $wgCaptcha, $wgCaptchaClass, $wgExtensionMessagesFiles;
6                 static $done = false;
7                 if ( !$done ) {
8                         $done = true;
9                         wfLoadExtensionMessages( 'ConfirmEdit' );
10                         if ( isset( $wgExtensionMessagesFiles[$wgCaptchaClass] ) ) {
11                                 wfLoadExtensionMessages( $wgCaptchaClass );
12                         }
13                         $wgCaptcha = new $wgCaptchaClass;
14                 }
15                 return $wgCaptcha;
16         }
17
18         static function confirmEdit( &$editPage, $newtext, $section ) {
19                 return self::getInstance()->confirmEdit( $editPage, $newtext, $section );
20         }
21
22         static function confirmEditMerged( &$editPage, $newtext ) {
23                 return self::getInstance()->confirmEditMerged( $editPage, $newtext );
24         }
25
26         static function injectUserCreate( &$template ) {
27                 return self::getInstance()->injectUserCreate( $template );
28         }
29
30         static function confirmUserCreate( $u, &$message ) {
31                 return self::getInstance()->confirmUserCreate( $u, $message );
32         }
33
34         static function triggerUserLogin( $user, $password, $retval ) {
35                 return self::getInstance()->triggerUserLogin( $user, $password, $retval );
36         }
37
38         static function injectUserLogin( &$template ) {
39                 return self::getInstance()->injectUserLogin( $template );
40         }
41
42         static function confirmUserLogin( $u, $pass, &$retval ) {
43                 return self::getInstance()->confirmUserLogin( $u, $pass, $retval );
44         }
45 }
46
47 class CaptchaSpecialPage extends UnlistedSpecialPage {
48         function execute( $par ) {
49                 $this->setHeaders();
50                 $instance = ConfirmEditHooks::getInstance();
51                 switch( $par ) {
52                 case "image":
53                         return $instance->showImage();
54                 case "help":
55                 default:
56                         return $instance->showHelp();
57                 }
58         }
59 }
60
61
62 class SimpleCaptcha {
63         function SimpleCaptcha() {
64                 global $wgCaptchaStorageClass;
65                 $this->storage = new $wgCaptchaStorageClass;
66         }
67         
68         /**
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.
72          *
73          * Override this!
74          *
75          * @return string HTML
76          */
77         function getForm() {
78                 $a = mt_rand(0, 100);
79                 $b = mt_rand(0, 10);
80                 $op = mt_rand(0, 1) ? '+' : '-';
81
82                 $test = "$a $op $b";
83                 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
84
85                 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
86
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
92                         "</p>\n" .
93                         wfElement( 'input', array(
94                                 'type'  => 'hidden',
95                                 'name'  => 'wpCaptchaId',
96                                 'id'    => 'wpCaptchaId',
97                                 'value' => $index ) );
98         }
99
100         /**
101          * Insert the captcha prompt into an edit form.
102          * @param OutputPage $out
103          */
104         function editCallback( &$out ) {
105                 $out->addWikiText( $this->getMessage( $this->action ) );
106                 $out->addHTML( $this->getForm() );
107         }
108
109         /**
110          * Show a message asking the user to enter a captcha on edit
111          * The result will be treated as wiki text
112          *
113          * @param $action Action being performed
114          * @return string
115          */
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;
122         }
123
124         /**
125          * Inject whazawhoo
126          * @fixme if multiple thingies insert a header, could break
127          * @param SimpleTemplate $template
128          * @return bool true to keep running callbacks
129          */
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' ) ) .
136                                 $this->getForm() .
137                                 "</div>\n" );
138                 }
139                 return true;
140         }
141
142         /**
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
148          */
149         function injectUserLogin( &$template ) {
150                 if( $this->isBadLoginTriggered() ) {
151                         global $wgOut;
152                         $template->set( 'header',
153                                 "<div class='captcha'>" .
154                                 $wgOut->parse( $this->getMessage( 'badlogin' ) ) .
155                                 $this->getForm() .
156                                 "</div>\n" );
157                 }
158                 return true;
159         }
160         
161         /**
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.
165          * @param User $user
166          * @param string $password
167          * @param int $retval authentication return value
168          * @return bool true to keep running callbacks
169          */
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 );
175                         if( !$count ) {
176                                 $wgMemc->add( $key, 0, $wgCaptchaBadLoginExpiration );
177                         }
178                         $count = $wgMemc->incr( $key );
179                 }
180                 return true;
181         }
182         
183         /**
184          * Check if a bad login has already been registered for this
185          * IP address. If so, require a captcha.
186          * @return bool
187          * @access private
188          */
189         function isBadLoginTriggered() {
190                 global $wgMemc;
191                 return intval( $wgMemc->get( $this->badLoginKey() ) ) > 0;
192         }
193         
194         /**
195          * Internal cache key for badlogin checks.
196          * @return string
197          * @access private
198          */
199         function badLoginKey() {
200                 return wfMemcKey( 'captcha', 'badlogin', 'ip', wfGetIP() );
201         }
202         
203         /**
204          * Check if the submitted form matches the captcha session data provided
205          * by the plugin when the form was generated.
206          *
207          * Override this!
208          *
209          * @param WebRequest $request
210          * @param array $info
211          * @return bool
212          */
213         function keyMatch( $request, $info ) {
214                 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
215         }
216
217         // ----------------------------------
218
219         /**
220          * @param EditPage $editPage
221          * @param string $action (edit/create/addurl...)
222          * @return bool true if action triggers captcha on editPage's namespace
223          */
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];
229
230                 return ( !empty( $wgCaptchaTriggers[$action] ) ); //Default
231         }
232
233
234         /**
235          * @param EditPage $editPage
236          * @param string $newtext
237          * @param string $section
238          * @return bool true if the captcha should run
239          */
240         function shouldCheck( &$editPage, $newtext, $section, $merged = false ) {
241                 $this->trigger = '';
242                 $title = $editPage->mArticle->getTitle();
243
244                 global $wgUser;
245                 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
246                         wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
247                         return false;
248                 }
249                 global $wgCaptchaWhitelistIP;
250                 if( !empty( $wgCaptchaWhitelistIP ) ) {
251                         $ip = wfGetIp();
252                         foreach ( $wgCaptchaWhitelistIP as $range ) {
253                                 if ( IP::isInRange( $ip, $range ) ) {
254                                         return false;
255                                 }
256                         }
257                 }
258
259
260                 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
261                 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
262                         $wgUser->isEmailConfirmed() ) {
263                         wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
264                         return false;
265                 }
266
267                 if( $this->captchaTriggers( $editPage, 'edit' ) ) {
268                         // Check on all edits
269                         global $wgUser;
270                         $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
271                                 $wgUser->getName(),
272                                 $title->getPrefixedText() );
273                         $this->action = 'edit';
274                         wfDebug( "ConfirmEdit: checking all edits...\n" );
275                         return true;
276                 }
277
278                 if( $this->captchaTriggers( $editPage, 'create' )  && !$editPage->mTitle->exists() ) {
279                         //Check if creating a page
280                         global $wgUser;
281                         $this->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
282                                 $wgUser->getName(),
283                                 $title->getPrefixedText() );
284                         $this->action = 'create';
285                         wfDebug( "ConfirmEdit: checking on page creation...\n" );
286                         return true;
287                 }
288
289                 if( $this->captchaTriggers( $editPage, 'addurl' ) ) {
290                         // Only check edits that add URLs
291                         if ( $merged ) {
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() );
297                         } else {
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 );
302                         }
303
304                         $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
305                         $addedLinks = array_diff( $unknownLinks, $oldLinks );
306                         $numLinks = count( $addedLinks );
307
308                         if( $numLinks > 0 ) {
309                                 global $wgUser;
310                                 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
311                                         $numLinks,
312                                         $wgUser->getName(),
313                                         $title->getPrefixedText(),
314                                         implode( ", ", $addedLinks ) );
315                                 $this->action = 'addurl';
316                                 return true;
317                         }
318                 }
319
320                 global $wgCaptchaRegexes;
321                 if( !empty( $wgCaptchaRegexes ) ) {
322                         // Custom regex checks
323                         $oldtext = $this->loadText( $editPage, $section );
324
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 );
330
331                                         $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
332
333                                         $numHits = count( $addedMatches );
334                                         if( $numHits > 0 ) {
335                                                 global $wgUser;
336                                                 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
337                                                         $numHits,
338                                                         $regex,
339                                                         $wgUser->getName(),
340                                                         $title->getPrefixedText(),
341                                                         implode( ", ", $addedMatches ) );
342                                                 $this->action = 'edit';
343                                                 return true;
344                                         }
345                                 }
346                         }
347                 }
348
349                 return false;
350         }
351
352         /**
353          * Filter callback function for URL whitelisting
354          * @param string url to check
355          * @return bool true if unknown, false if whitelisted
356          * @access private
357          */
358         function filterLink( $url ) {
359                 global $wgCaptchaWhitelist;
360                 $source = wfMsgForContent( 'captcha-addurl-whitelist' );
361
362                 $whitelist = wfEmptyMsg( 'captcha-addurl-whitelist', $source ) 
363                         ? false
364                         : $this->buildRegexes( explode( "\n", $source ) );
365
366                 $cwl = $wgCaptchaWhitelist !== false ? preg_match( $wgCaptchaWhitelist, $url ) : false;
367                 $wl  = $whitelist          !== false ? preg_match( $whitelist, $url )          : false;
368
369                 return !( $cwl || $wl );
370         }
371
372         /**
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
376          * @access private
377          */
378         function buildRegexes( $lines ) {
379                 # Code duplicated from the SpamBlacklist extension (r19197)
380
381                 # Strip comments and whitespace, then remove blanks
382                 $lines = array_filter( array_map( 'trim', preg_replace( '/#.*$/', '', $lines ) ) );
383
384                 # No lines, don't make a regex which will match everything
385                 if ( count( $lines ) == 0 ) {
386                         wfDebug( "No lines\n" );
387                         return false;
388                 } else {
389                         # Make regex
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';
393                         $regexes = '';
394                         $regexStart = '/http:\/\/+[a-z0-9_\-.]*(';
395                         $regexEnd = ')/Si';
396                         $regexMax = 4096;
397                         $build = false;
398                         foreach( $lines as $line ) {
399                                 // FIXME: not very robust size check, but should work. :)
400                                 if( $build === false ) {
401                                         $build = $line;
402                                 } elseif( strlen( $build ) + strlen( $line ) > $regexMax ) {
403                                         $regexes .= $regexStart .
404                                                 str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $build) ) .
405                                                 $regexEnd;
406                                         $build = $line;
407                                 } else {
408                                         $build .= '|' . $line;
409                                 }
410                         }
411                         if( $build !== false ) {
412                                 $regexes .= $regexStart .
413                                         str_replace( '/', '\/', preg_replace('|\\\*/|', '/', $build) ) .
414                                         $regexEnd;
415                         }
416                         return $regexes;
417                 }
418         }
419
420         /**
421          * Load external links from the externallinks table
422          */
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__ );
428                 $links = array();
429                 while ( $row = $dbr->fetchObject( $res ) ) {
430                         $links[] = $row->el_to;
431                 }
432                 return $links;
433         }               
434
435         /**
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
441          */
442         function confirmEdit( &$editPage, $newtext, $section, $merged = false ) {
443                 if( $this->shouldCheck( $editPage, $newtext, $section, $merged ) ) {
444                         if( $this->passCaptcha() ) {
445                                 return true;
446                         } else {
447                                 $editPage->showEditForm( array( &$this, 'editCallback' ) );
448                                 return false;
449                         }
450                 } else {
451                         wfDebug( "ConfirmEdit: no need to show captcha.\n" );
452                         return true;
453                 }
454         }
455
456         /**
457          * A more efficient edit filter callback based on the text after section merging
458          * @param EditPage $editPage
459          * @param string $newtext
460          */
461         function confirmEditMerged( &$editPage, $newtext ) {
462                 return $this->confirmEdit( $editPage, $newtext, false, true );
463         }
464
465         /**
466          * Hook for user creation form submissions.
467          * @param User $u
468          * @param string $message
469          * @return bool true to continue, false to abort user creation
470          */
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' );
477                                 return false;
478                         }
479                 }
480                 return true;
481         }
482         
483         /**
484          * Hook for user login form submissions.
485          * @param User $u
486          * @param string $message
487          * @return bool true to continue, false to abort user creation
488          */
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;
496                                 return false;
497                         }
498                 }
499                 return true;
500         }
501
502         /**
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
506          */
507         function passCaptcha() {
508                 $info = $this->retrieveCaptcha();
509                 if( $info ) {
510                         global $wgRequest;
511                         if( $this->keyMatch( $wgRequest, $info ) ) {
512                                 $this->log( "passed" );
513                                 $this->clearCaptcha( $info );
514                                 return true;
515                         } else {
516                                 $this->clearCaptcha( $info );
517                                 $this->log( "bad form input" );
518                                 return false;
519                         }
520                 } else {
521                         $this->log( "new captcha session" );
522                         return false;
523                 }
524         }
525
526         /**
527          * Log the status and any triggering info for debugging or statistics
528          * @param string $message
529          */
530         function log( $message ) {
531                 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' .  $this->trigger );
532         }
533
534         /**
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.)
537          *
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.
541          *
542          * @param array $info data to store
543          * @return string captcha ID key
544          */
545         function storeCaptcha( $info ) {
546                 if( !isset( $info['index'] ) ) {
547                         // Assign random index if we're not udpating
548                         $info['index'] = strval( mt_rand() );
549                 }
550                 $this->storage->store( $info['index'], $info );
551                 return $info['index'];
552         }
553
554         /**
555          * Fetch this session's captcha info.
556          * @return mixed array of info, or false if missing
557          */
558         function retrieveCaptcha() {
559                 global $wgRequest;
560                 $index = $wgRequest->getVal( 'wpCaptchaId' );
561                 return $this->storage->retrieve( $index );
562         }
563
564         /**
565          * Clear out existing captcha info from the session, to ensure
566          * it can't be reused.
567          */
568         function clearCaptcha( $info ) {
569                 $this->storage->clear( $info['index'] );
570         }
571
572         /**
573          * Retrieve the current version of the page or section being edited...
574          * @param EditPage $editPage
575          * @param string $section
576          * @return string
577          * @access private
578          */
579         function loadText( $editPage, $section ) {
580                 $rev = Revision::newFromTitle( $editPage->mTitle );
581                 if( is_null( $rev ) ) {
582                         return "";
583                 } else {
584                         $text = $rev->getText();
585                         if( $section != '' ) {
586                                 return Article::getSection( $text, $section );
587                         } else {
588                                 return $text;
589                         }
590                 }
591         }
592
593         /**
594          * Extract a list of all recognized HTTP links in the text.
595          * @param string $text
596          * @return array of strings
597          */
598         function findLinks( $text ) {
599                 global $wgParser, $wgTitle, $wgUser;
600
601                 $options = new ParserOptions();
602                 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
603                 $out = $wgParser->parse( $text, $wgTitle, $options );
604
605                 return array_keys( $out->getExternalLinks() );
606         }
607
608         /**
609          * Show a page explaining what this wacky thing is.
610          */
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' ) );
617                 }
618         }
619
620 }
621
622 class CaptchaSessionStore {
623         function store( $index, $info ) {
624                 $_SESSION['captcha' . $info['index']] = $info;
625         }
626         
627         function retrieve( $index ) {
628                 if( isset( $_SESSION['captcha' . $index] ) ) {
629                         return $_SESSION['captcha' . $index];
630                 } else {
631                         return false;
632                 }
633         }
634         
635         function clear( $index ) {
636                 unset( $_SESSION['captcha' . $index] );
637         }
638
639         function cookiesNeeded() {
640                 return true;
641         }
642 }
643
644 class CaptchaCacheStore {
645         function store( $index, $info ) {
646                 global $wgMemc, $wgCaptchaSessionExpiration;
647                 $wgMemc->set( wfMemcKey( 'captcha', $index ), $info,
648                         $wgCaptchaSessionExpiration );
649         }
650
651         function retrieve( $index ) {
652                 global $wgMemc;
653                 $info = $wgMemc->get( wfMemcKey( 'captcha', $index ) );
654                 if( $info ) {
655                         return $info;
656                 } else {
657                         return false;
658                 }
659         }
660         
661         function clear( $index ) {
662                 global $wgMemc;
663                 $wgMemc->delete( wfMemcKey( 'captcha', $index ) );
664         }
665
666         function cookiesNeeded() {
667                 return false;
668         }
669 }
670