ConfirmEdit: Consistency tweak
[toast/cookiecaptcha.git] / MathCaptcha.class.php
1 <?php
2
3 class MathCaptcha extends SimpleCaptcha {
4
5         /** Validate a captcha response */
6         function keyMatch( $answer, $info ) {
7                 return (int)$answer == (int)$info['answer'];
8         }
9
10         function addCaptchaAPI(&$resultArr) {
11                 list( $sum, $answer ) = $this->pickSum();
12                 $index = $this->storeCaptcha( array('answer' => $answer ) );
13                 $resultArr['captcha']['type'] = 'math';
14                 $resultArr['captcha']['id'] = $index;
15                 $resultArr['captcha']['question'] = $sum;
16         }
17         
18         /** Produce a nice little form */
19         function getForm() {
20                 list( $sum, $answer ) = $this->pickSum();
21                 $index = $this->storeCaptcha( array( 'answer' => $answer ) );
22                 
23                 $form = '<table><tr><td>' . $this->fetchMath( $sum ) . '</td>';
24                 $form .= '<td>' . wfInput( 'wpCaptchaAnswer', false, false, array( 'tabindex' => '1' ) ) . '</td></tr></table>';
25                 $form .= wfHidden( 'wpCaptchaId', $index );
26                 return $form;
27         }
28         
29         /** Pick a random sum */
30         function pickSum() {
31                 $a = mt_rand( 0, 100 );
32                 $b = mt_rand( 0, 10 );
33                 $op = mt_rand( 0, 1 ) ? '+' : '-';
34                 $sum = "{$a} {$op} {$b} = ";
35                 $ans = $op == '+' ? ( $a + $b ) : ( $a - $b );
36                 return array( $sum, $ans );
37         }
38         
39         /** Fetch the math */
40         function fetchMath( $sum ) {
41                 $math = new MathRenderer( $sum );
42                 $math->setOutputMode( MW_MATH_PNG );
43                 $html = $math->render();
44                 return preg_replace( '/alt=".*"/', '', $html );
45         }
46
47 }
48 ?>