summaryrefslogtreecommitdiff
path: root/extensions/ConfirmEdit/FancyCaptcha.class.php
blob: 3ce5670e4ecba395b4a0dfaf47820ebe447dcdfd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
<?php

class FancyCaptcha extends SimpleCaptcha {
	/**
	 * Check if the submitted form matches the captcha session data provided
	 * by the plugin when the form was generated.
	 *
	 * @param string $answer
	 * @param array $info
	 * @return bool
	 */
	function keyMatch( $answer, $info ) {
		global $wgCaptchaSecret;

		$digest = $wgCaptchaSecret . $info['salt'] . $answer . $wgCaptchaSecret . $info['salt'];
		$answerHash = substr( md5( $digest ), 0, 16 );

		if ( $answerHash == $info['hash'] ) {
			wfDebug( "FancyCaptcha: answer hash matches expected {$info['hash']}\n" );
			return true;
		} else {
			wfDebug( "FancyCaptcha: answer hashes to $answerHash, expected {$info['hash']}\n" );
			return false;
		}
	}

	function addCaptchaAPI( &$resultArr ) {
		$info = $this->pickImage();
		if ( !$info ) {
			$resultArr['captcha']['error'] = 'Out of images';
			return;
		}
		$index = $this->storeCaptcha( $info );
		$title = SpecialPage::getTitleFor( 'Captcha', 'image' );
		$resultArr['captcha']['type'] = 'image';
		$resultArr['captcha']['mime'] = 'image/png';
		$resultArr['captcha']['id'] = $index;
		$resultArr['captcha']['url'] = $title->getLocalUrl( 'wpCaptchaId=' . urlencode( $index ) );
	}

	/**
	 * Insert the captcha prompt into the edit form.
	 */
	function getForm() {
		$info = $this->pickImage();
		if ( !$info ) {
			throw new MWException( "Ran out of captcha images" );
		}

		// Generate a random key for use of this captcha image in this session.
		// This is needed so multiple edits in separate tabs or windows can
		// go through without extra pain.
		$index = $this->storeCaptcha( $info );

		wfDebug( "Captcha id $index using hash ${info['hash']}, salt ${info['salt']}.\n" );

		$title = SpecialPage::getTitleFor( 'Captcha', 'image' );

		return "<p>" .
			Xml::element( 'img', array(
				'src'    => $title->getLocalUrl( 'wpCaptchaId=' . urlencode( $index ) ),
				'width'  => $info['width'],
				'height' => $info['height'],
				'alt'    => '' ) ) .
			"</p>\n" .
			Xml::element( 'input', array(
				'type'  => 'hidden',
				'name'  => 'wpCaptchaId',
				'id'    => 'wpCaptchaId',
				'value' => $index ) ) .
			"<p>" .
			Html::element( 'input', array(
				'name' => 'wpCaptchaWord',
				'id'   => 'wpCaptchaWord',
				'autocorrect' => 'off',
				'autocapitalize' => 'off',
				'required',
				'tabindex' => 1 ) ) . // tab in before the edit textarea
			"</p>\n";
	}

	/**
	 * Select a previously generated captcha image from the queue.
	 * @fixme subject to race conditions if lots of files vanish
	 * @return mixed tuple of (salt key, text hash) or false if no image to find
	 */
	function pickImage() {
		global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
		return $this->pickImageDir(
			$wgCaptchaDirectory,
			$wgCaptchaDirectoryLevels );
	}

	function pickImageDir( $directory, $levels ) {
		if ( $levels ) {
			$dirs = array();

			// Check which subdirs are actually present...
			$dir = opendir( $directory );
			while ( false !== ( $entry = readdir( $dir ) ) ) {
				if ( ctype_xdigit( $entry ) && strlen( $entry ) == 1 ) {
					$dirs[] = $entry;
				}
			}
			closedir( $dir );

			$place = mt_rand( 0, count( $dirs ) - 1 );
			// In case all dirs are not filled,
			// cycle through next digits...
			for ( $j = 0; $j < count( $dirs ); $j++ ) {
				$char = $dirs[( $place + $j ) % count( $dirs )];
				$return = $this->pickImageDir( "$directory/$char", $levels - 1 );
				if ( $return ) {
					return $return;
				}
			}
			// Didn't find any images in this directory... empty?
			return false;
		} else {
			return $this->pickImageFromDir( $directory );
		}
	}

