MediaWiki  1.29.1
FancyCaptcha.class.php
Go to the documentation of this file.
1 <?php
2 
3 use MediaWiki\Auth\AuthenticationRequest;
4 use MediaWiki\Auth\AuthManager;
5 
9 class FancyCaptcha extends SimpleCaptcha {
10  // used for fancycaptcha-edit, fancycaptcha-addurl, fancycaptcha-badlogin,
11  // fancycaptcha-accountcreate, fancycaptcha-create, fancycaptcha-sendemail via getMessage()
12  protected static $messagePrefix = 'fancycaptcha-';
13 
17  public function getBackend() {
18  global $wgCaptchaFileBackend, $wgCaptchaDirectory;
19 
20  if ( $wgCaptchaFileBackend ) {
21  return FileBackendGroup::singleton()->get( $wgCaptchaFileBackend );
22  } else {
23  static $backend = null;
24  if ( !$backend ) {
25  $backend = new FSFileBackend( [
26  'name' => 'captcha-backend',
27  'wikiId' => wfWikiID(),
28  'lockManager' => new NullLockManager( [] ),
29  'containerPaths' => [ 'captcha-render' => $wgCaptchaDirectory ],
30  'fileMode' => 777,
31  'obResetFunc' => 'wfResetOutputBuffers',
32  'streamMimeFunc' => [ 'StreamFile', 'contentTypeFromPath' ]
33  ] );
34  }
35  return $backend;
36  }
37  }
38 
43  public function estimateCaptchaCount() {
44  wfDeprecated( __METHOD__ );
45  return $this->getCaptchaCount();
46  }
47 
51  public function getCaptchaCount() {
52  $backend = $this->getBackend();
53  $files = $backend->getFileList(
54  [ 'dir' => $backend->getRootStoragePath() . '/captcha-render' ]
55  );
56 
57  return iterator_count( $files );
58  }
59 
68  function keyMatch( $answer, $info ) {
69  global $wgCaptchaSecret;
70 
71  $digest = $wgCaptchaSecret . $info['salt'] . $answer . $wgCaptchaSecret . $info['salt'];
72  $answerHash = substr( md5( $digest ), 0, 16 );
73 
74  if ( $answerHash == $info['hash'] ) {
75  wfDebug( "FancyCaptcha: answer hash matches expected {$info['hash']}\n" );
76  return true;
77  } else {
78  wfDebug( "FancyCaptcha: answer hashes to $answerHash, expected {$info['hash']}\n" );
79  return false;
80  }
81  }
82 
86  function addCaptchaAPI( &$resultArr ) {
87  $info = $this->pickImage();
88  if ( !$info ) {
89  $resultArr['captcha']['error'] = 'Out of images';
90  return;
91  }
92  $index = $this->storeCaptcha( $info );
93  $title = SpecialPage::getTitleFor( 'Captcha', 'image' );
94  $resultArr['captcha'] = $this->describeCaptchaType();
95  $resultArr['captcha']['id'] = $index;
96  $resultArr['captcha']['url'] = $title->getLocalURL( 'wpCaptchaId=' . urlencode( $index ) );
97  }
98 
102  public function describeCaptchaType() {
103  return [
104  'type' => 'image',
105  'mime' => 'image/png',
106  ];
107  }
108 
113  function getFormInformation( $tabIndex = 1 ) {
114  global $wgEnableAPI;
115  $modules = [];
116 
117  $title = SpecialPage::getTitleFor( 'Captcha', 'image' );
118  $info = $this->getCaptcha();
119  $index = $this->storeCaptcha( $info );
120 
121  if ( $wgEnableAPI ) {
122  // Loaded only if JS is enabled
123  $modules[] = 'ext.confirmEdit.fancyCaptcha';
124 
125  $captchaReload = Html::element(
126  'small',
127  [
128  'class' => 'confirmedit-captcha-reload fancycaptcha-reload'
129  ],
130  wfMessage( 'fancycaptcha-reload-text' )->text()
131  );
132  } else {
133  $captchaReload = '';
134  }
135 
136  $form = Html::openElement( 'div' ) .
137  Html::element( 'label', [
138  'for' => 'wpCaptchaWord',
139  ],
140  wfMessage( 'captcha-label' )->text() . ' ' . wfMessage( 'fancycaptcha-captcha' )->text()
141  ) .
142  Html::openElement( 'div', [ 'class' => 'fancycaptcha-captcha-container' ] ) .
143  Html::openElement( 'div', [ 'class' => 'fancycaptcha-captcha-and-reload' ] ) .
144  Html::openElement( 'div', [ 'class' => 'fancycaptcha-image-container' ] ) .
145  Html::element( 'img', [
146  'class' => 'fancycaptcha-image',
147  'src' => $title->getLocalURL( 'wpCaptchaId=' . urlencode( $index ) ),
148  'alt' => ''
149  ]
150  ) . $captchaReload . Html::closeElement( 'div' ) . Html::closeElement( 'div' ) . "\n" .
151  Html::element( 'input', [
152  'name' => 'wpCaptchaWord',
153  'class' => 'mw-ui-input',
154  'id' => 'wpCaptchaWord',
155  'type' => 'text',
156  'size' => '12', // max_length in captcha.py plus fudge factor
157  'autocomplete' => 'off',
158  'autocorrect' => 'off',
159  'autocapitalize' => 'off',
160  'required' => 'required',
161  'tabindex' => $tabIndex,
162  'placeholder' => wfMessage( 'fancycaptcha-imgcaptcha-ph' )
163  ]
164  ); // tab in before the edit textarea
165  if ( $this->action == 'createaccount' ) {
166  // use raw element, because the message can contain links or some other html
167  $form .= Html::rawElement( 'small', [
168  'class' => 'mw-createacct-captcha-assisted'
169  ], wfMessage( 'createacct-imgcaptcha-help' )->parse()
170  );
171  }
172  $form .= Html::element( 'input', [
173  'type' => 'hidden',
174  'name' => 'wpCaptchaId',
175  'id' => 'wpCaptchaId',
176  'value' => $index
177  ]
178  ) . Html::closeElement( 'div' ) . Html::closeElement( 'div' ) . "\n";
179 
180  return [
181  'html' => $form,
182  'modules' => $modules,
183  // Uses addModuleStyles so it is loaded when JS is disabled.
184  'modulestyles' => [ 'ext.confirmEdit.fancyCaptcha.styles' ],
185  ];
186  }
187 
192  protected function pickImage() {
193  global $wgCaptchaDirectoryLevels;
194 
195  $lockouts = 0; // number of times another process claimed a file before this one
196  $baseDir = $this->getBackend()->getRootStoragePath() . '/captcha-render';
197  return $this->pickImageDir( $baseDir, $wgCaptchaDirectoryLevels, $lockouts );
198  }
199 
206  protected function pickImageDir( $directory, $levels, &$lockouts ) {
207  global $wgMemc;
208 
209  if ( $levels <= 0 ) { // $directory has regular files
210  return $this->pickImageFromDir( $directory, $lockouts );
211  }
212 
213  $backend = $this->getBackend();
214 
215  $key = "fancycaptcha:dirlist:{$backend->getWikiId()}:" . sha1( $directory );
216  $dirs = $wgMemc->get( $key ); // check cache
217  if ( !is_array( $dirs ) || !count( $dirs ) ) { // cache miss
218  $dirs = []; // subdirs actually present...
219  foreach ( $backend->getTopDirectoryList( [ 'dir' => $directory ] ) as $entry ) {
220  if ( ctype_xdigit( $entry ) && strlen( $entry ) == 1 ) {
221  $dirs[] = $entry;
222  }
223  }
224  wfDebug( "Cache miss for $directory subdirectory listing.\n" );
225  if ( count( $dirs ) ) {
226  $wgMemc->set( $key, $dirs, 86400 );
227  }
228  }
229 
230  if ( !count( $dirs ) ) {
231  // Remove this directory if empty so callers don't keep looking here
232  $backend->clean( [ 'dir' => $directory ] );
233  return false; // none found
234  }
235 
236  $place = mt_rand( 0, count( $dirs ) - 1 ); // pick a random subdir
237  // In case all dirs are not filled, cycle through next digits...
238  $fancyCount = count( $dirs );
239  for ( $j = 0; $j < $fancyCount; $j++ ) {
240  $char = $dirs[( $place + $j ) % count( $dirs )];
241  $info = $this->pickImageDir( "$directory/$char", $levels - 1, $lockouts );
242  if ( $info ) {
243  return $info; // found a captcha
244  } else {
245  wfDebug( "Could not find captcha in $directory.\n" );
246  $wgMemc->delete( $key ); // files changed on disk?
247  }
248  }
249 
250  return false; // didn't find any images in this directory... empty?
251  }
252 
258  protected function pickImageFromDir( $directory, &$lockouts ) {
259  global $wgMemc;
260 
261  $backend = $this->getBackend();
262 
263  $key = "fancycaptcha:filelist:{$backend->getWikiId()}:" . sha1( $directory );
264  $files = $wgMemc->get( $key ); // check cache
265  if ( !is_array( $files ) || !count( $files ) ) { // cache miss
266  $files = []; // captcha files
267  foreach ( $backend->getTopFileList( [ 'dir' => $directory ] ) as $entry ) {
268  $files[] = $entry;
269  if ( count( $files ) >= 500 ) { // sanity
270  wfDebug( 'Skipping some captchas; $wgCaptchaDirectoryLevels set too low?.' );
271  break;
272  }
273  }
274  if ( count( $files ) ) {
275  $wgMemc->set( $key, $files, 86400 );
276  }
277  wfDebug( "Cache miss for $directory captcha listing.\n" );
278  }
279 
280  if ( !count( $files ) ) {
281  // Remove this directory if empty so callers don't keep looking here
282  $backend->clean( [ 'dir' => $directory ] );
283  return false;
284  }
285 
286  $info = $this->pickImageFromList( $directory, $files, $lockouts );
287  if ( !$info ) {
288  wfDebug( "Could not find captcha in $directory.\n" );
289  $wgMemc->delete( $key ); // files changed on disk?
290  }
291 
292  return $info;
293  }
294 
301  protected function pickImageFromList( $directory, array $files, &$lockouts ) {
302  global $wgMemc, $wgCaptchaDeleteOnSolve;
303 
304  if ( !count( $files ) ) {
305  return false; // none found
306  }
307 
308  $backend = $this->getBackend();
309  $place = mt_rand( 0, count( $files ) - 1 ); // pick a random file
310  $misses = 0; // number of files in listing that don't actually exist
311  $fancyImageCount = count( $files );
312  for ( $j = 0; $j < $fancyImageCount; $j++ ) {
313  $entry = $files[( $place + $j ) % count( $files )];
314  if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
315  if ( $wgCaptchaDeleteOnSolve ) { // captcha will be deleted when solved
316  $key = "fancycaptcha:filelock:{$backend->getWikiId()}:" . sha1( $entry );
317  // Try to claim this captcha for 10 minutes (for the user to solve)...
318  if ( ++$lockouts <= 10 && !$wgMemc->add( $key, '1', 600 ) ) {
319  continue; // could not acquire (skip it to avoid race conditions)
320  }
321  }
322  if ( !$backend->fileExists( [ 'src' => "$directory/$entry" ] ) ) {
323  if ( ++$misses >= 5 ) { // too many files in the listing don't exist
324  break; // listing cache too stale? break out so it will be cleared
325  }
326  continue; // try next file
327  }
328  return [
329  'salt' => $matches[1],
330  'hash' => $matches[2],
331  'viewed' => false,
332  ];
333  }
334  }
335 
336  return false; // none found
337  }
338 
342  function showImage() {
344 
345  $wgOut->disable();
346 
347  $index = $wgRequest->getVal( 'wpCaptchaId' );
348  $info = $this->retrieveCaptcha( $index );
349  if ( $info ) {
350  $timestamp = new MWTimestamp();
351  $info['viewed'] = $timestamp->getTimestamp();
352  $this->storeCaptcha( $info );
353 
354  $salt = $info['salt'];
355  $hash = $info['hash'];
356 
357  return $this->getBackend()->streamFile( [
358  'src' => $this->imagePath( $salt, $hash ),
359  'headers' => [ "Cache-Control: private, s-maxage=0, max-age=3600" ]
360  ] )->isOK();
361  }
362 
363  wfHttpError( 400, 'Request Error', 'Requested bogus captcha image' );
364  return false;
365  }
366 
372  public function imagePath( $salt, $hash ) {
373  global $wgCaptchaDirectoryLevels;
374 
375  $file = $this->getBackend()->getRootStoragePath() . '/captcha-render/';
376  for ( $i = 0; $i < $wgCaptchaDirectoryLevels; $i++ ) {
377  $file .= $hash{ $i } . '/';
378  }
379  $file .= "image_{$salt}_{$hash}.png";
380 
381  return $file;
382  }
383 
389  public function hashFromImageName( $basename ) {
390  if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $basename, $matches ) ) {
391  return [ $matches[1], $matches[2] ];
392  } else {
393  throw new Exception( "Invalid filename '$basename'.\n" );
394  }
395  }
396 
401  protected function passCaptcha( $index, $word ) {
402  global $wgCaptchaDeleteOnSolve;
403 
404  $info = $this->retrieveCaptcha( $index ); // get the captcha info before it gets deleted
405  $pass = parent::passCaptcha( $index, $word );
406 
407  if ( $pass && $wgCaptchaDeleteOnSolve ) {
408  $this->getBackend()->quickDelete( [
409  'src' => $this->imagePath( $info['salt'], $info['hash'] )
410  ] );
411  }
412 
413  return $pass;
414  }
415 
422  public function getCaptcha() {
423  $info = $this->pickImage();
424  if ( !$info ) {
425  throw new UnderflowException( 'Ran out of captcha images' );
426  }
427  return $info;
428  }
429 
435  public function getCaptchaInfo( $captchaData, $id ) {
436  $title = SpecialPage::getTitleFor( 'Captcha', 'image' );
437  return $title->getLocalURL( 'wpCaptchaId=' . urlencode( $id ) );
438  }
439 
446  public function onAuthChangeFormFields(
447  array $requests, array $fieldInfo, array &$formDescriptor, $action
448  ) {
450  $req =
451  AuthenticationRequest::getRequestByClass( $requests,
453  if ( !$req ) {
454  return;
455  }
456 
457  // HTMLFancyCaptchaField will include this
458  unset( $formDescriptor['captchaInfo' ] );
459 
460  $formDescriptor['captchaWord'] = [
461  'class' => HTMLFancyCaptchaField::class,
462  'imageUrl' => $this->getCaptchaInfo( $req->captchaData, $req->captchaId ),
463  'label-message' => $this->getMessage( $this->action ),
464  'showCreateHelp' => in_array( $action, [
465  AuthManager::ACTION_CREATE,
466  AuthManager::ACTION_CREATE_CONTINUE
467  ], true ),
468  ] + $formDescriptor['captchaWord'];
469  }
470 }
MWTimestamp
Library for creating and parsing MW-style timestamps.
Definition: MWTimestamp.php:32
FancyCaptcha::onAuthChangeFormFields
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
Definition: FancyCaptcha.class.php:446
FancyCaptcha::getCaptchaCount
getCaptchaCount()
Definition: FancyCaptcha.class.php:51
FancyCaptcha::pickImageFromDir
pickImageFromDir( $directory, &$lockouts)
Definition: FancyCaptcha.class.php:258
FancyCaptcha::pickImageFromList
pickImageFromList( $directory, array $files, &$lockouts)
Definition: FancyCaptcha.class.php:301
FancyCaptcha::imagePath
imagePath( $salt, $hash)
Definition: FancyCaptcha.class.php:372
captcha-old.count
count
Definition: captcha-old.py:225
$wgMemc
globals will be eliminated from MediaWiki replaced by an application object which would be passed to constructors Whether that would be an convenient solution remains to be but certainly PHP makes such object oriented programming models easier than they were in previous versions For the time being MediaWiki programmers will have to work in an environment with some global context At the time of globals were initialised on startup by MediaWiki of these were configuration which are documented in DefaultSettings php There is no comprehensive documentation for the remaining however some of the most important ones are listed below They are typically initialised either in index php or in Setup php For a description of the see design txt $wgTitle Title object created from the request URL $wgOut OutputPage object for HTTP response $wgUser User object for the user associated with the current request $wgLang Language object selected by user preferences $wgContLang Language object associated with the wiki being viewed $wgParser Parser object Parser extensions register their hooks here $wgRequest WebRequest to get request data $wgMemc
Definition: globals.txt:25
text
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$req
this hook is for auditing only $req
Definition: hooks.txt:990
add
An extension or a will often add custom code to the function with or without a global variable For someone wanting email notification when an article is shown may add
Definition: hooks.txt:51
SpecialPage\getTitleFor
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
Definition: SpecialPage.php:82
FancyCaptcha::getCaptchaInfo
getCaptchaInfo( $captchaData, $id)
Definition: FancyCaptcha.class.php:435
SimpleCaptcha\$action
string $action
Used to select the right message.
Definition: Captcha.php:20
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
FancyCaptcha::pickImage
pickImage()
Select a previously generated captcha image from the queue.
Definition: FancyCaptcha.class.php:192
FileBackendGroup\singleton
static singleton()
Definition: FileBackendGroup.php:46
Html\closeElement
static closeElement( $element)
Returns "</$element>".
Definition: Html.php:309
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
NullLockManager
Simple version of LockManager that does nothing.
Definition: NullLockManager.php:29
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1128
FancyCaptcha::getBackend
getBackend()
Definition: FancyCaptcha.class.php:17
$matches
$matches
Definition: NoLocalSettings.php:24
FancyCaptcha::addCaptchaAPI
addCaptchaAPI(&$resultArr)
Definition: FancyCaptcha.class.php:86
$modules
$modules
Definition: HTMLFormElement.php:12
FancyCaptcha::pickImageDir
pickImageDir( $directory, $levels, &$lockouts)
Definition: FancyCaptcha.class.php:206
$dirs
$dirs
Definition: mergeMessageFileList.php:195
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
FancyCaptcha::showImage
showImage()
Definition: FancyCaptcha.class.php:342
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:999
FancyCaptcha::getCaptcha
getCaptcha()
Returns an array with 'salt' and 'hash' keys.
Definition: FancyCaptcha.class.php:422
captcha-old.action
action
Definition: captcha-old.py:189
FancyCaptcha::$messagePrefix
static $messagePrefix
Definition: FancyCaptcha.class.php:12
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:3011
FancyCaptcha::keyMatch
keyMatch( $answer, $info)
Check if the submitted form matches the captcha session data provided by the plugin when the form was...
Definition: FancyCaptcha.class.php:68
SimpleCaptcha\retrieveCaptcha
retrieveCaptcha( $index)
Fetch this session's captcha info.
Definition: Captcha.php:1046
FancyCaptcha
FancyCaptcha for displaying captchas precomputed by captcha.py.
Definition: FancyCaptcha.class.php:9
FancyCaptcha::describeCaptchaType
describeCaptchaType()
Definition: FancyCaptcha.class.php:102
SimpleCaptcha
Demo CAPTCHA (not for production usage) and base class for real CAPTCHAs.
Definition: Captcha.php:9
SimpleCaptcha\storeCaptcha
storeCaptcha( $info)
Generate a captcha session ID and save the info in PHP's session storage.
Definition: Captcha.php:1032
FancyCaptcha::hashFromImageName
hashFromImageName( $basename)
Definition: FancyCaptcha.class.php:389
SimpleCaptcha\getMessage
getMessage( $action)
Show a message asking the user to enter a captcha on edit The result will be treated as wiki text.
Definition: Captcha.php:230
FancyCaptcha::passCaptcha
passCaptcha( $index, $word)
Delete a solved captcha image, if $wgCaptchaDeleteOnSolve is true.
Definition: FancyCaptcha.class.php:401
wfHttpError
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
Definition: GlobalFunctions.php:1765
FSFileBackend
Class for a file system (FS) based file backend.
Definition: FSFileBackend.php:42
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
Html\openElement
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
Definition: Html.php:251
Html\rawElement
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
$requests
Allows to change the fields on the form that will be generated are created Can be used to omit specific feeds from being outputted You must not use this hook to add use OutputPage::addFeedLink() instead. & $feedLinks hooks can tweak the array to change how login etc forms should look $requests
Definition: hooks.txt:306
FancyCaptcha::getFormInformation
getFormInformation( $tabIndex=1)
Definition: FancyCaptcha.class.php:113
FancyCaptcha::estimateCaptchaCount
estimateCaptchaCount()
Definition: FancyCaptcha.class.php:43
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
$wgRequest
if(! $wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:639
Html\element
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
$wgOut
$wgOut
Definition: Setup.php:791
array
the array() calling protocol came about after MediaWiki 1.4rc1.