]> ToastFreeware Gitweb - toast/cookiecaptcha.git/blob - ConfirmEdit.php
Extension credits
[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 $wgExtensionCredits['other'][] = array( 'name' => 'ConfirmEdit', 'author' => 'Brion Vibber' );
36
37 # Internationalisation file
38 require_once( 'ConfirmEdit.i18n.php' );
39
40 /**
41  * The 'skipcaptcha' permission key can be given out to
42  * let known-good users perform triggering actions without
43  * having to go through the captcha.
44  *
45  * By default, sysops and registered bot accounts will be
46  * able to skip, while others have to go through it.
47  */
48 $wgGroupPermissions['*'            ]['skipcaptcha'] = false;
49 $wgGroupPermissions['user'         ]['skipcaptcha'] = false;
50 $wgGroupPermissions['autoconfirmed']['skipcaptcha'] = false;
51 $wgGroupPermissions['bot'          ]['skipcaptcha'] = true; // registered bots
52 $wgGroupPermissions['sysop'        ]['skipcaptcha'] = true;
53
54 global $wgCaptcha, $wgCaptchaClass, $wgCaptchaTriggers;
55 $wgCaptcha = null;
56 $wgCaptchaClass = 'SimpleCaptcha';
57
58 /**
59  * Currently the captcha works only for page edits.
60  *
61  * If the 'edit' trigger is on, *every* edit will trigger the captcha.
62  * This may be useful for protecting against vandalbot attacks.
63  *
64  * If using the default 'addurl' trigger, the captcha will trigger on
65  * edits that include URLs that aren't in the current version of the page.
66  * This should catch automated linkspammers without annoying people when
67  * they make more typical edits.
68  */
69 $wgCaptchaTriggers = array();
70 $wgCaptchaTriggers['edit']          = false; // Would check on every edit
71 $wgCaptchaTriggers['addurl']        = true;  // Check on edits that add URLs
72 $wgCaptchaTriggers['createaccount'] = true;  // Special:Userlogin&type=signup
73
74
75 /**
76  * Allow users who have confirmed their e-mail addresses to post
77  * URL links without being harassed by the captcha.
78  */
79 global $ceAllowConfirmedEmail;
80 $ceAllowConfirmedEmail = false;
81
82 /**
83  * Regex to whitelist URLs to known-good sites...
84  * For instance:
85  * $wgCaptchaWhitelist = '#^https?://([a-z0-9-]+\\.)?(wikimedia|wikipedia)\.org/#i';
86  * @fixme Use the 'spam-whitelist' thingy instead?
87  */
88 $wgCaptchaWhitelist = false;
89
90 /**
91  * Additional regexes to check for. Use full regexes; can match things
92  * other than URLs such as junk edits.
93  *
94  * If the new version matches one and the old version doesn't,
95  * toss up the captcha screen.
96  *
97  * @fixme Add a message for local admins to add items as well.
98  */
99 $wgCaptchaRegexes = array();
100
101 /** Register special page */
102 global $wgSpecialPages;
103 $wgSpecialPages['Captcha'] = array( /*class*/ 'SpecialPage', /*name*/'Captcha', /*restriction*/ '',
104         /*listed*/ false, /*function*/ false, /*file*/ false );
105
106 /**
107  * Set up message strings for captcha utilities.
108  */
109 function ceSetup() {
110         # Add messages
111         global $wgMessageCache, $wgConfirmEditMessages;
112         foreach( $wgConfirmEditMessages as $lang => $messages )
113                 $wgMessageCache->addMessages( $messages, $lang );
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( $this->getMessage( 'edit' ) );
176                 $out->addHTML( $this->getForm() );
177         }
178         
179         /**
180          * Show a message asking the user to enter a captcha on edit
181          * The result will be treated as wiki text
182          *
183          * @param $action Action being performed
184          * @return string
185          */
186         function getMessage( $action ) {
187                 $name = 'captcha-' . $action;
188                 $text = wfMsg( $name );
189                 # Obtain a more tailored message, if possible, otherwise, fall back to
190                 # the default for edits
191                 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
192         }
193         
194         /**
195          * Inject whazawhoo
196          * @fixme if multiple thingies insert a header, could break
197          * @param SimpleTemplate $template
198          * @return bool true to keep running callbacks
199          */
200         function injectUserCreate( &$template ) {
201                 global $wgCaptchaTriggers, $wgOut;
202                 if( $wgCaptchaTriggers['createaccount'] ) {
203                         $template->set( 'header',
204                                 "<div class='captcha'>" .
205                                 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
206                                 $this->getForm() .
207                                 "</div>\n" );
208                 }
209                 return true;
210         }
211         
212         /**
213          * Check if the submitted form matches the captcha session data provided
214          * by the plugin when the form was generated.
215          *
216          * Override this!
217          *
218          * @param WebRequest $request
219          * @param array $info
220          * @return bool
221          */
222         function keyMatch( $request, $info ) {
223                 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
224         }
225         
226         // ----------------------------------
227         
228         /**
229          * @param EditPage $editPage
230          * @param string $newtext
231          * @param string $section
232          * @return bool true if the captcha should run
233          */
234         function shouldCheck( &$editPage, $newtext, $section ) {
235                 $this->trigger = '';
236                 
237                 global $wgUser;
238                 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
239                         wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
240                         return false;
241                 }
242         
243                 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
244                 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
245                         $wgUser->isEmailConfirmed() ) {
246                         wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
247                         return false;
248                 }
249                 
250                 global $wgCaptchaTriggers;
251                 if( !empty( $wgCaptchaTriggers['edit'] ) ) {
252                         // Check on all edits
253                         global $wgUser, $wgTitle;
254                         $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
255                                 $wgUser->getName(),
256                                 $wgTitle->getPrefixedText() );
257                         wfDebug( "ConfirmEdit: checking all edits...\n" );
258                         return true;
259                 }
260                 
261                 if( !empty( $wgCaptchaTriggers['addurl'] ) ) {
262                         // Only check edits that add URLs
263                         $oldtext = $this->loadText( $editPage, $section );
264                         
265                         $oldLinks = $this->findLinks( $oldtext );
266                         $newLinks = $this->findLinks( $newtext );
267                         $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
268                         
269                         $addedLinks = array_diff( $unknownLinks, $oldLinks );
270                         $numLinks = count( $addedLinks );
271                         
272                         if( $numLinks > 0 ) {
273                                 global $wgUser, $wgTitle;
274                                 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
275                                         $numLinks,
276                                         $wgUser->getName(),
277                                         $wgTitle->getPrefixedText(),
278                                         implode( ", ", $addedLinks ) );
279                                 return true;
280                         }
281                 }
282                 
283                 global $wgCaptchaRegexes;
284                 if( !empty( $wgCaptchaRegexes ) ) {
285                         // Custom regex checks
286                         $oldtext = $this->loadText( $editPage, $section );
287                         
288                         foreach( $wgCaptchaRegexes as $regex ) {
289                                 $newMatches = array();
290                                 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
291                                         $oldMatches = array();
292                                         preg_match_all( $regex, $oldtext, $oldMatches );
293                                         
294                                         $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
295                                         
296                                         $numHits = count( $addedMatches );
297                                         if( $numHits > 0 ) {
298                                                 global $wgUser, $wgTitle;
299                                                 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
300                                                         $numHits,
301                                                         $regex,
302                                                         $wgUser->getName(),
303                                                         $wgTitle->getPrefixedText(),
304                                                         implode( ", ", $addedMatches ) );
305                                                 return true;
306                                         }
307                                 }
308                         }
309                 }
310                 
311                 return false;
312         }
313         
314         /**
315          * Filter callback function for URL whitelisting
316          * @return bool true if unknown, false if whitelisted
317          * @access private
318          */
319         function filterLink( $url ) {
320                 global $wgCaptchaWhitelist;
321                 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
322         }
323         
324         /**
325          * The main callback run on edit attempts.
326          * @param EditPage $editPage
327          * @param string $newtext
328          * @param string $section
329          * @param bool true to continue saving, false to abort and show a captcha form
330          */
331         function confirmEdit( &$editPage, $newtext, $section ) {
332                 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
333                         if( $this->passCaptcha() ) {
334                                 return true;
335                         } else {
336                                 $editPage->showEditForm( array( &$this, 'editCallback' ) );
337                                 return false;
338                         }
339                 } else {
340                         wfDebug( "ConfirmEdit: no new links.\n" );
341                         return true;
342                 }
343         }
344         
345         /**
346          * Hook for user creation form submissions.
347          * @param User $u
348          * @param string $message
349          * @return bool true to continue, false to abort user creation
350          */
351         function confirmUserCreate( $u, &$message ) {
352                 global $wgCaptchaTriggers;
353                 if( $wgCaptchaTriggers['createaccount'] ) {
354                         $this->trigger = "new account '" . $u->getName() . "'";
355                         if( !$this->passCaptcha() ) {
356                                 $message = wfMsg( 'captcha-createaccount-fail' );
357                                 return false;
358                         }
359                 }
360                 return true;
361         }
362         
363         /**
364          * Given a required captcha run, test form input for correct
365          * input on the open session.
366          * @return bool if passed, false if failed or new session
367          */
368         function passCaptcha() {
369                 $info = $this->retrieveCaptcha();
370                 if( $info ) {
371                         global $wgRequest;
372                         if( $this->keyMatch( $wgRequest, $info ) ) {
373                                 $this->log( "passed" );
374                                 $this->clearCaptcha( $info );
375                                 return true;
376                         } else {
377                                 $this->clearCaptcha( $info );
378                                 $this->log( "bad form input" );
379                                 return false;
380                         }
381                 } else {
382                         $this->log( "new captcha session" );
383                         return false;
384                 }
385         }
386         
387         /**
388          * Log the status and any triggering info for debugging or statistics
389          * @param string $message
390          */
391         function log( $message ) {
392                 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' .  $this->trigger );
393         }
394         
395         /**
396          * Generate a captcha session ID and save the info in PHP's session storage.
397          * (Requires the user to have cookies enabled to get through the captcha.)
398          *
399          * A random ID is used so legit users can make edits in multiple tabs or
400          * windows without being unnecessarily hobbled by a serial order requirement.
401          * Pass the returned id value into the edit form as wpCaptchaId.
402          *
403          * @param array $info data to store
404          * @return string captcha ID key
405          */
406         function storeCaptcha( $info ) {
407                 if( !isset( $info['index'] ) ) {
408                         // Assign random index if we're not udpating
409                         $info['index'] = strval( mt_rand() );
410                 }
411                 $_SESSION['captcha' . $info['index']] = $info;
412                 return $info['index'];
413         }
414         
415         /**
416          * Fetch this session's captcha info.
417          * @return mixed array of info, or false if missing
418          */
419         function retrieveCaptcha() {
420                 global $wgRequest;
421                 $index = $wgRequest->getVal( 'wpCaptchaId' );
422                 if( isset( $_SESSION['captcha' . $index] ) ) {
423                         return $_SESSION['captcha' . $index];
424                 } else {
425                         return false;
426                 }
427         }
428         
429         /**
430          * Clear out existing captcha info from the session, to ensure
431          * it can't be reused.
432          */
433         function clearCaptcha( $info ) {
434                 unset( $_SESSION['captcha' . $info['index']] );
435         }
436         
437         /**
438          * Retrieve the current version of the page or section being edited...
439          * @param EditPage $editPage
440          * @param string $section
441          * @return string
442          * @access private
443          */
444         function loadText( $editPage, $section ) {
445                 $rev = Revision::newFromTitle( $editPage->mTitle );
446                 if( is_null( $rev ) ) {
447                         return "";
448                 } else {
449                         $text = $rev->getText();
450                         if( $section != '' ) {
451                                 return Article::getSection( $text, $section );
452                         } else {
453                                 return $text;
454                         }
455                 }
456         }
457         
458         /**
459          * Extract a list of all recognized HTTP links in the text.
460          * @param string $text
461          * @return array of strings
462          */
463         function findLinks( $text ) {
464                 global $wgParser, $wgTitle, $wgUser;
465                 
466                 $options = new ParserOptions();
467                 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
468                 $out = $wgParser->parse( $text, $wgTitle, $options );
469                 
470                 return array_keys( $out->getExternalLinks() );
471         }
472         
473         /**
474          * Show a page explaining what this wacky thing is.
475          */
476         function showHelp() {
477                 global $wgOut, $ceAllowConfirmedEmail;
478                 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
479                 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
480         }
481         
482 }
483
484 } # End invocation guard
485
486 ?>