* (bug 33366) ConfirmEdit: Disable autocorrect, autocapitalize on FancyCaptcha's...
[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                                 'autocorrect' => 'off',
76                                 'autocapitalize' => 'off',
77                                 'required',
78                                 'tabindex' => 1 ) ) . // tab in before the edit textarea
79                         "</p>\n";
80         }
81
82         /**
83          * Select a previously generated captcha image from the queue.
84          * @fixme subject to race conditions if lots of files vanish
85          * @return mixed tuple of (salt key, text hash) or false if no image to find
86          */
87         function pickImage() {
88                 global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
89                 return $this->pickImageDir(
90                         $wgCaptchaDirectory,
91                         $wgCaptchaDirectoryLevels );
92         }
93
94         function pickImageDir( $directory, $levels ) {
95                 if ( $levels ) {
96                         $dirs = array();
97
98                         // Check which subdirs are actually present...
99                         $dir = opendir( $directory );
100                         while ( false !== ( $entry = readdir( $dir ) ) ) {
101                                 if ( ctype_xdigit( $entry ) && strlen( $entry ) == 1 ) {
102                                         $dirs[] = $entry;
103                                 }
104                         }
105                         closedir( $dir );
106
107                         $place = mt_rand( 0, count( $dirs ) - 1 );
108                         // In case all dirs are not filled,
109                         // cycle through next digits...
110                         for ( $j = 0; $j < count( $dirs ); $j++ ) {
111                                 $char = $dirs[( $place + $j ) % count( $dirs )];
112                                 $return = $this->pickImageDir( "$directory/$char", $levels - 1 );
113                                 if ( $return ) {
114                                         return $return;
115                                 }
116                         }
117                         // Didn't find any images in this directory... empty?
118                         return false;
119                 } else {
120                         return $this->pickImageFromDir( $directory );
121                 }
122         }
123
124         function pickImageFromDir( $directory ) {
125                 if ( !is_dir( $directory ) ) {
126                         return false;
127                 }
128                 $n = mt_rand( 0, $this->countFiles( $directory ) - 1 );
129                 $dir = opendir( $directory );
130
131                 $count = 0;
132
133                 $entry = readdir( $dir );
134                 $pick = false;
135                 while ( false !== $entry ) {
136                         $entry = readdir( $dir );
137                         if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
138                                 $size = getimagesize( "$directory/$entry" );
139                                 $pick = array(
140                                         'salt' => $matches[1],
141                                         'hash' => $matches[2],
142                                         'width' => $size[0],
143                                         'height' => $size[1],
144                                         'viewed' => false,
145                                 );
146                                 if ( $count++ == $n ) {
147                                         break;
148                                 }
149                         }
150                 }
151                 closedir( $dir );
152                 return $pick;
153         }
154
155         /**
156          * Count the number of files in a directory.
157          * @return int
158          */
159         function countFiles( $dirname ) {
160                 $dir = opendir( $dirname );
161                 $count = 0;
162                 while ( false !== ( $entry = readdir( $dir ) ) ) {
163                         if ( $entry != '.' && $entry != '..' ) {
164                                 $count++;
165                         }
166                 }
167                 closedir( $dir );
168                 return $count;
169         }
170
171         function showImage() {
172                 global $wgOut;
173
174                 $wgOut->disable();
175
176                 $info = $this->retrieveCaptcha();
177                 if ( $info ) {
178                         /*
179                         // Be a little less restrictive for now; in at least some circumstances,
180                         // Konqueror tries to reload the image even if you haven't navigated
181                         // away from the page.
182                         if( $info['viewed'] ) {
183                                 wfHttpError( 403, 'Access Forbidden', "Can't view captcha image a second time." );
184                                 return false;
185                         }
186                         */
187
188                         $info['viewed'] = wfTimestamp();
189                         $this->storeCaptcha( $info );
190
191                         $salt = $info['salt'];
192                         $hash = $info['hash'];
193                         $file = $this->imagePath( $salt, $hash );
194
195                         if ( file_exists( $file ) ) {
196                                 global $IP;
197                                 require_once "$IP/includes/StreamFile.php";
198                                 header( "Cache-Control: private, s-maxage=0, max-age=3600" );
199                                 wfStreamFile( $file );
200                                 return true;
201                         }
202                 }
203                 wfHttpError( 500, 'Internal Error', 'Requested bogus captcha image' );
204                 return false;
205         }
206
207         function imagePath( $salt, $hash ) {
208                 global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
209                 $file = $wgCaptchaDirectory;
210                 $file .= DIRECTORY_SEPARATOR;
211                 for ( $i = 0; $i < $wgCaptchaDirectoryLevels; $i++ ) {
212                         $file .= $hash { $i } ;
213                         $file .= DIRECTORY_SEPARATOR;
214                 }
215                 $file .= "image_{$salt}_{$hash}.png";
216                 return $file;
217         }
218
219         /**
220          * Show a message asking the user to enter a captcha on edit
221          * The result will be treated as wiki text
222          *
223          * @param $action Action being performed
224          * @return string
225          */
226         function getMessage( $action ) {
227                 $name = 'fancycaptcha-' . $action;
228                 $text = wfMsg( $name );
229                 # Obtain a more tailored message, if possible, otherwise, fall back to
230                 # the default for edits
231                 return wfEmptyMsg( $name, $text ) ? wfMsg( 'fancycaptcha-edit' ) : $text;
232         }
233
234         /**
235          * Delete a solved captcha image, if $wgCaptchaDeleteOnSolve is true.
236          */
237         function passCaptcha() {
238                 global $wgCaptchaDeleteOnSolve;
239
240                 $info = $this->retrieveCaptcha(); // get the captcha info before it gets deleted
241                 $pass = parent::passCaptcha();
242
243                 if ( $pass && $wgCaptchaDeleteOnSolve ) {
244                         $filename = $this->imagePath( $info['salt'], $info['hash'] );
245                         if ( file_exists( $filename ) ) {
246                                 unlink( $filename );
247                         }
248                 }
249
250                 return $pass;
251         }
252 }