Forgot to clear used captcha info from the session after answering.
[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                 $n = mt_rand( 0, $this->countFiles( $wgCaptchaDirectory ) );
110                 $dir = opendir( $wgCaptchaDirectory );
111                 
112                 $count = 0;
113                 
114                 $entry = readdir( $dir );
115                 $pick = false;
116                 while( false !== $entry ) {
117                         $entry = readdir( $dir );
118                         if( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
119                                 $size = getimagesize( "$wgCaptchaDirectory/$entry" );
120                                 $pick = array(
121                                         'salt' => $matches[1],
122                                         'hash' => $matches[2],
123                                         'width' => $size[0],
124                                         'height' => $size[1],
125                                         'viewed' => false,
126                                 );
127                                 if( $count++ == $n ) {
128                                         break;
129                                 }
130                         }
131                 }
132                 closedir( $dir );
133                 return $pick;
134         }
135         
136         /**
137          * Count the number of files in a directory.
138          * @return int
139          */
140         function countFiles( $dirname ) {
141                 $dir = opendir( $dirname );
142                 $count = 0;
143                 while( false !== ($entry = readdir( $dir ) ) ) {
144                         if( $dir != '.' && $dir != '..' ) {
145                                 $count++;
146                         }
147                 }
148                 closedir( $dir );
149                 return $count;
150         }
151         
152         function showImage() {
153                 global $wgOut, $wgRequest;
154                 global $wgCaptchaDirectory;
155                 
156                 $wgOut->disable();
157                 
158                 $info = $this->retrieveCaptcha();
159                 if( $info ) {
160                         if( $info['viewed'] ) {
161                                 wfHttpError( 403, 'Access Forbidden', "Can't view captcha image a second time." );
162                                 return false;
163                         }
164                         
165                         $info['viewed'] = wfTimestamp();
166                         $this->storeCaptcha( $info );
167                         
168                         $salt = $info['salt'];
169                         $hash = $info['hash'];
170                         $file = $wgCaptchaDirectory . DIRECTORY_SEPARATOR . "image_{$salt}_{$hash}.png";
171                         
172                         if( file_exists( $file ) ) {
173                                 header( 'Content-type: image/png' );
174                                 readfile( $file );
175                                 return true;
176                         }
177                 }
178                 wfHttpError( 500, 'Internal Error', 'Requested bogus captcha image' );
179                 return false;
180         }
181 }
182
183 } # End invocation guard
184
185 ?>