	function pickImageFromDir( $directory ) {
		if ( !is_dir( $directory ) ) {
			return false;
		}
		$n = mt_rand( 0, $this->countFiles( $directory ) - 1 );
		$dir = opendir( $directory );

		$count = 0;

		$entry = readdir( $dir );
		$pick = false;
		while ( false !== $entry ) {
			$entry = readdir( $dir );
			if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
				$size = getimagesize( "$directory/$entry" );
				$pick = array(
					'salt' => $matches[1],
					'hash' => $matches[2],
					'width' => $size[0],
					'height' => $size[1],
					'viewed' => false,
				);
				if ( $count++ == $n ) {
					break;
				}
			}
		}
		closedir( $dir );
		return $pick;
	}

	/**
	 * Count the number of files in a directory.
	 * @return int
	 */
	function countFiles( $dirname ) {
		$dir = opendir( $dirname );
		$count = 0;
		while ( false !== ( $entry = readdir( $dir ) ) ) {
			if ( $entry != '.' && $entry != '..' ) {
				$count++;
			}
		}
		closedir( $dir );
		return $count;
	}

	function showImage() {
		global $wgOut;

		$wgOut->disable();

		$info = $this->retrieveCaptcha();
		if ( $info ) {
			/*
			// Be a little less restrictive for now; in at least some circumstances,
			// Konqueror tries to reload the image even if you haven't navigated
			// away from the page.
			if( $info['viewed'] ) {
				wfHttpError( 403, 'Access Forbidden', "Can't view captcha image a second time." );
				return false;
			}
			*/

			$info['viewed'] = wfTimestamp();
			$this->storeCaptcha( $info );

			$salt = $info['salt'];
			$hash = $info['hash'];
			$file = $this->imagePath( $salt, $hash );

			if ( file_exists( $file ) ) {
				global $IP;
				require_once "$IP/includes/StreamFile.php";
				header( "Cache-Control: private, s-maxage=0, max-age=3600" );
				wfStreamFile( $file );
				return true;
			}
		}
		wfHttpError( 500, 'Internal Error', 'Requested bogus captcha image' );
		return false;
	}

	function imagePath( $salt, $hash ) {
		global $wgCaptchaDirectory, $wgCaptchaDirectoryLevels;
		$file = $wgCaptchaDirectory;
		$file .= DIRECTORY_SEPARATOR;
		for ( $i = 0; $i < $wgCaptchaDirectoryLevels; $i++ ) {
			$file .= $hash { $i } ;
			$file .= DIRECTORY_SEPARATOR;
		}
		$file .= "image_{$salt}_{$hash}.png";
		return $file;
	}

	/**
	 * Show a message asking the user to enter a captcha on edit
	 * The result will be treated as wiki text
	 *
	 * @param $action Action being performed
	 * @return string
	 */
	function getMessage( $action ) {
		$name = 'fancycaptcha-' . $action;
		$text = wfMsg( $name );
		# Obtain a more tailored message, if possible, otherwise, fall back to
		# the default for edits
		return wfEmptyMsg( $name, $text ) ? wfMsg( 'fancycaptcha-edit' ) : $text;
	}

	/**
	 * Delete a solved captcha image, if $wgCaptchaDeleteOnSolve is true.
	 */
	function passCaptcha() {
		global $wgCaptchaDeleteOnSolve;

		$info = $this->retrieveCaptcha(); // get the captcha info before it gets deleted
		$pass = parent::passCaptcha();

		if ( $pass && $wgCaptchaDeleteOnSolve ) {
			$filename = $this->imagePath( $info['salt'], $info['hash'] );
			if ( file_exists( $filename ) ) {
				unlink( $filename );
			}
		}

		return $pass;
	}
}