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