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