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