MediaWiki REL1_34
MathCaptcha.php
Go to the documentation of this file.
1<?php
2
4
6
13 protected function keyMatch( $answer, $info ) {
14 return (int)$answer == (int)$info['answer'];
15 }
16
20 protected function addCaptchaAPI( &$resultArr ) {
21 list( $sum, $answer ) = $this->pickSum();
22 $html = $this->fetchMath( $sum );
23 $index = $this->storeCaptcha( [ 'answer' => $answer ] );
24 $resultArr['captcha'] = $this->describeCaptchaType();
25 $resultArr['captcha']['id'] = $index;
26 $resultArr['captcha']['question'] = $html;
27 }
28
32 public function describeCaptchaType() {
33 return [
34 'type' => 'math',
35 'mime' => 'text/html',
36 ];
37 }
38
43 public function getFormInformation( $tabIndex = 1 ) {
44 list( $sum, $answer ) = $this->pickSum();
45 $index = $this->storeCaptcha( [ 'answer' => $answer ] );
46
47 $form = '<table><tr><td>' . $this->fetchMath( $sum ) . '</td>';
48 $form .= '<td>' . Html::input( 'wpCaptchaWord', false, false, [
49 'tabindex' => $tabIndex,
50 'autocomplete' => 'off',
51 'required'
52 ] ) . '</td></tr></table>';
53 $form .= Html::hidden( 'wpCaptchaId', $index );
54 return [ 'html' => $form ];
55 }
56
61 private function pickSum() {
62 $a = mt_rand( 0, 100 );
63 $b = mt_rand( 0, 10 );
64 $op = mt_rand( 0, 1 ) ? '+' : '-';
65 $sum = "{$a} {$op} {$b} = ";
66 $ans = $op == '+' ? ( $a + $b ) : ( $a - $b );
67 return [ $sum, $ans ];
68 }
69
75 private function fetchMath( $sum ) {
76 $math = MathRenderer::getRenderer( $sum, [], 'png' );
77 $math->render();
78 $html = $math->getHtmlOutput();
79 return preg_replace( '/alt=".*?"/', '', $html );
80 }
81
85 public function getCaptcha() {
86 list( $sum, $answer ) = $this->pickSum();
87 return [ 'question' => $sum, 'answer' => $answer ];
88 }
89
95 public function getCaptchaInfo( $captchaData, $id ) {
96 $sum = $captchaData['question'];
97 return $this->fetchMath( $sum );
98 }
99
106 public function onAuthChangeFormFields( array $requests, array $fieldInfo,
107 array &$formDescriptor, $action ) {
109 $req = AuthenticationRequest::getRequestByClass(
110 $requests,
111 CaptchaAuthenticationRequest::class,
112 true
113 );
114 if ( !$req ) {
115 return;
116 }
117
118 $formDescriptor['captchaInfo']['raw'] = true;
119 $formDescriptor['captchaWord']['label-message'] = null;
120 }
121}
addCaptchaAPI(&$resultArr)
pickSum()
Pick a random sum.
getFormInformation( $tabIndex=1)
keyMatch( $answer, $info)
Validate a captcha response.
getCaptchaInfo( $captchaData, $id)
onAuthChangeFormFields(array $requests, array $fieldInfo, array &$formDescriptor, $action)
fetchMath( $sum)
Fetch the math.
This is a value object for authentication requests.
Demo CAPTCHA (not for production usage) and base class for real CAPTCHAs.
string $action
Used to select the right message.
storeCaptcha( $info)
Generate a captcha session ID and save the info in PHP's session storage.