c6ee03c6ddf76b155bc8c1cd8c88a2162c7cf276
[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                 $n = mt_rand( 0, $this->countFiles( $directory ) - 1 );
136                 $dir = opendir( $directory );
137
138                 $count = 0;
139
140                 $entry = readdir( $dir );
141                 $pick = false;
142                 while ( false !== $entry ) {
143                         $entry = readdir( $dir );
144                         if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
145                                 $size = getimagesize( "$directory/$entry" );
146                                 $pick = array(
147                                         'salt' => $matches[1],
148                                         'hash' => $matches[2],
149                                         'width' => $size[0],
150                                         'height' => $size[1],
151                                         'viewed' => false,
152                                 );
153                                 if ( $count++ == $n ) {
154                                         break;
155                                 }
156                         }
157                 }
158                 closedir( $dir );
159                 return $pick;
160         }
161
162         /**
163          * Count the number of files in a directory.
164          * @param $dirname
165          * @return int
166          */
167         function countFiles( $dirname ) {
168                 $dir = opendir( $dirname );
169                 $count = 0;
170                 while ( false !== ( $entry = readdir( $dir ) ) ) {
171                         if ( $entry != '.' && $entry != '..' ) {
172                                 $count++;
173                         }
174                 }
175                 closedir( $dir );
176                 return $count;
177         }
178
179         function showImage() {
180                 global $wgOut;
181
182                 $wgOut->disable();
183
184                 $info = $this->retrieveCaptcha();
185                 if ( $info ) {
186                         $timestamp = new MWTimestamp();
187                         $info['viewed'] = $timestamp->getTimestamp();
188                         $this->storeCaptcha( $info );
189
190                         $salt = $info['salt'];
191                         $hash = $info['hash'];
192                         $file = $this->imagePath( $salt, $hash );
193
194                         if ( file_exists( $file ) ) {
195                                 global $IP;
196                                 require_once "$IP/includes/StreamFile.php";
197                                 header( "Cache-Control: private, s-maxage=0, max-age=3600" );
198                                 StreamFile::stream( $file );
199                                 return true;
200                         }
201                 }
202                 wfHttpError( 500, 'Internal Error', 'Requested bogus captcha image' );
203                 return false;
204         }
205
206         function imagePath( $salt, $hash ) {
207                 global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
208                 $file = $wgCaptchaDirectory;
209                 $file .= DIRECTORY_SEPARATOR;
210                 for ( $i = 0; $i < $wgCaptchaDirectoryLevels; $i++ ) {
211                         $file .= $hash { $i } ;
212                         $file .= DIRECTORY_SEPARATOR;
213                 }
214                 $file .= "image_{$salt}_{$hash}.png";
215                 return $file;
216         }
217
218         /**
219          * Show a message asking the user to enter a captcha on edit
220          * The result will be treated as wiki text
221          *
222          * @param $action string Action being performed
223          * @return string
224          */
225         function getMessage( $action ) {
226                 $name = 'fancycaptcha-' . $action;
227                 $text = wfMessage( $name )->text();
228                 # Obtain a more tailored message, if possible, otherwise, fall back to
229                 # the default for edits
230                 return wfMessage( $name, $text )->isDisabled() ? wfMessage( 'fancycaptcha-edit' )->text() : $text;
231         }
232
233         /**
234          * Delete a solved captcha image, if $wgCaptchaDeleteOnSolve is true.
235          */
236         function passCaptcha() {
237                 global $wgCaptchaDeleteOnSolve;
238
239                 $info = $this->retrieveCaptcha(); // get the captcha info before it gets deleted
240                 $pass = parent::passCaptcha();
241
242                 if ( $pass && $wgCaptchaDeleteOnSolve ) {
243                         $filename = $this->imagePath( $info['salt'], $info['hash'] );
244                         if ( file_exists( $filename ) ) {
245                                 unlink( $filename );
246                         }
247                 }
248
249                 return $pass;
250         }
251 }