]> ToastFreeware Gitweb - toast/cookiecaptcha.git/blob - ConfirmEdit.php
(bug 8484) Provide a getMessage() method that individual captcha plugins can use...
[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 $lang => $messages )
112                 $wgMessageCache->addMessages( $messages, $lang );
113         
114         global $wgHooks, $wgCaptcha, $wgCaptchaClass, $wgSpecialPages;
115         $wgCaptcha = new $wgCaptchaClass();
116         $wgHooks['EditFilter'][] = array( &$wgCaptcha, 'confirmEdit' );
117         
118         $wgHooks['UserCreateForm'][] = array( &$wgCaptcha, 'injectUserCreate' );
119         $wgHooks['AbortNewAccount'][] = array( &$wgCaptcha, 'confirmUserCreate' );
120 }
121
122 /**
123  * Entry point for Special:Captcha
124  */
125 function wfSpecialCaptcha( $par = null ) {
126         global $wgCaptcha;
127         switch( $par ) {
128         case "image":
129                 return $wgCaptcha->showImage();
130         case "help":
131         default:
132                 return $wgCaptcha->showHelp();
133         }
134 }
135
136 class SimpleCaptcha {
137         /**
138          * Insert a captcha prompt into the edit form.
139          * This sample implementation generates a simple arithmetic operation;
140          * it would be easy to defeat by machine.
141          *
142          * Override this!
143          *
144          * @return string HTML
145          */
146         function getForm() {
147                 $a = mt_rand(0, 100);
148                 $b = mt_rand(0, 10);
149                 $op = mt_rand(0, 1) ? '+' : '-';
150                 
151                 $test = "$a $op $b";
152                 $answer = ($op == '+') ? ($a + $b) : ($a - $b);
153                 
154                 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
155                 
156                 return "<p><label for=\"wpCaptchaWord\">$test</label> = " .
157                         wfElement( 'input', array(
158                                 'name' => 'wpCaptchaWord',
159                                 'id'   => 'wpCaptchaWord',
160                                 'tabindex' => 1 ) ) . // tab in before the edit textarea
161                         "</p>\n" .
162                         wfElement( 'input', array(
163                                 'type'  => 'hidden',
164                                 'name'  => 'wpCaptchaId',
165                                 'id'    => 'wpCaptchaId',
166                                 'value' => $index ) );
167         }
168         
169         /**
170          * Insert the captcha prompt into an edit form.
171          * @param OutputPage $out
172          */
173         function editCallback( &$out ) {
174                 $out->addWikiText( $this->getMessage( 'edit' ) );
175                 $out->addHTML( $this->getForm() );
176         }
177         
178         /**
179          * Show a message asking the user to enter a captcha on edit
180          * The result will be treated as wiki text
181          *
182          * @param $action Action being performed
183          * @return string
184          */
185         function getMessage( $action ) {
186                 $name = 'captcha-' . $action;
187                 $text = wfMsg( $name );
188                 # Obtain a more tailored message, if possible, otherwise, fall back to
189                 # the default for edits
190                 return wfEmptyMsg( $name, $text ) ? wfMsg( 'captcha-edit' ) : $text;
191         }
192         
193         /**
194          * Inject whazawhoo
195          * @fixme if multiple thingies insert a header, could break
196          * @param SimpleTemplate $template
197          * @return bool true to keep running callbacks
198          */
199         function injectUserCreate( &$template ) {
200                 global $wgCaptchaTriggers, $wgOut;
201                 if( $wgCaptchaTriggers['createaccount'] ) {
202                         $template->set( 'header',
203                                 "<div class='captcha'>" .
204                                 $wgOut->parse( $this->getMessage( 'createaccount' ) ) .
205                                 $this->getForm() .
206                                 "</div>\n" );
207                 }
208                 return true;
209         }
210         
211         /**
212          * Check if the submitted form matches the captcha session data provided
213          * by the plugin when the form was generated.
214          *
215          * Override this!
216          *
217          * @param WebRequest $request
218          * @param array $info
219          * @return bool
220          */
221         function keyMatch( $request, $info ) {
222                 return $request->getVal( 'wpCaptchaWord' ) == $info['answer'];
223         }
224         
225         // ----------------------------------
226         
227         /**
228          * @param EditPage $editPage
229          * @param string $newtext
230          * @param string $section
231          * @return bool true if the captcha should run
232          */
233         function shouldCheck( &$editPage, $newtext, $section ) {
234                 $this->trigger = '';
235                 
236                 global $wgUser;
237                 if( $wgUser->isAllowed( 'skipcaptcha' ) ) {
238                         wfDebug( "ConfirmEdit: user group allows skipping captcha\n" );
239                         return false;
240                 }
241         
242                 global $wgEmailAuthentication, $ceAllowConfirmedEmail;
243                 if( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
244                         $wgUser->isEmailConfirmed() ) {
245                         wfDebug( "ConfirmEdit: user has confirmed mail, skipping captcha\n" );
246                         return false;
247                 }
248                 
249                 global $wgCaptchaTriggers;
250                 if( !empty( $wgCaptchaTriggers['edit'] ) ) {
251                         // Check on all edits
252                         global $wgUser, $wgTitle;
253                         $this->trigger = sprintf( "edit trigger by '%s' at [[%s]]",
254                                 $wgUser->getName(),
255                                 $wgTitle->getPrefixedText() );
256                         wfDebug( "ConfirmEdit: checking all edits...\n" );
257                         return true;
258                 }
259                 
260                 if( !empty( $wgCaptchaTriggers['addurl'] ) ) {
261                         // Only check edits that add URLs
262                         $oldtext = $this->loadText( $editPage, $section );
263                         
264                         $oldLinks = $this->findLinks( $oldtext );
265                         $newLinks = $this->findLinks( $newtext );
266                         $unknownLinks = array_filter( $newLinks, array( &$this, 'filterLink' ) );
267                         
268                         $addedLinks = array_diff( $unknownLinks, $oldLinks );
269                         $numLinks = count( $addedLinks );
270                         
271                         if( $numLinks > 0 ) {
272                                 global $wgUser, $wgTitle;
273                                 $this->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
274                                         $numLinks,
275                                         $wgUser->getName(),
276                                         $wgTitle->getPrefixedText(),
277                                         implode( ", ", $addedLinks ) );
278                                 return true;
279                         }
280                 }
281                 
282                 global $wgCaptchaRegexes;
283                 if( !empty( $wgCaptchaRegexes ) ) {
284                         // Custom regex checks
285                         $oldtext = $this->loadText( $editPage, $section );
286                         
287                         foreach( $wgCaptchaRegexes as $regex ) {
288                                 $newMatches = array();
289                                 if( preg_match_all( $regex, $newtext, $newMatches ) ) {
290                                         $oldMatches = array();
291                                         preg_match_all( $regex, $oldtext, $oldMatches );
292                                         
293                                         $addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
294                                         
295                                         $numHits = count( $addedMatches );
296                                         if( $numHits > 0 ) {
297                                                 global $wgUser, $wgTitle;
298                                                 $this->trigger = sprintf( "%dx %s at [[%s]]: %s",
299                                                         $numHits,
300                                                         $regex,
301                                                         $wgUser->getName(),
302                                                         $wgTitle->getPrefixedText(),
303                                                         implode( ", ", $addedMatches ) );
304                                                 return true;
305                                         }
306                                 }
307                         }
308                 }
309                 
310                 return false;
311         }
312         
313         /**
314          * Filter callback function for URL whitelisting
315          * @return bool true if unknown, false if whitelisted
316          * @access private
317          */
318         function filterLink( $url ) {
319                 global $wgCaptchaWhitelist;
320                 return !( $wgCaptchaWhitelist && preg_match( $wgCaptchaWhitelist, $url ) );
321         }
322         
323         /**
324          * The main callback run on edit attempts.
325          * @param EditPage $editPage
326          * @param string $newtext
327          * @param string $section
328          * @param bool true to continue saving, false to abort and show a captcha form
329          */
330         function confirmEdit( &$editPage, $newtext, $section ) {
331                 if( $this->shouldCheck( $editPage, $newtext, $section ) ) {
332                         if( $this->passCaptcha() ) {
333                                 return true;
334                         } else {
335                                 $editPage->showEditForm( array( &$this, 'editCallback' ) );
336                                 return false;
337                         }
338                 } else {
339                         wfDebug( "ConfirmEdit: no new links.\n" );
340                         return true;
341                 }
342         }
343         
344         /**
345          * Hook for user creation form submissions.
346          * @param User $u
347          * @param string $message
348          * @return bool true to continue, false to abort user creation
349          */
350         function confirmUserCreate( $u, &$message ) {
351                 global $wgCaptchaTriggers;
352                 if( $wgCaptchaTriggers['createaccount'] ) {
353                         $this->trigger = "new account '" . $u->getName() . "'";
354                         if( !$this->passCaptcha() ) {
355                                 $message = wfMsg( 'captcha-createaccount-fail' );
356                                 return false;
357                         }
358                 }
359                 return true;
360         }
361         
362         /**
363          * Given a required captcha run, test form input for correct
364          * input on the open session.
365          * @return bool if passed, false if failed or new session
366          */
367         function passCaptcha() {
368                 $info = $this->retrieveCaptcha();
369                 if( $info ) {
370                         global $wgRequest;
371                         if( $this->keyMatch( $wgRequest, $info ) ) {
372                                 $this->log( "passed" );
373                                 $this->clearCaptcha( $info );
374                                 return true;
375                         } else {
376                                 $this->clearCaptcha( $info );
377                                 $this->log( "bad form input" );
378                                 return false;
379                         }
380                 } else {
381                         $this->log( "new captcha session" );
382                         return false;
383                 }
384         }
385         
386         /**
387          * Log the status and any triggering info for debugging or statistics
388          * @param string $message
389          */
390         function log( $message ) {
391                 wfDebugLog( 'captcha', 'ConfirmEdit: ' . $message . '; ' .  $this->trigger );
392         }
393         
394         /**
395          * Generate a captcha session ID and save the info in PHP's session storage.
396          * (Requires the user to have cookies enabled to get through the captcha.)
397          *
398          * A random ID is used so legit users can make edits in multiple tabs or
399          * windows without being unnecessarily hobbled by a serial order requirement.
400          * Pass the returned id value into the edit form as wpCaptchaId.
401          *
402          * @param array $info data to store
403          * @return string captcha ID key
404          */
405         function storeCaptcha( $info ) {
406                 if( !isset( $info['index'] ) ) {
407                         // Assign random index if we're not udpating
408                         $info['index'] = strval( mt_rand() );
409                 }
410                 $_SESSION['captcha' . $info['index']] = $info;
411                 return $info['index'];
412         }
413         
414         /**
415          * Fetch this session's captcha info.
416          * @return mixed array of info, or false if missing
417          */
418         function retrieveCaptcha() {
419                 global $wgRequest;
420                 $index = $wgRequest->getVal( 'wpCaptchaId' );
421                 if( isset( $_SESSION['captcha' . $index] ) ) {
422                         return $_SESSION['captcha' . $index];
423                 } else {
424                         return false;
425                 }
426         }
427         
428         /**
429          * Clear out existing captcha info from the session, to ensure
430          * it can't be reused.
431          */
432         function clearCaptcha( $info ) {
433                 unset( $_SESSION['captcha' . $info['index']] );
434         }
435         
436         /**
437          * Retrieve the current version of the page or section being edited...
438          * @param EditPage $editPage
439          * @param string $section
440          * @return string
441          * @access private
442          */
443         function loadText( $editPage, $section ) {
444                 $rev = Revision::newFromTitle( $editPage->mTitle );
445                 if( is_null( $rev ) ) {
446                         return "";
447                 } else {
448                         $text = $rev->getText();
449                         if( $section != '' ) {
450                                 return Article::getSection( $text, $section );
451                         } else {
452                                 return $text;
453                         }
454                 }
455         }
456         
457         /**
458          * Extract a list of all recognized HTTP links in the text.
459          * @param string $text
460          * @return array of strings
461          */
462         function findLinks( $text ) {
463                 global $wgParser, $wgTitle, $wgUser;
464                 
465                 $options = new ParserOptions();
466                 $text = $wgParser->preSaveTransform( $text, $wgTitle, $wgUser, $options );
467                 $out = $wgParser->parse( $text, $wgTitle, $options );
468                 
469                 return array_keys( $out->getExternalLinks() );
470         }
471         
472         /**
473          * Show a page explaining what this wacky thing is.
474          */
475         function showHelp() {
476                 global $wgOut, $ceAllowConfirmedEmail;
477                 $wgOut->setPageTitle( wfMsg( 'captchahelp-title' ) );
478                 $wgOut->addWikiText( wfMsg( 'captchahelp-text' ) );
479         }
480         
481 }
482
483 } # End invocation guard
484
485 ?>