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