* save each captcha's session data separately, so multiple tabs/windows work
[toast/cookiecaptcha.git] / FancyCaptcha.php
1 <?php
2 /**
3  * Experimental image-based captcha plugin, using images generated by an
4  * external tool.
5  *
6  * Copyright (C) 2005, 2006 Brion Vibber <brion@pobox.com>
7  * http://www.mediawiki.org/
8  *
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.
13  *
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.
18  *
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
23  *
24  * @package MediaWiki
25  * @subpackage Extensions
26  */
27
28 if ( defined( 'MEDIAWIKI' ) ) {
29
30 global $wgCaptchaDirectory;
31 $wgCaptchaDirectory = "$wgUploadDirectory/captcha"; // bad default :D
32
33 global $wgCaptchaSecret;
34 $wgCaptchaSecret = "CHANGE_THIS_SECRET!";
35
36
37 class FancyCaptcha extends SimpleCaptcha {
38         /**
39          * Check if the submitted form matches the captcha session data provided
40          * by the plugin when the form was generated.
41          *
42          * @param WebRequest $request
43          * @param array $info
44          * @return bool
45          */
46         function keyMatch( $request, $info ) {
47                 global $wgCaptchaSecret;
48                 
49                 $answer = $request->getVal( 'wpCaptchaWord' );
50                 $digest = $wgCaptchaSecret . $info['salt'] . $answer . $wgCaptchaSecret . $info['salt'];
51                 $answerHash = substr( md5( $digest ), 0, 16 );
52                 
53                 if( $answerHash == $info['hash'] ) {
54                         wfDebug( "FancyCaptcha: answer hash matches expected $hash\n" );
55                         return true;
56                 } else {
57                         wfDebug( "FancyCaptcha: answer hashes to $answerHash, expected {$info['hash']}\n" );
58                         return false;
59                 }
60         }
61         
62         /**
63          * Insert the captcha prompt into the edit form.
64          */
65         function formCallback( &$out ) {
66                 $info = $this->pickImage();
67                 if( !$info ) {
68                         die( "out of captcha images; this shouldn't happen" );
69                 }
70                 
71                 // Generate a random key for use of this captcha image in this session.
72                 // This is needed so multiple edits in separate tabs or windows can
73                 // go through without extra pain.
74                 $index = $this->storeCaptcha( $info );
75                 
76                 wfDebug( "Captcha id $index using hash ${info['hash']}, salt ${info['salt']}.\n" );
77                 
78                 $title = Title::makeTitle( NS_SPECIAL, 'Captcha/image' );
79                 
80                 $out->addWikiText( wfMsg( "captcha-short" ) );
81                 
82                 $out->addHTML( "<p>" . 
83                         wfElement( 'img', array(
84                                 'src'    => $title->getLocalUrl( 'wpCaptchaId=' . urlencode( $index ) ),
85                                 'width'  => $info['width'],
86                                 'height' => $info['height'],
87                                 'alt'    => '' ) ) .
88                         "</p>\n" .
89                         wfElement( 'input', array(
90                                 'type'  => 'hidden',
91                                 'name'  => 'wpCaptchaId',
92                                 'id'    => 'wpCaptchaId',
93                                 'value' => $index ) ) .
94                         "<p>" .
95                         wfElement( 'input', array(
96                                 'name' => 'wpCaptchaWord',
97                                 'id'   => 'wpCaptchaWord',
98                                 'tabindex' => 1 ) ) . // tab in before the edit textarea
99                         "</p>\n" );
100         }
101         
102         /**
103          * Select a previously generated captcha image from the queue.
104          * @fixme subject to race conditions if lots of files vanish
105          * @return mixed tuple of (salt key, text hash) or false if no image to find
106          */
107         function pickImage() {
108                 global $wgCaptchaDirectory;
109                 $pick = mt_rand( 0, $this->countFiles( $wgCaptchaDirectory ) );
110                 $dir = opendir( $wgCaptchaDirectory );
111                 
112                 $n = mt_rand( 0, 16 );
113                 $count = 0;
114                 
115                 $entry = readdir( $dir );
116                 $pick = false;
117                 while( false !== $entry ) {
118                         $entry = readdir( $dir );
119                         if( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
120                                 $size = getimagesize( "$wgCaptchaDirectory/$entry" );
121                                 $pick = array(
122                                         'salt' => $matches[1],
123                                         'hash' => $matches[2],
124                                         'width' => $size[0],
125                                         'height' => $size[1],
126                                         'viewed' => false,
127                                 );
128                                 if( $count++ == $n ) {
129                                         break;
130                                 }
131                         }
132                 }
133                 closedir( $dir );
134                 return $pick;
135         }
136         
137         /**
138          * Count the number of files in a directory.
139          * @return int
140          */
141         function countFiles( $dirname ) {
142                 $dir = opendir( $dirname );
143                 $count = 0;
144                 while( false !== ($entry = readdir( $dir ) ) ) {
145                         if( $dir != '.' && $dir != '..' ) {
146                                 $count++;
147                         }
148                 }
149                 closedir( $dir );
150                 return $count;
151         }
152         
153         function showImage() {
154                 global $wgOut, $wgRequest;
155                 global $wgCaptchaDirectory;
156                 
157                 $wgOut->disable();
158                 
159                 $info = $this->retrieveCaptcha();
160                 if( $info ) {
161                         if( $info['viewed'] ) {
162                                 wfHttpError( 403, 'Access Forbidden', "Can't view captcha image a second time." );
163                                 return false;
164                         }
165                         
166                         $info['viewed'] = wfTimestamp();
167                         $this->storeCaptcha( $info, $info['index'] );
168                         
169                         $salt = $info['salt'];
170                         $hash = $info['hash'];
171                         $file = $wgCaptchaDirectory . DIRECTORY_SEPARATOR . "image_{$salt}_{$hash}.png";
172                         
173                         if( file_exists( $file ) ) {
174                                 header( 'Content-type: image/png' );
175                                 readfile( $file );
176                                 return true;
177                         }
178                 }
179                 wfHttpError( 500, 'Internal Error', 'Requested bogus captcha image' );
180                 return false;
181         }
182 }
183
184 } # End invocation guard
185
186 ?>