Debian Codegraph @

extensions/ConfirmEdit/FancyCaptcha/includes/FancyCaptcha.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\ConfirmEdit\FancyCaptcha;
4
5 use InvalidArgumentException;
6 use MediaWiki\Auth\AuthenticationRequest;
7 use MediaWiki\Auth\AuthManager;
8 use MediaWiki\Context\RequestContext;
9 use MediaWiki\Extension\ConfirmEdit\Auth\CaptchaAuthenticationRequest;
10 use MediaWiki\Extension\ConfirmEdit\SimpleCaptcha\SimpleCaptcha;
11 use MediaWiki\Html\Html;
12 use MediaWiki\MediaWikiServices;
13 use MediaWiki\SpecialPage\SpecialPage;
14 use MediaWiki\Utils\MWTimestamp;
15 use MediaWiki\WikiMap\WikiMap;
16 use NullLockManager;
17 use UnderflowException;
18 use Wikimedia\FileBackend\FileBackend;
19 use Wikimedia\FileBackend\FSFileBackend;
20
21 /**
22 * FancyCaptcha for displaying captchas precomputed by captcha.py
23 */
24 class FancyCaptcha extends SimpleCaptcha {
25 /**
26 * @var string used for fancycaptcha-edit, fancycaptcha-addurl, fancycaptcha-badlogin,
27 * fancycaptcha-accountcreate, fancycaptcha-create, fancycaptcha-sendemail via getMessage()
28 */
29 protected static $messagePrefix = 'fancycaptcha-';
30
31 /**
32 * @return FileBackend
33 */
34 public function getBackend() {
35 global $wgCaptchaFileBackend, $wgCaptchaDirectory;
36
37 if ( $wgCaptchaFileBackend ) {
38 return MediaWikiServices::getInstance()->getFileBackendGroup()
39 ->get( $wgCaptchaFileBackend );
40 }
41
42 static $backend = null;
43 if ( !$backend ) {
44 $backend = new FSFileBackend( [
45 'name' => 'captcha-backend',
46 'wikiId' => WikiMap::getCurrentWikiId(),
47 'lockManager' => new NullLockManager( [] ),
48 'containerPaths' => [ $this->getStorageDir() => $wgCaptchaDirectory ],
49 'fileMode' => 777,
50 'obResetFunc' => 'wfResetOutputBuffers',
51 'streamMimeFunc' => [ 'StreamFile', 'contentTypeFromPath' ]
52 ] );
53 }
54
55 return $backend;
56 }
57
58 /**
59 * @return int Number of captcha files
60 */
61 public function getCaptchaCount() {
62 $backend = $this->getBackend();
63 $files = $backend->getFileList(
64 [ 'dir' => $backend->getRootStoragePath() . '/' . $this->getStorageDir() ]
65 );
66
67 return iterator_count( $files );
68 }
69
70 /**
71 * @return string
72 */
73 public function getStorageDir() {
74 global $wgCaptchaStorageDirectory;
75 return $wgCaptchaStorageDirectory;
76 }
77
78 /**
79 * Check if the submitted form matches the captcha session data provided
80 * by the plugin when the form was generated.
81 *
82 * @param string $answer
83 * @param array $info
84 * @return bool
85 */
86 protected function keyMatch( $answer, $info ) {
87 global $wgCaptchaSecret;
88
89 $digest = $wgCaptchaSecret . $info['salt'] . $answer . $wgCaptchaSecret . $info['salt'];
90 $answerHash = substr( md5( $digest ), 0, 16 );
91
92 if ( $answerHash == $info['hash'] ) {
93 wfDebug( "FancyCaptcha: answer hash matches expected {$info['hash']}\n" );
94 return true;
95 } else {
96 wfDebug( "FancyCaptcha: answer hashes to $answerHash, expected {$info['hash']}\n" );
97 return false;
98 }
99 }
100
101 /**
102 * @param array &$resultArr
103 */
104 protected function addCaptchaAPI( &$resultArr ) {
105 $info = $this->pickImage();
106 if ( !$info ) {
107 $resultArr['captcha']['error'] = 'Out of images';
108 return;
109 }
110 $index = $this->storeCaptcha( $info );
111 $title = SpecialPage::getTitleFor( 'Captcha', 'image' );
112 $resultArr['captcha'] = $this->describeCaptchaType();
113 $resultArr['captcha']['id'] = $index;
114 $resultArr['captcha']['url'] = $title->getLocalURL( 'wpCaptchaId=' . urlencode( $index ) );
115 }
116
117 /**
118 * @return array
119 */
120 public function describeCaptchaType() {
121 return [
122 'type' => 'image',
123 'mime' => 'image/png',
124 ];
125 }
126
127 /**
128 * @param int $tabIndex
129 * @return array
130 */
131 public function getFormInformation( $tabIndex = 1 ) {
132 $title = SpecialPage::getTitleFor( 'Captcha', 'image' );
133 $info = $this->getCaptcha();
134 $index = $this->storeCaptcha( $info );
135
136 $captchaReload = Html::element(
137 'small',
138 [
139 'class' => 'confirmedit-captcha-reload fancycaptcha-reload'
140 ],
141 wfMessage( 'fancycaptcha-reload-text' )->text()
142 );
143
144 $form = Html::openElement( 'div' ) .
145 Html::element( 'label', [
146 'for' => 'wpCaptchaWord',
147 ],
148 wfMessage( 'captcha-label' )->text() . ' ' . wfMessage( 'fancycaptcha-captcha' )->text()
149 ) .
150 Html::openElement( 'div', [ 'class' => 'fancycaptcha-captcha-container' ] ) .
151 Html::openElement( 'div', [ 'class' => 'fancycaptcha-captcha-and-reload' ] ) .
152 Html::openElement( 'div', [ 'class' => 'fancycaptcha-image-container' ] ) .
153 Html::element( 'img', [
154 'class' => 'fancycaptcha-image',
155 'src' => $title->getLocalURL( 'wpCaptchaId=' . urlencode( $index ) ),
156 'alt' => ''
157 ]
158 ) . $captchaReload . Html::closeElement( 'div' ) . Html::closeElement( 'div' ) . "\n" .
159 // FIXME: This should use CodexHTMLForm rather than Html::element
160 Html::openElement( 'div', [ 'class' => 'cdx-text-input' ] ) .
161 Html::element( 'input', [
162 'name' => 'wpCaptchaWord',
163 'class' => 'cdx-text-input__input',
164 'id' => 'wpCaptchaWord',
165 'type' => 'text',
166 // max_length in captcha.py plus fudge factor
167 'size' => '12',
168 'autocomplete' => 'off',
169 'autocorrect' => 'off',
170 'autocapitalize' => 'off',
171 'required' => 'required',
172 // tab in before the edit textarea
173 'tabindex' => $tabIndex,
174 'placeholder' => wfMessage( 'fancycaptcha-imgcaptcha-ph' )->text()
175 ]
176 ) . Html::closeElement( 'div' );
177 if ( $this->action == 'createaccount' ) {
178 // use raw element, because the message can contain links or some other html
179 $form .= Html::rawElement( 'small', [
180 'class' => 'mw-createacct-captcha-assisted'
181 ], wfMessage( 'createacct-imgcaptcha-help' )->parse()
182 );
183 }
184 $form .= Html::element( 'input', [
185 'type' => 'hidden',
186 'name' => 'wpCaptchaId',
187 'id' => 'wpCaptchaId',
188 'value' => $index
189 ]
190 ) . Html::closeElement( 'div' ) . Html::closeElement( 'div' ) . "\n";
191
192 return [
193 'html' => $form,
194 'modules' => [ 'ext.confirmEdit.fancyCaptcha' ],
195 // Uses addModuleStyles so it is loaded when JS is disabled.
196 'modulestyles' => [ 'codex-styles', 'ext.confirmEdit.fancyCaptcha.styles' ],
197 ];
198 }
199
200 /**
201 * Select a previously generated captcha image from the queue.
202 * @return mixed tuple of (salt key, text hash) or false if no image to find
203 */
204 protected function pickImage() {
205 global $wgCaptchaDirectoryLevels;
206
207 // number of times another process claimed a file before this one
208 $lockouts = 0;
209 $baseDir = $this->getBackend()->getRootStoragePath() . '/' . $this->getStorageDir();
210 return $this->pickImageDir( $baseDir, $wgCaptchaDirectoryLevels, $lockouts );
211 }
212
213 /**
214 * @param string $directory
215 * @param int $levels
216 * @param int &$lockouts
217 * @return array|bool
218 */
219 protected function pickImageDir( $directory, $levels, &$lockouts ) {
220 if ( $levels <= 0 ) {
221 // $directory has regular files
222 return $this->pickImageFromDir( $directory, $lockouts );
223 }
224
225 $backend = $this->getBackend();
226 $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
227
228 $key = $cache->makeGlobalKey(
229 'fancycaptcha-dirlist',
230 $backend->getDomainId(),
231 sha1( $directory )
232 );
233
234 // check cache
235 $dirs = $cache->get( $key );
236 if ( !is_array( $dirs ) || !count( $dirs ) ) {
237 // cache miss
238 $dirs = [];
239 // subdirs actually present...
240 foreach ( $backend->getTopDirectoryList( [ 'dir' => $directory ] ) as $entry ) {
241 if ( ctype_xdigit( $entry ) && strlen( $entry ) == 1 ) {
242 $dirs[] = $entry;
243 }
244 }
245 wfDebug( "Cache miss for $directory subdirectory listing.\n" );
246 if ( count( $dirs ) ) {
247 $cache->set( $key, $dirs, 86400 );
248 }
249 }
250
251 if ( !count( $dirs ) ) {
252 // Remove this directory if empty so callers don't keep looking here
253 $backend->clean( [ 'dir' => $directory ] );
254 // none found
255 return false;
256 }
257
258 // pick a random subdir
259 $place = random_int( 0, count( $dirs ) - 1 );
260 // In case all dirs are not filled, cycle through the next digits...
261 $fancyCount = count( $dirs );
262 for ( $j = 0; $j < $fancyCount; $j++ ) {
263 $char = $dirs[( $place + $j ) % count( $dirs )];
264 $info = $this->pickImageDir( "$directory/$char", $levels - 1, $lockouts );
265 if ( $info ) {
266 // found a captcha
267 return $info;
268 } else {
269 wfDebug( "Could not find captcha in $directory.\n" );
270 // files changed on disk?
271 $cache->delete( $key );
272 }
273 }
274
275 // didn't find any images in this directory... empty?
276 return false;
277 }
278
279 /**
280 * @param string $directory
281 * @param int &$lockouts
282 * @return array|bool
283 */
284 protected function pickImageFromDir( $directory, &$lockouts ) {
285 $backend = $this->getBackend();
286 $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
287
288 $key = $cache->makeGlobalKey(
289 'fancycaptcha-filelist',
290 $backend->getDomainId(),
291 sha1( $directory )
292 );
293
294 // check cache
295 $files = $cache->get( $key );
296 if ( !is_array( $files ) || !count( $files ) ) {
297 // cache miss
298 $files = [];
299 foreach ( $backend->getTopFileList( [ 'dir' => $directory ] ) as $entry ) {
300 $files[] = $entry;
301 if ( count( $files ) >= 500 ) {
302 // sanity
303 wfDebug( 'Skipping some captchas; $wgCaptchaDirectoryLevels set too low?.' );
304 break;
305 }
306 }
307 if ( count( $files ) ) {
308 $cache->set( $key, $files, 86400 );
309 }
310 wfDebug( "Cache miss for $directory captcha listing.\n" );
311 }
312
313 if ( !count( $files ) ) {
314 // Remove this directory if empty so callers don't keep looking here
315 $backend->clean( [ 'dir' => $directory ] );
316 return false;
317 }
318
319 $info = $this->pickImageFromList( $directory, $files, $lockouts );
320 if ( !$info ) {
321 wfDebug( "Could not find captcha in $directory.\n" );
322 // files changed on disk?
323 $cache->delete( $key );
324 }
325
326 return $info;
327 }
328
329 /**
330 * @param string $directory
331 * @param array $files
332 * @param int &$lockouts
333 * @return array|bool
334 */
335 protected function pickImageFromList( $directory, array $files, &$lockouts ) {
336 global $wgCaptchaDeleteOnSolve;
337
338 if ( !count( $files ) ) {
339 // none found
340 return false;
341 }
342
343 $backend = $this->getBackend();
344 $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
345
346 // pick a random file
347 $place = random_int( 0, count( $files ) - 1 );
348 // number of files in listing that don't actually exist
349 $misses = 0;
350 $fancyImageCount = count( $files );
351 for ( $j = 0; $j < $fancyImageCount; $j++ ) {
352 $entry = $files[( $place + $j ) % count( $files )];
353 if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
354 if ( $wgCaptchaDeleteOnSolve ) {
355 // captcha will be deleted when solved
356 $key = $cache->makeGlobalKey(
357 'fancycaptcha-filelock',
358 $backend->getDomainId(),
359 sha1( $entry )
360 );
361 // Try to claim this captcha for 10 minutes (for the user to solve)...
362 if ( ++$lockouts <= 10 && !$cache->add( $key, '1', 600 ) ) {
363 // could not acquire (skip it to avoid race conditions)
364 continue;
365 }
366 }
367 if ( !$backend->fileExists( [ 'src' => "$directory/$entry" ] ) ) {
368 if ( ++$misses >= 5 ) {
369 // too many files in the listing don't exist
370 // listing cache too stale? break out so it will be cleared
371 break;
372 }
373 // try next file
374 continue;
375 }
376 return [
377 'salt' => $matches[1],
378 'hash' => $matches[2],
379 'viewed' => false,
380 ];
381 }
382 }
383
384 // none found
385 return false;
386 }
387
388 /**
389 * @return bool
390 */
391 public function showImage() {
392 $context = RequestContext::getMain();
393 $context->getOutput()->disable();
394
395 $index = $context->getRequest()->getVal( 'wpCaptchaId' );
396 $info = $this->retrieveCaptcha( $index );
397 if ( $info ) {
398 $timestamp = new MWTimestamp();
399 $info['viewed'] = $timestamp->getTimestamp();
400 $this->storeCaptcha( $info );
401
402 $salt = $info['salt'];
403 $hash = $info['hash'];
404
405 return $this->getBackend()->streamFile( [
406 'src' => $this->imagePath( $salt, $hash ),
407 'headers' => [ "Cache-Control: private, s-maxage=0, max-age=3600" ]
408 ] )->isOK();
409 }
410
411 wfHttpError( 400, 'Request Error', 'Requested bogus captcha image' );
412 return false;
413 }
414
415 /**
416 * @param string $salt
417 * @param string $hash
418 * @return string
419 */
420 public function imagePath( $salt, $hash ) {
421 global $wgCaptchaDirectoryLevels;
422
423 $file = $this->getBackend()->getRootStoragePath() . '/' . $this->getStorageDir() . '/';
424 for ( $i = 0; $i < $wgCaptchaDirectoryLevels; $i++ ) {
425 $file .= $hash[ $i ] . '/';
426 }
427 $file .= "image_{$salt}_{$hash}.png";
428
429 return $file;
430 }
431
432 /**
433 * @param string $basename
434 * @return array (salt, hash)
435 */
436 public function hashFromImageName( $basename ) {
437 if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $basename, $matches ) ) {
438 return [ $matches[1], $matches[2] ];
439 } else {
440 throw new InvalidArgumentException( "Invalid filename '$basename'.\n" );
441 }
442 }
443
444 /**
445 * Delete a solved captcha image, if $wgCaptchaDeleteOnSolve is true.
446 * @inheritDoc
447 */
448 protected function passCaptcha( $index, $word ) {
449 global $wgCaptchaDeleteOnSolve;
450
451 if ( !$wgCaptchaDeleteOnSolve || $index === null ) {
452 return parent::passCaptcha( $index, $word, $user );
453 }
454
455 // get the captcha info before it gets deleted
456 $info = $this->retrieveCaptcha( $index );
457 $pass = parent::passCaptcha( $index, $word );
458
459 if ( $pass ) {
460 $this->getBackend()->quickDelete( [
461 'src' => $this->imagePath( $info['salt'], $info['hash'] )
462 ] );
463 }
464
465 return $pass;
466 }
467
468 /**
469 * Returns an array with 'salt' and 'hash' keys. Hash is
470 * md5( $wgCaptchaSecret . $salt . $answer . $wgCaptchaSecret . $salt )[0..15]
471 * @return array
472 * @throws UnderflowException When a captcha image cannot be produced.
473 */
474 public function getCaptcha() {
475 $info = $this->pickImage();
476 if ( !$info ) {
477 throw new UnderflowException( 'Ran out of captcha images' );
478 }
479 return $info;
480 }
481
482 /**
483 * @param array $captchaData
484 * @param string $id
485 * @return string
486 */
487 public function getCaptchaInfo( $captchaData, $id ) {
488 $title = SpecialPage::getTitleFor( 'Captcha', 'image' );
489 return $title->getLocalURL( 'wpCaptchaId=' . urlencode( $id ) );
490 }
491
492 /**
493 * @param array $requests
494 * @param array $fieldInfo
495 * @param array &$formDescriptor
496 * @param string $action
497 */
498 public function onAuthChangeFormFields(
499 array $requests, array $fieldInfo, array &$formDescriptor, $action
500 ) {
501 /** @var CaptchaAuthenticationRequest $req */
502 $req =
503 AuthenticationRequest::getRequestByClass( $requests,
504 CaptchaAuthenticationRequest::class, true );
505 if ( !$req ) {
506 return;
507 }
508
509 // HTMLFancyCaptchaField will include this
510 unset( $formDescriptor['captchaInfo' ] );
511
512 $formDescriptor['captchaWord'] = [
513 'class' => HTMLFancyCaptchaField::class,
514 'imageUrl' => $this->getCaptchaInfo( $req->captchaData, $req->captchaId ),
515 'label-message' => $this->getMessage( $this->action ),
516 'showCreateHelp' => in_array( $action, [
517 AuthManager::ACTION_CREATE,
518 AuthManager::ACTION_CREATE_CONTINUE
519 ], true ),
520 ] + $formDescriptor['captchaWord'];
521 }
522 }
523
524 class_alias( FancyCaptcha::class, 'FancyCaptcha' );