3 * Experimental image-based captcha plugin, using images generated by an
6 * Copyright (C) 2005, 2006 Brion Vibber <brion@pobox.com>
7 * http://www.mediawiki.org/
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 * http://www.gnu.org/copyleft/gpl.html
24 * @addtogroup Extensions
27 if ( defined( 'MEDIAWIKI' ) ) {
29 global $wgCaptchaDirectory;
30 $wgCaptchaDirectory = "$wgUploadDirectory/captcha"; // bad default :D
32 global $wgCaptchaDirectoryLevels;
33 $wgCaptchaDirectoryLevels = 0; // To break into subdirectories
35 global $wgCaptchaSecret;
36 $wgCaptchaSecret = "CHANGE_THIS_SECRET!";
38 $wgExtensionFunctions[] = 'efFancyCaptcha';
40 function efFancyCaptcha() {
41 global $wgMessageCache;
42 require_once( dirname( __FILE__ ) . '/FancyCaptcha.i18n.php' );
43 foreach( efFancyCaptchaMessages() as $lang => $messages )
44 $wgMessageCache->addMessages( $messages, $lang );
47 class FancyCaptcha extends SimpleCaptcha {
49 * Check if the submitted form matches the captcha session data provided
50 * by the plugin when the form was generated.
52 * @param WebRequest $request
56 function keyMatch( $request, $info ) {
57 global $wgCaptchaSecret;
59 $answer = $request->getVal( 'wpCaptchaWord' );
60 $digest = $wgCaptchaSecret . $info['salt'] . $answer . $wgCaptchaSecret . $info['salt'];
61 $answerHash = substr( md5( $digest ), 0, 16 );
63 if( $answerHash == $info['hash'] ) {
64 wfDebug( "FancyCaptcha: answer hash matches expected {$info['hash']}\n" );
67 wfDebug( "FancyCaptcha: answer hashes to $answerHash, expected {$info['hash']}\n" );
73 * Insert the captcha prompt into the edit form.
76 $info = $this->pickImage();
78 die( "out of captcha images; this shouldn't happen" );
81 // Generate a random key for use of this captcha image in this session.
82 // This is needed so multiple edits in separate tabs or windows can
83 // go through without extra pain.
84 $index = $this->storeCaptcha( $info );
86 wfDebug( "Captcha id $index using hash ${info['hash']}, salt ${info['salt']}.\n" );
88 $title = Title::makeTitle( NS_SPECIAL, 'Captcha/image' );
91 wfElement( 'img', array(
92 'src' => $title->getLocalUrl( 'wpCaptchaId=' . urlencode( $index ) ),
93 'width' => $info['width'],
94 'height' => $info['height'],
97 wfElement( 'input', array(
99 'name' => 'wpCaptchaId',
100 'id' => 'wpCaptchaId',
101 'value' => $index ) ) .
103 wfElement( 'input', array(
104 'name' => 'wpCaptchaWord',
105 'id' => 'wpCaptchaWord',
106 'tabindex' => 1 ) ) . // tab in before the edit textarea
111 * Select a previously generated captcha image from the queue.
112 * @fixme subject to race conditions if lots of files vanish
113 * @return mixed tuple of (salt key, text hash) or false if no image to find
115 function pickImage() {
116 global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
117 return $this->pickImageDir(
119 $wgCaptchaDirectoryLevels );
122 function pickImageDir( $directory, $levels ) {
126 // Check which subdirs are actually present...
127 $dir = opendir( $directory );
128 while( false !== ($entry = readdir( $dir ) ) ) {
129 if( ctype_xdigit( $entry ) && strlen( $entry ) == 1 ) {
135 $place = mt_rand( 0, count( $dirs ) - 1 );
136 // In case all dirs are not filled,
137 // cycle through next digits...
138 for( $j = 0; $j < count( $dirs ); $j++ ) {
139 $char = $dirs[($place + $j) % count( $dirs )];
140 $return = $this->pickImageDir( "$directory/$char", $levels - 1 );
145 // Didn't find any images in this directory... empty?
148 return $this->pickImageFromDir( $directory );
152 function pickImageFromDir( $directory ) {
153 if( !is_dir( $directory ) ) {
156 $n = mt_rand( 0, $this->countFiles( $directory ) - 1 );
157 $dir = opendir( $directory );
161 $entry = readdir( $dir );
163 while( false !== $entry ) {
164 $entry = readdir( $dir );
165 if( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
166 $size = getimagesize( "$directory/$entry" );
168 'salt' => $matches[1],
169 'hash' => $matches[2],
171 'height' => $size[1],
174 if( $count++ == $n ) {
184 * Count the number of files in a directory.
187 function countFiles( $dirname ) {
188 $dir = opendir( $dirname );
190 while( false !== ($entry = readdir( $dir ) ) ) {
191 if( $entry != '.' && $entry != '..' ) {
199 function showImage() {
200 global $wgOut, $wgRequest;
204 $info = $this->retrieveCaptcha();
206 if( $info['viewed'] ) {
207 wfHttpError( 403, 'Access Forbidden', "Can't view captcha image a second time." );
211 $info['viewed'] = wfTimestamp();
212 $this->storeCaptcha( $info );
214 $salt = $info['salt'];
215 $hash = $info['hash'];
216 $file = $this->imagePath( $salt, $hash );
218 if( file_exists( $file ) ) {
220 require_once "$IP/includes/StreamFile.php";
221 wfStreamFile( $file );
225 wfHttpError( 500, 'Internal Error', 'Requested bogus captcha image' );
229 function imagePath( $salt, $hash ) {
230 global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
231 $file = $wgCaptchaDirectory;
232 $file .= DIRECTORY_SEPARATOR;
233 for( $i = 0; $i < $wgCaptchaDirectoryLevels; $i++ ) {
235 $file .= DIRECTORY_SEPARATOR;
237 $file .= "image_{$salt}_{$hash}.png";
242 * Show a message asking the user to enter a captcha on edit
243 * The result will be treated as wiki text
245 * @param $action Action being performed
248 function getMessage( $action ) {
249 $name = 'fancycaptcha-' . $action;
250 $text = wfMsg( $name );
251 # Obtain a more tailored message, if possible, otherwise, fall back to
252 # the default for edits
253 return wfEmptyMsg( $name, $text ) ? wfMsg( 'fancycaptcha-edit' ) : $text;
258 } # End invocation guard