MediaWiki REL1_31
FancyCaptcha.class.php
Go to the documentation of this file.
1<?php
2
5
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 $modules = [];
115
116 $title = SpecialPage::getTitleFor( 'Captcha', 'image' );
117 $info = $this->getCaptcha();
118 $index = $this->storeCaptcha( $info );
119
120 // Loaded only for clients with JS enabled
121 $modules[] = 'ext.confirmEdit.fancyCaptcha';
122
123 $captchaReload = Html::element(
124 'small',
125 [
126 'class' => 'confirmedit-captcha-reload fancycaptcha-reload'
127 ],
128 wfMessage( 'fancycaptcha-reload-text' )->text()
129 );
130
131 $form = Html::openElement( 'div' ) .
132 Html::element( 'label', [
133 'for' => 'wpCaptchaWord',
134 ],
135 wfMessage( 'captcha-label' )->text() . ' ' . wfMessage( 'fancycaptcha-captcha' )->text()
136 ) .
137 Html::openElement( 'div', [ 'class' => 'fancycaptcha-captcha-container' ] ) .
138 Html::openElement( 'div', [ 'class' => 'fancycaptcha-captcha-and-reload' ] ) .
139 Html::openElement( 'div', [ 'class' => 'fancycaptcha-image-container' ] ) .
140 Html::element( 'img', [
141 'class' => 'fancycaptcha-image',
142 'src' => $title->getLocalURL( 'wpCaptchaId=' . urlencode( $index ) ),
143 'alt' => ''
144 ]
145 ) . $captchaReload . Html::closeElement( 'div' ) . Html::closeElement( 'div' ) . "\n" .
146 Html::element( 'input', [
147 'name' => 'wpCaptchaWord',
148 'class' => 'mw-ui-input',
149 'id' => 'wpCaptchaWord',
150 'type' => 'text',
151 'size' => '12', // max_length in captcha.py plus fudge factor
152 'autocomplete' => 'off',
153 'autocorrect' => 'off',
154 'autocapitalize' => 'off',
155 'required' => 'required',
156 'tabindex' => $tabIndex,
157 'placeholder' => wfMessage( 'fancycaptcha-imgcaptcha-ph' )
158 ]
159 ); // tab in before the edit textarea
160 if ( $this->action == 'createaccount' ) {
161 // use raw element, because the message can contain links or some other html
162 $form .= Html::rawElement( 'small', [
163 'class' => 'mw-createacct-captcha-assisted'
164 ], wfMessage( 'createacct-imgcaptcha-help' )->parse()
165 );
166 }
167 $form .= Html::element( 'input', [
168 'type' => 'hidden',
169 'name' => 'wpCaptchaId',
170 'id' => 'wpCaptchaId',
171 'value' => $index
172 ]
173 ) . Html::closeElement( 'div' ) . Html::closeElement( 'div' ) . "\n";
174
175 return [
176 'html' => $form,
177 'modules' => $modules,
178 // Uses addModuleStyles so it is loaded when JS is disabled.
179 'modulestyles' => [ 'ext.confirmEdit.fancyCaptcha.styles' ],
180 ];
181 }
182
187 protected function pickImage() {
188 global $wgCaptchaDirectoryLevels;
189
190 $lockouts = 0; // number of times another process claimed a file before this one
191 $baseDir = $this->getBackend()->getRootStoragePath() . '/captcha-render';
192 return $this->pickImageDir( $baseDir, $wgCaptchaDirectoryLevels, $lockouts );
193 }
194
201 protected function pickImageDir( $directory, $levels, &$lockouts ) {
202 global $wgMemc;
203
204 if ( $levels <= 0 ) { // $directory has regular files
205 return $this->pickImageFromDir( $directory, $lockouts );
206 }
207
208 $backend = $this->getBackend();
209
210 $key = "fancycaptcha:dirlist:{$backend->getWikiId()}:" . sha1( $directory );
211 $dirs = $wgMemc->get( $key ); // check cache
212 if ( !is_array( $dirs ) || !count( $dirs ) ) { // cache miss
213 $dirs = []; // subdirs actually present...
214 foreach ( $backend->getTopDirectoryList( [ 'dir' => $directory ] ) as $entry ) {
215 if ( ctype_xdigit( $entry ) && strlen( $entry ) == 1 ) {
216 $dirs[] = $entry;
217 }
218 }
219 wfDebug( "Cache miss for $directory subdirectory listing.\n" );
220 if ( count( $dirs ) ) {
221 $wgMemc->set( $key, $dirs, 86400 );
222 }
223 }
224
225 if ( !count( $dirs ) ) {
226 // Remove this directory if empty so callers don't keep looking here
227 $backend->clean( [ 'dir' => $directory ] );
228 return false; // none found
229 }
230
231 $place = mt_rand( 0, count( $dirs ) - 1 ); // pick a random subdir
232 // In case all dirs are not filled, cycle through next digits...
233 $fancyCount = count( $dirs );
234 for ( $j = 0; $j < $fancyCount; $j++ ) {
235 $char = $dirs[( $place + $j ) % count( $dirs )];
236 $info = $this->pickImageDir( "$directory/$char", $levels - 1, $lockouts );
237 if ( $info ) {
238 return $info; // found a captcha
239 } else {
240 wfDebug( "Could not find captcha in $directory.\n" );
241 $wgMemc->delete( $key ); // files changed on disk?
242 }
243 }
244
245 return false; // didn't find any images in this directory... empty?
246 }
247
253 protected function pickImageFromDir( $directory, &$lockouts ) {
254 global $wgMemc;
255
256 $backend = $this->getBackend();
257
258 $key = "fancycaptcha:filelist:{$backend->getWikiId()}:" . sha1( $directory );
259 $files = $wgMemc->get( $key ); // check cache
260 if ( !is_array( $files ) || !count( $files ) ) { // cache miss
261 $files = []; // captcha files
262 foreach ( $backend->getTopFileList( [ 'dir' => $directory ] ) as $entry ) {
263 $files[] = $entry;
264 if ( count( $files ) >= 500 ) { // sanity
265 wfDebug( 'Skipping some captchas; $wgCaptchaDirectoryLevels set too low?.' );
266 break;
267 }
268 }
269 if ( count( $files ) ) {
270 $wgMemc->set( $key, $files, 86400 );
271 }
272 wfDebug( "Cache miss for $directory captcha listing.\n" );
273 }
274
275 if ( !count( $files ) ) {
276 // Remove this directory if empty so callers don't keep looking here
277 $backend->clean( [ 'dir' => $directory ] );
278 return false;
279 }
280
281 $info = $this->pickImageFromList( $directory, $files, $lockouts );
282 if ( !$info ) {
283 wfDebug( "Could not find captcha in $directory.\n" );
284 $wgMemc->delete( $key ); // files changed on disk?
285 }
286
287 return $info;
288 }
289
296 protected function pickImageFromList( $directory, array $files, &$lockouts ) {
297 global $wgMemc, $wgCaptchaDeleteOnSolve;
298
299 if ( !count( $files ) ) {
300 return false; // none found
301 }
302
303 $backend = $this->getBackend();
304 $place = mt_rand( 0, count( $files ) - 1 ); // pick a random file
305 $misses = 0; // number of files in listing that don't actually exist
306 $fancyImageCount = count( $files );
307 for ( $j = 0; $j < $fancyImageCount; $j++ ) {
308 $entry = $files[( $place + $j ) % count( $files )];
309 if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $entry, $matches ) ) {
310 if ( $wgCaptchaDeleteOnSolve ) { // captcha will be deleted when solved
311 $key = "fancycaptcha:filelock:{$backend->getWikiId()}:" . sha1( $entry );
312 // Try to claim this captcha for 10 minutes (for the user to solve)...
313 if ( ++$lockouts <= 10 && !$wgMemc->add( $key, '1', 600 ) ) {
314 continue; // could not acquire (skip it to avoid race conditions)
315 }
316 }
317 if ( !$backend->fileExists( [ 'src' => "$directory/$entry" ] ) ) {
318 if ( ++$misses >= 5 ) { // too many files in the listing don't exist
319 break; // listing cache too stale? break out so it will be cleared
320 }
321 continue; // try next file
322 }
323 return [
324 'salt' => $matches[1],
325 'hash' => $matches[2],
326 'viewed' => false,
327 ];
328 }
329 }
330
331 return false; // none found
332 }
333
337 function showImage() {
338 global $wgOut, $wgRequest;
339
340 $wgOut->disable();
341
342 $index = $wgRequest->getVal( 'wpCaptchaId' );
343 $info = $this->retrieveCaptcha( $index );
344 if ( $info ) {
345 $timestamp = new MWTimestamp();
346 $info['viewed'] = $timestamp->getTimestamp();
347 $this->storeCaptcha( $info );
348
349 $salt = $info['salt'];
350 $hash = $info['hash'];
351
352 return $this->getBackend()->streamFile( [
353 'src' => $this->imagePath( $salt, $hash ),
354 'headers' => [ "Cache-Control: private, s-maxage=0, max-age=3600" ]
355 ] )->isOK();
356 }
357
358 wfHttpError( 400, 'Request Error', 'Requested bogus captcha image' );
359 return false;
360 }
361
367 public function imagePath( $salt, $hash ) {
368 global $wgCaptchaDirectoryLevels;
369
370 $file = $this->getBackend()->getRootStoragePath() . '/captcha-render/';
371 for ( $i = 0; $i < $wgCaptchaDirectoryLevels; $i++ ) {
372 $file .= $hash{ $i } . '/';
373 }
374 $file .= "image_{$salt}_{$hash}.png";
375
376 return $file;
377 }
378
384 public function hashFromImageName( $basename ) {
385 if ( preg_match( '/^image_([0-9a-f]+)_([0-9a-f]+)\\.png$/', $basename, $matches ) ) {
386 return [ $matches[1], $matches[2] ];
387 } else {
388 throw new Exception( "Invalid filename '$basename'.\n" );
389 }
390 }
391
396 protected function passCaptcha( $index, $word ) {
397 global $wgCaptchaDeleteOnSolve;
398
399 $info = $this->retrieveCaptcha( $index ); // get the captcha info before it gets deleted
400 $pass = parent::passCaptcha( $index, $word );
401
402 if ( $pass && $wgCaptchaDeleteOnSolve ) {
403 $this->getBackend()->quickDelete( [
404 'src' => $this->imagePath( $info['salt'], $info['hash'] )
405 ] );
406 }
407
408 return $pass;
409 }
410
417 public function getCaptcha() {
418 $info = $this->pickImage();
419 if ( !$info ) {
420 throw new UnderflowException( 'Ran out of captcha images' );
421 }
422 return $info;
423 }
424
430 public function getCaptchaInfo( $captchaData, $id ) {
431 $title = SpecialPage::getTitleFor( 'Captcha', 'image' );
432 return $title->getLocalURL( 'wpCaptchaId=' . urlencode( $id ) );
433 }
434
441 public function onAuthChangeFormFields(
442 array $requests, array $fieldInfo, array &$formDescriptor, $action
443 ) {
445 $req =
446 AuthenticationRequest::getRequestByClass( $requests,
447 CaptchaAuthenticationRequest::class, true );
448 if ( !$req ) {
449 return;
450 }
451
452 // HTMLFancyCaptchaField will include this
453 unset( $formDescriptor['captchaInfo' ] );
454
455 $formDescriptor['captchaWord'] = [
456 'class' => HTMLFancyCaptchaField::class,
457 'imageUrl' => $this->getCaptchaInfo( $req->captchaData, $req->captchaId ),
458 'label-message' => $this->getMessage( $this->action ),
459 'showCreateHelp' => in_array( $action, [
460 AuthManager::ACTION_CREATE,
461 AuthManager::ACTION_CREATE_CONTINUE
462 ], true ),
463 ] + $formDescriptor['captchaWord'];
464 }
465}
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfHttpError( $code, $label, $desc)
Provide a simple HTTP error.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
$wgOut
Definition Setup.php:912
if(! $wgDBerrorLogTZ) $wgRequest
Definition Setup.php:737
Class for a file system (FS) based file backend.
FancyCaptcha for displaying captchas precomputed by captcha.py.
imagePath( $salt, $hash)
pickImage()
Select a previously generated captcha image from the queue.
passCaptcha( $index, $word)
Delete a solved captcha image, if $wgCaptchaDeleteOnSolve is true.
addCaptchaAPI(&$resultArr)
getFormInformation( $tabIndex=1)
getCaptcha()
Returns an array with 'salt' and 'hash' keys.
pickImageFromList( $directory, array $files, &$lockouts)
pickImageDir( $directory, $levels, &$lockouts)
getCaptchaInfo( $captchaData, $id)
hashFromImageName( $basename)
keyMatch( $answer, $info)
Check if the submitted form matches the captcha session data provided by the plugin when the form was...
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
pickImageFromDir( $directory, &$lockouts)
Library for creating and parsing MW-style timestamps.
This serves as the entry point to the authentication system.
This is a value object for authentication requests.
Simple version of LockManager that does nothing.
Demo CAPTCHA (not for production usage) and base class for real CAPTCHAs.
Definition Captcha.php:8
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:229
retrieveCaptcha( $index)
Fetch this session's captcha info.
Definition Captcha.php:1072
string $action
Used to select the right message.
Definition Captcha.php:19
storeCaptcha( $info)
Generate a captcha session ID and save the info in PHP's session storage.
Definition Captcha.php:1058
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:18
this hook is for auditing only $req
Definition hooks.txt:990
An extension or a local 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:56
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;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
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:304
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:66