* Optimised startup
[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 WebRequest $request
9          * @param array $info
10          * @return bool
11          */
12         function keyMatch( $request, $info ) {
13                 global $wgCaptchaSecret;
14
15                 $answer = $request->getVal( 'wpCaptchaWord' );
16                 $digest = $wgCaptchaSecret . $info['salt'] . $answer . $wgCaptchaSecret . $info['salt'];
17                 $answerHash = substr( md5( $digest ), 0, 16 );
18
19                 if( $answerHash == $info['hash'] ) {
20                         wfDebug( "FancyCaptcha: answer hash matches expected {$info['hash']}\n" );
21                         return true;
22                 } else {
23                         wfDebug( "FancyCaptcha: answer hashes to $answerHash, expected {$info['hash']}\n" );
24                         return false;
25                 }
26         }
27
28         /**
29          * Insert the captcha prompt into the edit form.
30          */
31         function getForm() {
32                 $info = $this->pickImage();
33                 if( !$info ) {
34                         die( "out of captcha images; this shouldn't happen" );
35                 }
36
37                 // Generate a random key for use of this captcha image in this session.
38                 // This is needed so multiple edits in separate tabs or windows can
39                 // go through without extra pain.
40                 $index = $this->storeCaptcha( $info );
41
42                 wfDebug( "Captcha id $index using hash ${info['hash']}, salt ${info['salt']}.\n" );
43
44                 $title = Title::makeTitle( NS_SPECIAL, 'Captcha/image' );
45
46                 return "<p>" .
47                         wfElement( 'img', array(
48                                 'src'    => $title->getLocalUrl( 'wpCaptchaId=' . urlencode( $index ) ),
49                                 'width'  => $info['width'],
50                                 'height' => $info['height'],
51                                 'alt'    => '' ) ) .
52                         "</p>\n" .
53                         wfElement( 'input', array(
54                                 'type'  => 'hidden',
55                                 'name'  => 'wpCaptchaId',
56                                 'id'    => 'wpCaptchaId',
57                                 'value' => $index ) ) .
58                         "<p>" .
59                         wfElement( 'input', array(
60                                 'name' => 'wpCaptchaWord',
61                                 'id'   => 'wpCaptchaWord',
62                                 'tabindex' => 1 ) ) . // tab in before the edit textarea
63                         "</p>\n";
64         }
65
66         /**
67          * Select a previously generated captcha image from the queue.
68          * @fixme subject to race conditions if lots of files vanish
69          * @return mixed tuple of (salt key, text hash) or false if no image to find
70          */
71         function pickImage() {
72                 global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
73                 return $this->pickImageDir(
74                         $wgCaptchaDirectory,
75                         $wgCaptchaDirectoryLevels );
76         }
77         
78         function pickImageDir( $directory, $levels ) {
79                 if( $levels ) {
80                         $dirs = array();
81                         
82                         // Check which subdirs are actually present...
83                         $dir = opendir( $directory );
84                         while( false !== ($entry = readdir( $dir ) ) ) {
85                                 if( ctype_xdigit( $entry ) && strlen( $entry ) == 1 ) {
86                                         $dirs[] = $entry;
87                                 }
88                         }
89                         closedir( $dir );
90                         
91                         $place = mt_rand( 0, count( $dirs ) - 1 );
92                         // In case all dirs are not filled,
93                         // cycle through next digits...
94                         for( $j = 0; $j < count( $dirs ); $j++ ) {
95                                 $char = $dirs[($place + $j) % count( $dirs )];
96                                 $return = $this->pickImageDir( "$directory/$char", $levels - 1 );
97                                 if( $return ) {
98                                         return $return;
99                                 }
100                         }
101                         // Didn't find any images in this directory... empty?
102                         return false;
103                 } else {
104                         return $this->pickImageFromDir( $directory );
105                 }
106         }
107         
108         function pickImageFromDir( $directory ) {
109                 if( !is_dir( $directory ) ) {
110                         return false;
111                 }
112                 $n = mt_rand( 0, $this->countFiles( $directory ) - 1 );
113                 $dir = opendir( $directory );
114
115                 $count = 0;
116
117                 $entry = readdir( $dir );
118                 $pick = false;
119                 while( false !== $entry ) {
120                         $entry = readdir( $dir );
121                         if( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
122                                 $size = getimagesize( "$directory/$entry" );
123                                 $pick = array(
124                                         'salt' => $matches[1],
125                                         'hash' => $matches[2],
126                                         'width' => $size[0],
127                                         'height' => $size[1],
128                                         'viewed' => false,
129                                 );
130                                 if( $count++ == $n ) {
131                                         break;
132                                 }
133                         }
134                 }
135                 closedir( $dir );
136                 return $pick;
137         }
138
139         /**
140          * Count the number of files in a directory.
141          * @return int
142          */
143         function countFiles( $dirname ) {
144                 $dir = opendir( $dirname );
145                 $count = 0;
146                 while( false !== ($entry = readdir( $dir ) ) ) {
147                         if( $entry != '.' && $entry != '..' ) {
148                                 $count++;
149                         }
150                 }
151                 closedir( $dir );
152                 return $count;
153         }
154
155         function showImage() {
156                 global $wgOut, $wgRequest;
157
158                 $wgOut->disable();
159
160                 $info = $this->retrieveCaptcha();
161                 if( $info ) {
162                         if( $info['viewed'] ) {
163                                 wfHttpError( 403, 'Access Forbidden', "Can't view captcha image a second time." );
164                                 return false;
165                         }
166
167                         $info['viewed'] = wfTimestamp();
168                         $this->storeCaptcha( $info );
169
170                         $salt = $info['salt'];
171                         $hash = $info['hash'];
172                         $file = $this->imagePath( $salt, $hash );
173
174                         if( file_exists( $file ) ) {
175                                 global $IP;
176                                 require_once "$IP/includes/StreamFile.php";
177                                 wfStreamFile( $file );
178                                 return true;
179                         }
180                 }
181                 wfHttpError( 500, 'Internal Error', 'Requested bogus captcha image' );
182                 return false;
183         }
184         
185         function imagePath( $salt, $hash ) {
186                 global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
187                 $file = $wgCaptchaDirectory;
188                 $file .= DIRECTORY_SEPARATOR;
189                 for( $i = 0; $i < $wgCaptchaDirectoryLevels; $i++ ) {
190                         $file .= $hash{$i};
191                         $file .= DIRECTORY_SEPARATOR;
192                 }
193                 $file .= "image_{$salt}_{$hash}.png";
194                 return $file;
195         }
196
197         /**
198          * Show a message asking the user to enter a captcha on edit
199          * The result will be treated as wiki text
200          *
201          * @param $action Action being performed
202          * @return string
203          */
204         function getMessage( $action ) {
205                 $name = 'fancycaptcha-' . $action;
206                 $text = wfMsg( $name );
207                 # Obtain a more tailored message, if possible, otherwise, fall back to
208                 # the default for edits
209                 return wfEmptyMsg( $name, $text ) ? wfMsg( 'fancycaptcha-edit' ) : $text;
210         }
211
212 }