Revert 15644; extensions need to remain self-contained
[toast/cookiecaptcha.git] / ConfirmEdit.php
1 <?php
2 /**
3  * Experimental captcha plugin framework.
4  * Not intended as a real production captcha system; derived classes
5  * can extend the base to produce their fancy images in place of the
6  * text-based test output here.
7  *
8  * Copyright (C) 2005, 2006 Brion Vibber <brion@pobox.com>
9  * http://www.mediawiki.org/
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License along
22  * with this program; if not, write to the Free Software Foundation, Inc.,
23  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24  * http://www.gnu.org/copyleft/gpl.html
25  *
26  * @package MediaWiki
27  * @subpackage Extensions
28  */
29
30 if ( defined( 'MEDIAWIKI' ) ) {
31
32 global $wgExtensionFunctions, $wgGroupPermissions;
33
34 $wgExtensionFunctions[] = 'ceSetup';
35
36 # Internationalisation file
37 require_once( 'ConfirmEdit.i18n.php' );
38
39 /**
40  * The 'skipcaptcha' permission key can be given out to
41  * let known-good users perform triggering actions without
42  * having to go through the captcha.
43  *
44  * By default, sysops and registered bot accounts will be
45  * able to skip, while others have to go through it.
46  */
47 $wgGroupPermissions['*'            ]['skipcaptcha'] = false;
48 $wgGroupPermissions['user'         ]['skipcaptcha'] = false;
49 $wgGroupPermissions['autoconfirmed']['skipcaptcha'] = false;
50 $wgGroupPermissions['bot'          ]['skipcaptcha'] = true; // registered bots
51 $wgGroupPermissions['sysop'        ]['skipcaptcha'] = true;
52
53 global $wgCaptcha, $wgCaptchaClass, $wgCaptchaTriggers;
54 $wgCaptcha = null;
55 $wgCaptchaClass = 'SimpleCaptcha';
56
57 /**
58  * Currently the captcha works only for page edits.
59  *
60  * If the 'edit' trigger is on, *every* edit will trigger the captcha.
61  * This may be useful for protecting against vandalbot attacks.
62  *
63  * If using the default 'addurl' trigger, the captcha will trigger on
64  * edits that include URLs that aren't in the current version of the page.
65  * This should catch automated linkspammers without annoying people when
66  * they make more typical edits.
67  */
68 $wgCaptchaTriggers = array();
69 $wgCaptchaTriggers['edit']          = false; // Would check on every edit
70 $wgCaptchaTriggers['addurl']        = true;  // Check on edits that add URLs
71 $wgCaptchaTriggers['createaccount'] = true;  // Special:Userlogin&type=signup
72
73
74 /**
75  * Allow users who have confirmed their e-mail addresses to post
76  * URL links without being harassed by the captcha.
77  */
78 global $ceAllowConfirmedEmail;
79 $ceAllowConfirmedEmail = false;
80
81 /**
82  * Regex to whitelist URLs to known-good sites...
83  * For instance:
84  * $wgCaptchaWhitelist = '#^https?://([a-z0-9-]+\\.)?(wikimedia|wikipedia)\.org/#i';
85  * @fixme Use the 'spam-whitelist' thingy instead?
86  */
87 $wgCaptchaWhitelist = false;
88
89 /**
90  * Additional regexes to check for. Use full regexes; can match things
91  * other than URLs such as junk edits.
92  *
93  * If the new version matches one and the old version doesn't,
94  * toss up the captcha screen.
95  *
96  * @fixme Add a message for local admins to add items as well.
97  */
98 $wgCaptchaRegexes = array();
99
100 /** Register special page */
101 global $wgSpecialPages;
102 $wgSpecialPages['Captcha'] = array( /*class*/ 'SpecialPage', /*name*/'Captcha', /*restriction*/ '',
103         /*listed*/ false, /*function*/ false, /*file*/ false );
104
105 /**
106  * Set up message strings for captcha utilities.
107  */
108 function ceSetup() {
109         # Add messages
110         global $wgMessageCache, $wgConfirmEditMessages;
111         foreach( $wgConfirmEditMessages as $key => $value ) {
112                 $wgMessageCache->addMessages( $wgConfirmEditMessages[$key], $key );
113         }
114         
115         global $wgHooks, $wgCaptcha, $wgCaptchaClass, $wgSpecialPages;
116         $wgCaptcha = new $wgCaptchaClass();
117         $wgHooks['EditFilter'][] = array( &$wgCaptcha, 'confirmEdit' );
118         
119         $wgHooks['UserCreateForm'][] = array( &$wgCaptcha, 'injectUserCreate' );
120         $wgHooks['AbortNewAccount'][] = array( &$wgCaptcha, 'confirmUserCreate' );
121 }
122
123 /**
124  * Entry point for Special:Captcha
125  */
126 function wfSpecialCaptcha( $par = null ) {
127         global $wgCaptcha;
128         switch( $par ) {
129         case "image":
130                 return $wgCaptcha->showImage();
131         case "help":
132         default:
133                 return $wgCaptcha->showHelp();
134         }
135 }
136
137 class SimpleCaptcha {
138         /**
139          * Insert a captcha prompt into the edit form.
140          * This sample implementation generates a simple arithmetic operation;
141          * it would be easy to defeat by machine.
142          *
143          * Override this!
144          *
145          * @return string HTML
146          */
147         function getForm() {
148                 $a = mt_rand(0, 100);
149                 $b = mt_rand(0, 10);
150                 $op = mt_rand(0, 1) ? '+' : '-';
151                 
152                 $test = "$a $op $b";
153                 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
154                 
155                 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
156                 
157                 return "<p><label for=\"wpCaptchaWord\">$test</label> = " .
158                         wfElement( 'input', array(
159                                 'name' => 'wpCaptchaWord',
160                                 'id'   => 'wpCaptchaWord',
161                                 'tabindex' => 1 ) ) . // tab in before the edit textarea
162                         "</p>\n" .
163                         wfElement( 'input', array(
164                                 'type'  => 'hidden',
165                                 'name'  => 'wpCaptchaId',
166                                 'id'    => 'wpCaptchaId',
167                                 'value' => $index ) );
168         }
169         
170         /**
171          * Insert the captcha prompt into an edit form.
172          * @param OutputPage $out
173          */
174         function editCallback( &$out ) {
175                 $out->addWikiText( wfMsg( "captcha-short" ) );  
176                 $out->addHTML( $this->getForm() );
177         }
178         
179         /**
180          * Inject whazawhoo
181          * @fixme if multiple thingies insert a header, could break
182          * @param SimpleTemplate $template
183          * @return bool true to keep running callbacks
184          */
185         function injectUserCreate( &$template ) {
186                 global $wgCaptchaTriggers, $wgOut;
187                 if( $wgCaptchaTriggers['createaccount'] ) {
188                         $template->set( 'header',
189                                 "<div class='captcha'>" .
190                                 $wgOut->parse( wfMsg( 'captcha-createaccount' ) ) .
191                                 $this->getForm() .
192                                 "</div>\n" );
193                 }
194                 return true;
195         }
196         
197         /**
198          * Check if the submitted form matches the captcha session data provided
199          * by the plugin when the form was generated.
200          *
201          * Override this!
202          *
203          * @param WebRequest $request
204          * @param array $info
205          * @return bool
206          */
207         function keyMatch( $request, $info ) {
208                 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
209         }
210         
211         // ----------------------------------
212         
213         /**
214          * @param EditPage $editPage
215          * @param string $newtext
216          * @param string $section
217          * @return bool true if the captcha should run
218          */
219         function shouldCheck( &$editPage, $newtext, $section ) {
220                 $this->trigger = '';
221                 
222                 global $wgUser;
223                 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
224                         wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
225                         return false;
226                 }
227         
228                 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
229                 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
230                         $wgUser->isEmailConfirmed() ) {
231                         wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
232                         return false;
233                 }
234                 
235                 global $wgCaptchaTriggers;
236                 if( !empty( $wgCaptchaTriggers['edit'] ) ) {
237                         // Check on all edits
238                         global $wgUser, $wgTitle;
239                         $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
240                                 $wgUser->getName(),
241                                 $wgTitle->getPrefixedText() );
242                         wfDebug( "ConfirmEdit: checking all edits...\n" );
243                         return true;
244                 }
245                 
246                 if( !empty( $wgCaptchaTriggers['addurl'] ) ) {
247                         // Only check edits that add URLs
248                         $oldtext = $this->loadText( $editPage, $section );
249                         
250                         $oldLinks = $this->findLinks( $oldtext );
251                         $newLinks = $this->findLinks( $newtext );
252                         $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
253                         
254                         $addedLinks = array_diff( $unknownLinks, $oldLinks );
255                         $numLinks = count( $addedLinks );
256                         
257                         if( $numLinks > 0 ) {
258                                 global $wgUser, $wgTitle;
259                                 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
260                                         $numLinks,
261                                         $wgUser->getName(),
262                                         $wgTitle->getPrefixedText(),
263                                         implode( ", ", $addedLinks ) );
264                                 return true;
265                         }
266                 }
267                 
268                 global $wgCaptchaRegexes;
269                 if( !empty( $wgCaptchaRegexes ) ) {
270                         // Custom regex checks
271                         $oldtext = $this->loadText( $editPage, $section );
272                         
273                         foreach( $wgCaptchaRegexes as $regex ) {
274                                 $newMatches = array();
275                                 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
276                                         $oldMatches = array();
277                                         preg_match_all( $regex, $oldtext, $oldMatches );
278                                         
279                                         $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
280                                         
281                                         $numHits = count( $addedMatches );
282                                         if( $numHits > 0 ) {
283                                                 global $wgUser, $wgTitle;
284                                                 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
285                                                         $numHits,
286                                                         $regex,
287                                                         $wgUser->getName(),
288                                                         $wgTitle->getPrefixedText(),
289                                                         implode( ", ", $addedMatches ) );
290                                                 return true;
291                                         }
292                                 }
293                         }
294                 }
295                 
296                 return false;
297         }
298         
299         /**
300          * Filter callback function for URL whitelisting
301          * @return bool true if unknown, false if whitelisted
302          * @access private
303          */
304         function filterLink( $url ) {
305                 global $wgCaptchaWhitelist;
306                 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
307         }
308         
309         /**
310          * The main callback run on edit attempts.
311          * @param EditPage $editPage
312          * @param string $newtext
313          * @param string $section
314          * @param bool true to continue saving, false to abort and show a captcha form
315          */
316         function confirmEdit( &$editPage, $newtext, $section ) {
317                 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
318                         if( $this->passCaptcha() ) {
319                                 return true;
320                         } else {
321                                 $editPage->showEditForm( array( &$this, 'editCallback' ) );
322                                 return false;
323                         }
324                 } else {
325                         wfDebug( "ConfirmEdit: no new links.\n" );
326                         return true;
327                 }
328         }
329         
330         /**
331          * Hook for user creation form submissions.
332          * @param User $u
333          * @param string $message
334          * @return bool true to continue, false to abort user creation
335          */
336         function confirmUserCreate( $u, &$message ) {
337                 global $wgCaptchaTriggers;
338                 if( $wgCaptchaTriggers['createaccount'] ) {
339                         $this->trigger = "new account '" . $u->getName() . "'";
340                         if( !$this->passCaptcha() ) {
341                                 $message = wfMsg( 'captcha-createaccount-fail' );
342                                 return false;
343                         }
344                 }
345                 return true;
346         }
347         
348         /**
349          * Given a required captcha run, test form input for correct
350          * input on the open session.
351          * @return bool if passed, false if failed or new session
352          */
353         function passCaptcha() {
354                 $info = $this->retrieveCaptcha();
355                 if( $info ) {
356                         global $wgRequest;
357                         if( $this->keyMatch( $wgRequest, $info ) ) {
358                                 $this->log( "passed" );
359                                 $this->clearCaptcha( $info );
360                                 return true;
361                         } else {
362                                 $this->clearCaptcha( $info );
363                                 $this->log( "bad form input" );
364                                 return false;
365                         }
366                 } else {
367                         $this->log( "new captcha session" );
368                         return false;
369                 }
370         }
371         
372         /**
373          * Log the status and any triggering info for debugging or statistics
374          * @param string $message
375          */
376         function log( $message ) {
377                 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' .  $this->trigger );
378         }
379         
380         /**
381          * Generate a captcha session ID and save the info in PHP's session storage.
382          * (Requires the user to have cookies enabled to get through the captcha.)
383          *
384          * A random ID is used so legit users can make edits in multiple tabs or
385          * windows without being unnecessarily hobbled by a serial order requirement.
386          * Pass the returned id value into the edit form as wpCaptchaId.
387          *
388          * @param array $info data to store
389          * @return string captcha ID key
390          */
391         function storeCaptcha( $info ) {
392                 if( !isset( $info['index'] ) ) {
393                         // Assign random index if we're not udpating
394                         $info['index'] = strval( mt_rand() );
395                 }
396                 $_SESSION['captcha' . $info['index']] = $info;
397                 return $info['index'];
398         }
399         
400         /**
401          * Fetch this session's captcha info.
402          * @return mixed array of info, or false if missing
403          */
404         function retrieveCaptcha() {
405                 global $wgRequest;
406                 $index = $wgRequest->getVal( 'wpCaptchaId' );
407                 if( isset( $_SESSION['captcha' . $index] ) ) {
408                         return $_SESSION['captcha' . $index];
409                 } else {
410                         return false;
411                 }
412         }
413         
414         /**
415          * Clear out existing captcha info from the session, to ensure
416          * it can't be reused.
417          */
418         function clearCaptcha( $info ) {
419                 unset( $_SESSION['captcha' . $info['index']] );
420         }
421         
422         /**
423          * Retrieve the current version of the page or section being edited...
424          * @param EditPage $editPage
425          * @param string $section
426          * @return string
427          * @access private
428          */
429         function loadText( $editPage, $section ) {
430                 $rev = Revision::newFromTitle( $editPage->mTitle );
431                 if( is_null( $rev ) ) {
432                         return "";
433                 } else {
434                         $text = $rev->getText();
435                         if( $section != '' ) {
436                                 return Article::getSection( $text, $section );
437                         } else {
438                                 return $text;
439                         }
440                 }
441         }
442         
443         /**
444          * Extract a list of all recognized HTTP links in the text.
445          * @param string $text
446          * @return array of strings
447          */
448         function findLinks( $text ) {
449                 $regex = '/((?:' . HTTP_PROTOCOLS . ')' . EXT_LINK_URL_CLASS . '+)/';
450                 
451                 if( preg_match_all( $regex, $text, $matches, PREG_PATTERN_ORDER ) ) {
452                         return $matches[1];
453                 } else {
454                         return array();
455                 }
456         }
457         
458         /**
459          * Show a page explaining what this wacky thing is.
460          */
461         function showHelp() {
462                 global $wgOut, $ceAllowConfirmedEmail;
463                 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
464                 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
465         }
466         
467 }
468
469 } # End invocation guard
470
471 ?>