final move of files
[web.mtrack] / MTrack / Captcha / Recaptcha.php
1 <?php # vim:ts=2:sw=2:et:
2 /* For licensing and copyright terms, see the file named LICENSE */
3
4
5
6 class MTrack_Captcha_Recaptcha implements MTrack_Implementation_Captcha 
7 {
8   public $errcode = null;
9   public $pub;
10   public $priv;
11   public $userclass;
12
13   function __construct($pub, $priv, $userclass = 'anonymous|authenticated') {
14     $this->pub = $pub;
15     $this->priv = $priv;
16     $this->userclass = explode("|", $userclass);
17     MTrackCaptcha::register($this);
18   }
19
20   function emit($form)
21   {
22     $class = MTrackAuth::getUserClass();
23     if (!in_array($class, $this->userclass)) {
24       return '';
25     }
26     $pub = $this->pub;
27     $err = $this->errcode === null ? '' : "&error=$this->errcode";
28     return <<<HTML
29 <script type='text/javascript' src="https://api-secure.recaptcha.net/challenge?k=$pub$err"></script>
30 <noscript>
31   <iframe src="https://api-secure.recaptcha.net/noscript?k=$pub$err"
32     height="300" width="500" frameborder="0"></iframe>
33   <br/>
34   <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea>
35   <input type="hidden" name="recaptcha_response_field"
36     value="manual_challenge"/>
37 </noscript>
38 HTML;
39   }
40
41   function check($form)
42   {
43     $class = MTrackAuth::getUserClass();
44     if (!in_array($class, $this->userclass)) {
45       return true;
46     }
47     if (empty($_POST['recaptcha_challenge_field']) or
48         empty($_POST['recaptcha_response_field'])) {
49       return array('false', 'incorrect-captcha-sol');
50     }
51
52     $data = http_build_query(array(
53           'privatekey' => $this->priv,
54           'remoteip' => $_SERVER['REMOTE_ADDR'],
55           'challenge' => $_POST['recaptcha_challenge_field'],
56           'response' => $_POST['recaptcha_response_field'],
57           ));
58     $params = array(
59         'http' => array(
60           'method' => 'POST',
61           'content' => $data,
62           ),
63         );
64     $ctx = stream_context_create($params);
65
66     /* first line: true/false
67      * second line: error code
68      */
69     $res = array();
70     foreach (file('http://api-verify.recaptcha.net/verify', 0, $ctx) as $line) {
71       $res[] = trim($line);
72     }
73     if ($res[0] == 'true') {
74       return true;
75     }
76     $this->errcode = $res[1];
77     return false;
78   }
79
80 }
81