Add required attribute to captcha answers per
[toast/cookiecaptcha.git] / FancyCaptcha.class.php
1 <?php
2
3 class FancyCaptcha extends SimpleCaptcha {
4         /**
5          * Check if the submitted form matches the captcha session data provided
6          * by the plugin when the form was generated.
7          *
8          * @param string $answer
9          * @param array $info
10          * @return bool
11          */
12         function keyMatch( $answer, $info ) {
13                 global $wgCaptchaSecret;
14
15                 $digest = $wgCaptchaSecret . $info['salt'] . $answer . $wgCaptchaSecret . $info['salt'];
16                 $answerHash = substr( md5( $digest ), 0, 16 );
17
18                 if ( $answerHash == $info['hash'] ) {
19                         wfDebug( "FancyCaptcha: answer hash matches expected {$info['hash']}\n" );
20                         return true;
21                 } else {
22                         wfDebug( "FancyCaptcha: answer hashes to $answerHash, expected {$info['hash']}\n" );
23                         return false;
24                 }
25         }
26
27         function addCaptchaAPI( &$resultArr ) {
28                 $info = $this->pickImage();
29                 if ( !$info ) {
30                         $resultArr['captcha']['error'] = 'Out of images';
31                         return;
32                 }
33                 $index = $this->storeCaptcha( $info );
34                 $title = SpecialPage::getTitleFor( 'Captcha', 'image' );
35                 $resultArr['captcha']['type'] = 'image';
36                 $resultArr['captcha']['mime'] = 'image/png';
37                 $resultArr['captcha']['id'] = $index;
38                 $resultArr['captcha']['url'] = $title->getLocalUrl( 'wpCaptchaId=' . urlencode( $index ) );
39         }
40
41         /**
42          * Insert the captcha prompt into the edit form.
43          */
44         function getForm() {
45                 $info = $this->pickImage();
46                 if ( !$info ) {
47                         throw new MWException( "Ran out of captcha images" );
48                 }
49
50                 // Generate a random key for use of this captcha image in this session.
51                 // This is needed so multiple edits in separate tabs or windows can
52                 // go through without extra pain.
53                 $index = $this->storeCaptcha( $info );
54
55                 wfDebug( "Captcha id $index using hash ${info['hash']}, salt ${info['salt']}.\n" );
56
57                 $title = SpecialPage::getTitleFor( 'Captcha', 'image' );
58
59                 return "<p>" .
60                         Xml::element( 'img', array(
61                                 'src'    => $title->getLocalUrl( 'wpCaptchaId=' . urlencode( $index ) ),
62                                 'width'  => $info['width'],
63                                 'height' => $info['height'],
64                                 'alt'    => '' ) ) .
65                         "</p>\n" .
66                         Xml::element( 'input', array(
67                                 'type'  => 'hidden',
68                                 'name'  => 'wpCaptchaId',
69                                 'id'    => 'wpCaptchaId',
70                                 'value' => $index ) ) .
71                         "<p>" .
72                         Html::element( 'input', array(
73                                 'name' => 'wpCaptchaWord',
74                                 'id'   => 'wpCaptchaWord',
75                                 'required',
76                                 'tabindex' => 1 ) ) . // tab in before the edit textarea
77                         "</p>\n";
78         }
79
80         /**
81          * Select a previously generated captcha image from the queue.
82          * @fixme subject to race conditions if lots of files vanish
83          * @return mixed tuple of (salt key, text hash) or false if no image to find
84          */
85         function pickImage() {
86                 global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
87                 return $this->pickImageDir(
88                         $wgCaptchaDirectory,
89                         $wgCaptchaDirectoryLevels );
90         }
91
92         function pickImageDir( $directory, $levels ) {
93                 if ( $levels ) {
94                         $dirs = array();
95
96                         // Check which subdirs are actually present...
97                         $dir = opendir( $directory );
98                         while ( false !== ( $entry = readdir( $dir ) ) ) {
99                                 if ( ctype_xdigit( $entry ) && strlen( $entry ) == 1 ) {
100                                         $dirs[] = $entry;
101                                 }
102                         }
103                         closedir( $dir );
104
105                         $place = mt_rand( 0, count( $dirs ) - 1 );
106                         // In case all dirs are not filled,
107                         // cycle through next digits...
108                         for ( $j = 0; $j < count( $dirs ); $j++ ) {
109                                 $char = $dirs[( $place + $j ) % count( $dirs )];
110                                 $return = $this->pickImageDir( "$directory/$char", $levels - 1 );
111                                 if ( $return ) {
112                                         return $return;
113                                 }
114                         }
115                         // Didn't find any images in this directory... empty?
116                         return false;
117                 } else {
118                         return $this->pickImageFromDir( $directory );
119                 }
120         }
121
122         function pickImageFromDir( $directory ) {
123                 if ( !is_dir( $directory ) ) {
124                         return false;
125                 }
126                 $n = mt_rand( 0, $this->countFiles( $directory ) - 1 );
127                 $dir = opendir( $directory );
128
129                 $count = 0;
130
131                 $entry = readdir( $dir );
132                 $pick = false;
133                 while ( false !== $entry ) {
134                         $entry = readdir( $dir );
135                         if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
136                                 $size = getimagesize( "$directory/$entry" );
137                                 $pick = array(
138                                         'salt' => $matches[1],
139                                         'hash' => $matches[2],
140                                         'width' => $size[0],
141                                         'height' => $size[1],
142                                         'viewed' => false,
143                                 );
144                                 if ( $count++ == $n ) {
145                                         break;
146                                 }
147                         }
148                 }
149                 closedir( $dir );
150                 return $pick;
151         }
152
153         /**
154          * Count the number of files in a directory.
155          * @return int
156          */
157         function countFiles( $dirname ) {
158                 $dir = opendir( $dirname );
159                 $count = 0;
160                 while ( false !== ( $entry = readdir( $dir ) ) ) {
161                         if ( $entry != '.' && $entry != '..' ) {
162                                 $count++;
163                         }
164                 }
165                 closedir( $dir );
166                 return $count;
167         }
168
169         function showImage() {
170                 global $wgOut;
171
172                 $wgOut->disable();
173
174                 $info = $this->retrieveCaptcha();
175                 if ( $info ) {
176                         /*
177                         // Be a little less restrictive for now; in at least some circumstances,
178                         // Konqueror tries to reload the image even if you haven't navigated
179                         // away from the page.
180                         if( $info['viewed'] ) {
181                                 wfHttpError( 403, 'Access Forbidden', "Can't view captcha image a second time." );
182                                 return false;
183                         }
184                         */
185
186                         $info['viewed'] = wfTimestamp();
187                         $this->storeCaptcha( $info );
188
189                         $salt = $info['salt'];
190                         $hash = $info['hash'];
191                         $file = $this->imagePath( $salt, $hash );
192
193                         if ( file_exists( $file ) ) {
194                                 global $IP;
195                                 require_once "$IP/includes/StreamFile.php";
196                                 header( "Cache-Control: private, s-maxage=0, max-age=3600" );
197                                 wfStreamFile( $file );
198                                 return true;
199                         }
200                 }
201                 wfHttpError( 500, 'Internal Error', 'Requested bogus captcha image' );
202                 return false;
203         }
204
205         function imagePath( $salt, $hash ) {
206                 global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
207                 $file = $wgCaptchaDirectory;
208                 $file .= DIRECTORY_SEPARATOR;
209                 for ( $i = 0; $i < $wgCaptchaDirectoryLevels; $i++ ) {
210                         $file .= $hash { $i } ;
211                         $file .= DIRECTORY_SEPARATOR;
212                 }
213                 $file .= "image_{$salt}_{$hash}.png";
214                 return $file;
215         }
216
217         /**
218          * Show a message asking the user to enter a captcha on edit
219          * The result will be treated as wiki text
220          *
221          * @param $action Action being performed
222          * @return string
223          */
224         function getMessage( $action ) {
225                 $name = 'fancycaptcha-' . $action;
226                 $text = wfMsg( $name );
227                 # Obtain a more tailored message, if possible, otherwise, fall back to
228                 # the default for edits
229                 return wfEmptyMsg( $name, $text ) ? wfMsg( 'fancycaptcha-edit' ) : $text;
230         }
231
232         /**
233          * Delete a solved captcha image, if $wgCaptchaDeleteOnSolve is true.
234          */
235         function passCaptcha() {
236                 global $wgCaptchaDeleteOnSolve;
237
238                 $info = $this->retrieveCaptcha(); // get the captcha info before it gets deleted
239                 $pass = parent::passCaptcha();
240
241                 if ( $pass && $wgCaptchaDeleteOnSolve ) {
242                         $filename = $this->imagePath( $info['salt'], $info['hash'] );
243                         if ( file_exists( $filename ) ) {
244                                 unlink( $filename );
245                         }
246                 }
247
248                 return $pass;
249         }
250 }