summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/ConfirmEdit/FancyCaptcha/FancyCaptcha.class.php
blob: 3010374fb56ca6d5e2f0b163985b96b4858d98df (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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<?php

use MediaWiki\Auth\AuthenticationRequest;
use MediaWiki\Auth\AuthManager;

/**
 * FancyCaptcha for displaying captchas precomputed by captcha.py
 */
class FancyCaptcha extends SimpleCaptcha {
	// used for fancycaptcha-edit, fancycaptcha-addurl, fancycaptcha-badlogin,
	// fancycaptcha-accountcreate, fancycaptcha-create, fancycaptcha-sendemail via getMessage()
	protected static $messagePrefix = 'fancycaptcha-';

	/**
	 * @return FileBackend
	 */
	public function getBackend() {
		global $wgCaptchaFileBackend, $wgCaptchaDirectory;

		if ( $wgCaptchaFileBackend ) {
			return FileBackendGroup::singleton()->get( $wgCaptchaFileBackend );
		} else {
			static $backend = null;
			if ( !$backend ) {
				$backend = new FSFileBackend( [
					'name'           => 'captcha-backend',
					'wikiId'         => wfWikiID(),
					'lockManager'    => new NullLockManager( [] ),
					'containerPaths' => [ 'captcha-render' => $wgCaptchaDirectory ],
					'fileMode'       => 777,
					'obResetFunc'    => 'wfResetOutputBuffers',
					'streamMimeFunc' => [ 'StreamFile', 'contentTypeFromPath' ]
				] );
			}
			return $backend;
		}
	}

	/**
	 * @deprecated Use getCaptchaCount instead for an accurate figure
	 * @return int Number of captcha files
	 */
	public function estimateCaptchaCount() {
		wfDeprecated( __METHOD__ );
		return $this->getCaptchaCount();
	}

	/**
	 * @return int Number of captcha files
	 */
	public function getCaptchaCount() {
		$backend = $this->getBackend();
		$files = $backend->getFileList(
			[ 'dir' => $backend->getRootStoragePath() . '/captcha-render' ]
		);

		return iterator_count( $files );
	}

	/**
	 * 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;
		}
	}

	/**
	 * @param array &$resultArr
	 */
	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'] = $this->describeCaptchaType();
		$resultArr['captcha']['id'] = $index;
		$resultArr['captcha']['url'] = $title->getLocalURL( 'wpCaptchaId=' . urlencode( $index ) );
	}

	/**
	 * @return array
	 */
	public function describeCaptchaType() {
		return [
			'type' => 'image',
			'mime' => 'image/png',
		];
	}

	/**
	 * @param int $tabIndex
	 * @return array
	 */
	function getFormInformation( $tabIndex = 1 ) {
		$modules = [];

		$title = SpecialPage::getTitleFor( 'Captcha', 'image' );
		$info = $this->getCaptcha();
		$index = $this->storeCaptcha( $info );

		// Loaded only for clients with JS enabled
		$modules[] = 'ext.confirmEdit.fancyCaptcha';

		$captchaReload = Html::element(
			'small',
			[
				'class' => 'confirmedit-captcha-reload fancycaptcha-reload'
			],
			wfMessage( 'fancycaptcha-reload-text' )->text()
		);

		$form = Html::openElement( 'div' ) .
			Html::element( 'label', [
					'for' => 'wpCaptchaWord',
				],
				wfMessage( 'captcha-label' )->text() . ' ' . wfMessage( 'fancycaptcha-captcha' )->text()
			) .
			Html::openElement( 'div', [ 'class' => 'fancycaptcha-captcha-container' ] ) .
			Html::openElement( 'div', [ 'class' => 'fancycaptcha-captcha-and-reload' ] ) .
			Html::openElement( 'div', [ 'class' => 'fancycaptcha-image-container' ] ) .
			Html::element( 'img', [
					'class'  => 'fancycaptcha-image',
					'src'    => $title->getLocalURL( 'wpCaptchaId=' . urlencode( $index ) ),
					'alt'    => ''
				]
			) . $captchaReload . Html::closeElement( 'div' ) . Html::closeElement( 'div' ) . "\n" .
			Html::element( 'input', [
					'name' => 'wpCaptchaWord',
					'class' => 'mw-ui-input',
					'id'   => 'wpCaptchaWord',
					'type' => 'text',
					'size' => '12',  // max_length in captcha.py plus fudge factor
					'autocomplete' => 'off',
					'autocorrect' => 'off',
					'autocapitalize' => 'off',
					'required' => 'required',
					'tabindex' => $tabIndex,
					'placeholder' => wfMessage( 'fancycaptcha-imgcaptcha-ph' )
				]
			); // tab in before the edit textarea
			if ( $this->action == 'createaccount' ) {
				// use raw element, because the message can contain links or some other html
				$form .= Html::rawElement( 'small', [
						'class' => 'mw-createacct-captcha-assisted'
					], wfMessage( 'createacct-imgcaptcha-help' )->parse()
				);
			}
			$form .= Html::element( 'input', [
					'type'  => 'hidden',
					'name'  => 'wpCaptchaId',
					'id'    => 'wpCaptchaId',
					'value' => $index
				]
			) . Html::closeElement( 'div' ) . Html::closeElement( 'div' ) . "\n";

		return [
			'html' => $form,
			'modules' => $modules,
			// Uses addModuleStyles so it is loaded when JS is disabled.
			'modulestyles' => [ 'ext.confirmEdit.fancyCaptcha.styles' ],
		];
	}

	/**
	 * Select a previously generated captcha image from the queue.
	 * @return mixed tuple of (salt key, text hash) or false if no image to find
	 */
	protected function pickImage() {
		global $wgCaptchaDirectoryLevels;

		$lockouts = 0; // number of times another process claimed a file before this one
		$baseDir = $this->getBackend()->getRootStoragePath() . '/captcha-render';
		return $this->pickImageDir( $baseDir, $wgCaptchaDirectoryLevels, $lockouts );
	}

	/**
	 * @param string $directory
	 * @param int $levels
	 * @param int &$lockouts
	 * @return array|bool
	 */
	protected function pickImageDir( $directory, $levels, &$lockouts ) {
		global $wgMemc;

		if ( $levels <= 0 ) { // $directory has regular files
			return $this->pickImageFromDir( $directory, $lockouts );
		}

		$backend = $this->getBackend();

		$key  = "fancycaptcha:dirlist:{$backend->getWikiId()}:" . sha1( $directory );
		$dirs = $wgMemc->get( $key ); // check cache
		if ( !is_array( $dirs ) || !count( $dirs ) ) { // cache miss
			$dirs = []; // subdirs actually present...
			foreach ( $backend->getTopDirectoryList( [ 'dir' => $directory ] ) as $entry ) {
				if ( ctype_xdigit( $entry ) && strlen( $entry ) == 1 ) {
					$dirs[] = $entry;
				}
			}
			wfDebug( "Cache miss for $directory subdirectory listing.\n" );
			if ( count( $dirs ) ) {
				$wgMemc->set( $key, $dirs, 86400 );
			}
		}

		if ( !count( $dirs ) ) {
			// Remove this directory if empty so callers don't keep looking here
			$backend->clean( [ 'dir' => $directory ] );
			return false; // none found
		}

		$place = mt_rand( 0, count( $dirs ) - 1 ); // pick a random subdir
		// In case all dirs are not filled, cycle through next digits...
		$fancyCount = count( $dirs );
		for ( $j = 0; $j < $fancyCount; $j++ ) {
			$char = $dirs[( $place + $j ) % count( $dirs )];
			$info = $this->pickImageDir( "$directory/$char", $levels - 1, $lockouts );
			if ( $info ) {
				return $info; // found a captcha
			} else {
				wfDebug( "Could not find captcha in $directory.\n" );
				$wgMemc->delete( $key ); // files changed on disk?
			}
		}

		return false; // didn't find any images in this directory... empty?
	}

	/**
	 * @param string $directory
	 * @param int &$lockouts
	 * @return array|bool
	 */
	protected function pickImageFromDir( $directory, &$lockouts ) {
		global $wgMemc;

		$backend = $this->getBackend();

		$key   = "fancycaptcha:filelist:{$backend->getWikiId()}:" . sha1( $directory );
		$files = $wgMemc->get( $key ); // check cache
		if ( !is_array( $files ) || !count( $files ) ) { // cache miss
			$files = []; // captcha files
			foreach ( $backend->getTopFileList( [ 'dir' => $directory ] ) as $entry ) {
				$files[] = $entry;
				if ( count( $files ) >= 500 ) { // sanity
					wfDebug( 'Skipping some captchas; $wgCaptchaDirectoryLevels set too low?.' );
					break;
				}
			}
			if ( count( $files ) ) {
				$wgMemc->set( $key, $files, 86400 );
			}
			wfDebug( "Cache miss for $directory captcha listing.\n" );
		}

		if ( !count( $files ) ) {
			// Remove this directory if empty so callers don't keep looking here
			$backend->clean( [ 'dir' => $directory ] );
			return false;
		}

		$info = $this->pickImageFromList( $directory, $files, $lockouts );
		if ( !$info ) {
			wfDebug( "Could not find captcha in $directory.\n" );
			$wgMemc->delete( $key ); // files changed on disk?
		}

		return $info;
	}

	/**
	 * @param string $directory
	 * @param array $files
	 * @param int &$lockouts
	 * @return array|bool
	 */
	protected function pickImageFromList( $directory, array $files, &$lockouts ) {
		global $wgMemc, $wgCaptchaDeleteOnSolve;

		if ( !count( $files ) ) {
			return false; // none found
		}

		$backend  = $this->getBackend();
		$place    = mt_rand( 0, count( $files ) - 1 ); // pick a random file
		$misses   = 0; // number of files in listing that don't actually exist
		$fancyImageCount = count( $files );
		for ( $j = 0; $j < $fancyImageCount; $j++ ) {
			$entry = $files[( $place + $j ) % count( $files )];
			if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
				if ( $wgCaptchaDeleteOnSolve ) { // captcha will be deleted when solved
					$key = "fancycaptcha:filelock:{$backend->getWikiId()}:" . sha1( $entry );
					// Try to claim this captcha for 10 minutes (for the user to solve)...
					if ( ++$lockouts <= 10 && !$wgMemc->add( $key, '1', 600 ) ) {
						continue; // could not acquire (skip it to avoid race conditions)
					}
				}
				if ( !$backend->fileExists( [ 'src' => "$directory/$entry" ] ) ) {
					if ( ++$misses >= 5 ) { // too many files in the listing don't exist
						break; // listing cache too stale? break out so it will be cleared
					}
					continue; // try next file
				}
				return [
					'salt'   => $matches[1],
					'hash'   => $matches[2],
					'viewed' => false,
				];
			}
		}

		return false; // none found
	}

	/**
	 * @return bool|StatusValue
	 */
	function showImage() {
		global $wgOut, $wgRequest;

		$wgOut->disable();

		$index = $wgRequest->getVal( 'wpCaptchaId' );
		$info = $this->retrieveCaptcha( $index );
		if ( $info ) {
			$timestamp = new MWTimestamp();
			$info['viewed'] = $timestamp->getTimestamp();
			$this->storeCaptcha( $info );

			$salt = $info['salt'];
			$hash = $info['hash'];

			return $this->getBackend()->streamFile( [
				'src'     => $this->imagePath( $salt, $hash ),
				'headers' => [ "Cache-Control: private, s-maxage=0, max-age=3600" ]
			] )->isOK();
		}

		wfHttpError( 400, 'Request Error', 'Requested bogus captcha image' );
		return false;
	}

	/**
	 * @param string $salt
	 * @param string $hash
	 * @return string
	 */
	public function imagePath( $salt, $hash ) {
		global $wgCaptchaDirectoryLevels;

		$file = $this->getBackend()->getRootStoragePath() . '/captcha-render/';
		for ( $i = 0; $i < $wgCaptchaDirectoryLevels; $i++ ) {
			$file .= $hash{ $i } . '/';
		}
		$file .= "image_{$salt}_{$hash}.png";

		return $file;
	}

	/**
	 * @param string $basename
	 * @return array (salt, hash)
	 * @throws Exception
	 */
	public function hashFromImageName( $basename ) {
		if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $basename, $matches ) ) {
			return [ $matches[1], $matches[2] ];
		} else {
			throw new Exception( "Invalid filename '$basename'.\n" );
		}
	}

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

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

		if ( $pass && $wgCaptchaDeleteOnSolve ) {
			$this->getBackend()->quickDelete( [
				'src' => $this->imagePath( $info['salt'], $info['hash'] )
			] );
		}

		return $pass;
	}

	/**
	 * Returns an array with 'salt' and 'hash' keys. Hash is
	 * md5( $wgCaptchaSecret . $salt . $answer . $wgCaptchaSecret . $salt )[0..15]
	 * @return array
	 * @throws Exception When a captcha image cannot be produced.
	 */
	public function getCaptcha() {
		$info = $this->pickImage();
		if ( !$info ) {
			throw new UnderflowException( 'Ran out of captcha images' );
		}
		return $info;
	}

	/**
	 * @param array $captchaData
	 * @param string $id
	 * @return string
	 */
	public function getCaptchaInfo( $captchaData, $id ) {
		$title = SpecialPage::getTitleFor( 'Captcha', 'image' );
		return $title->getLocalURL( 'wpCaptchaId=' . urlencode( $id ) );
	}

	/**
	 * @param array $requests
	 * @param array $fieldInfo
	 * @param array &$formDescriptor
	 * @param string $action
	 */
	public function onAuthChangeFormFields(
		array $requests, array $fieldInfo, array &$formDescriptor, $action
	) {
		/** @var CaptchaAuthenticationRequest $req */
		$req =
			AuthenticationRequest::getRequestByClass( $requests,
				CaptchaAuthenticationRequest::class, true );
		if ( !$req ) {
			return;
		}

		// HTMLFancyCaptchaField will include this
		unset( $formDescriptor['captchaInfo' ] );

		$formDescriptor['captchaWord'] = [
			'class' => HTMLFancyCaptchaField::class,
			'imageUrl' => $this->getCaptchaInfo( $req->captchaData, $req->captchaId ),
			'label-message' => $this->getMessage( $this->action ),
			'showCreateHelp' => in_array( $action, [
				AuthManager::ACTION_CREATE,
				AuthManager::ACTION_CREATE_CONTINUE
			], true ),
		] + $formDescriptor['captchaWord'];
	}
}