Rearrange to work with the user account creation form as well as edits.
[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 {$info['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 getForm() {
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                 return "<p>" . 
81                         wfElement( 'img', array(
82                                 'src'    => $title->getLocalUrl( 'wpCaptchaId=' . urlencode( $index ) ),
83                                 'width'  => $info['width'],
84                                 'height' => $info['height'],
85                                 'alt'    => '' ) ) .
86                         "</p>\n" .
87                         wfElement( 'input', array(
88                                 'type'  => 'hidden',
89                                 'name'  => 'wpCaptchaId',
90                                 'id'    => 'wpCaptchaId',
91                                 'value' => $index ) ) .
92                         "<p>" .
93                         wfElement( 'input', array(
94                                 'name' => 'wpCaptchaWord',
95                                 'id'   => 'wpCaptchaWord',
96                                 'tabindex' => 1 ) ) . // tab in before the edit textarea
97                         "</p>\n";
98         }
99         
100         /**
101          * Select a previously generated captcha image from the queue.
102          * @fixme subject to race conditions if lots of files vanish
103          * @return mixed tuple of (salt key, text hash) or false if no image to find
104          */
105         function pickImage() {
106                 global $wgCaptchaDirectory;
107                 $n = mt_rand( 0, $this->countFiles( $wgCaptchaDirectory ) );
108                 $dir = opendir( $wgCaptchaDirectory );
109                 
110                 $count = 0;
111                 
112                 $entry = readdir( $dir );
113                 $pick = false;
114                 while( false !== $entry ) {
115                         $entry = readdir( $dir );
116                         if( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
117                                 $size = getimagesize( "$wgCaptchaDirectory/$entry" );
118                                 $pick = array(
119                                         'salt' => $matches[1],
120                                         'hash' => $matches[2],
121                                         'width' => $size[0],
122                                         'height' => $size[1],
123                                         'viewed' => false,
124                                 );
125                                 if( $count++ == $n ) {
126                                         break;
127                                 }
128                         }
129                 }
130                 closedir( $dir );
131                 return $pick;
132         }
133         
134         /**
135          * Count the number of files in a directory.
136          * @return int
137          */
138         function countFiles( $dirname ) {
139                 $dir = opendir( $dirname );
140                 $count = 0;
141                 while( false !== ($entry = readdir( $dir ) ) ) {
142                         if( $dir != '.' && $dir != '..' ) {
143                                 $count++;
144                         }
145                 }
146                 closedir( $dir );
147                 return $count;
148         }
149         
150         function showImage() {
151                 global $wgOut, $wgRequest;
152                 global $wgCaptchaDirectory;
153                 
154                 $wgOut->disable();
155                 
156                 $info = $this->retrieveCaptcha();
157                 if( $info ) {
158                         if( $info['viewed'] ) {
159                                 wfHttpError( 403, 'Access Forbidden', "Can't view captcha image a second time." );
160                                 return false;
161                         }
162                         
163                         $info['viewed'] = wfTimestamp();
164                         $this->storeCaptcha( $info );
165                         
166                         $salt = $info['salt'];
167                         $hash = $info['hash'];
168                         $file = $wgCaptchaDirectory . DIRECTORY_SEPARATOR . "image_{$salt}_{$hash}.png";
169                         
170                         if( file_exists( $file ) ) {
171                                 header( 'Content-type: image/png' );
172                                 readfile( $file );
173                                 return true;
174                         }
175                 }
176                 wfHttpError( 500, 'Internal Error', 'Requested bogus captcha image' );
177                 return false;
178         }
179 }
180
181 } # End invocation guard
182
183 ?>