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