xref: /plugin/captcha/helper.php (revision a285df67bba92c0e515b79f89013d7edbd478251)
1<?php
2/**
3 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
4 * @author     Andreas Gohr <andi@splitbrain.org>
5 */
6
7// must be run within Dokuwiki
8if(!defined('DOKU_INC')) die();
9if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
10
11/**
12 * Class helper_plugin_captcha
13 */
14class helper_plugin_captcha extends DokuWiki_Plugin {
15
16    protected $field_in = 'plugin__captcha';
17    protected $field_sec = 'plugin__captcha_secret';
18    protected $field_hp = 'plugin__captcha_honeypot';
19
20    /**
21     * Constructor. Initializes field names
22     */
23    public function __construct() {
24        $this->field_in  = md5($this->_fixedIdent().$this->field_in);
25        $this->field_sec = md5($this->_fixedIdent().$this->field_sec);
26        $this->field_hp  = md5($this->_fixedIdent().$this->field_hp);
27    }
28
29    /**
30     * Check if the CAPTCHA should be used. Always check this before using the methods below.
31     *
32     * @return bool true when the CAPTCHA should be used
33     */
34    public function isEnabled() {
35        if(!$this->getConf('forusers') && $_SERVER['REMOTE_USER']) return false;
36        return true;
37    }
38
39    /**
40     * Returns the HTML to display the CAPTCHA with the chosen method
41     */
42    public function getHTML() {
43        global $ID;
44
45        $rand = (float) (rand(0, 10000)) / 10000;
46        $this->storeCaptchaCookie($this->_fixedIdent(), $rand);
47
48        if($this->getConf('mode') == 'math') {
49            $code = $this->_generateMATH($this->_fixedIdent(), $rand);
50            $code = $code[0];
51            $text = $this->getLang('fillmath');
52        } elseif($this->getConf('mode') == 'question') {
53            $code = ''; // not used
54            $text = $this->getConf('question');
55        } else {
56            $code = $this->_generateCAPTCHA($this->_fixedIdent(), $rand);
57            $text = $this->getLang('fillcaptcha');
58        }
59        $secret = $this->encrypt($rand);
60
61        $txtlen = $this->getConf('lettercount');
62
63        $out = '';
64        $out .= '<div id="plugin__captcha_wrapper">';
65        $out .= '<input type="hidden" name="'.$this->field_sec.'" value="'.hsc($secret).'" />';
66        $out .= '<label for="plugin__captcha">'.$text.'</label> ';
67
68        switch($this->getConf('mode')) {
69            case 'math':
70            case 'text':
71                $out .= $this->_obfuscateText($code);
72                break;
73            case 'js':
74                $out .= '<span id="plugin__captcha_code">'.$this->_obfuscateText($code).'</span>';
75                break;
76            case 'image':
77                $out .= '<img src="'.DOKU_BASE.'lib/plugins/captcha/img.php?secret='.rawurlencode($secret).'&amp;id='.$ID.'" '.
78                    ' width="'.$this->getConf('width').'" height="'.$this->getConf('height').'" alt="" /> ';
79                break;
80            case 'audio':
81                $out .= '<img src="'.DOKU_BASE.'lib/plugins/captcha/img.php?secret='.rawurlencode($secret).'&amp;id='.$ID.'" '.
82                    ' width="'.$this->getConf('width').'" height="'.$this->getConf('height').'" alt="" /> ';
83                $out .= '<a href="'.DOKU_BASE.'lib/plugins/captcha/wav.php?secret='.rawurlencode($secret).'&amp;id='.$ID.'"'.
84                    ' class="JSnocheck" title="'.$this->getLang('soundlink').'">';
85                $out .= '<img src="'.DOKU_BASE.'lib/plugins/captcha/sound.png" width="16" height="16"'.
86                    ' alt="'.$this->getLang('soundlink').'" /></a>';
87                break;
88            case 'figlet':
89                require_once(dirname(__FILE__).'/figlet.php');
90                $figlet = new phpFiglet();
91                if($figlet->loadfont(dirname(__FILE__).'/figlet.flf')) {
92                    $out .= '<pre>';
93                    $out .= rtrim($figlet->fetch($code));
94                    $out .= '</pre>';
95                } else {
96                    msg('Failed to load figlet.flf font file. CAPTCHA broken', -1);
97                }
98                break;
99        }
100        $out .= ' <input type="text" size="'.$txtlen.'" name="'.$this->field_in.'" class="edit" /> ';
101
102        // add honeypot field
103        $out .= '<label class="no">'.$this->getLang('honeypot').'<input type="text" name="'.$this->field_hp.'" /></label>';
104        $out .= '</div>';
105        return $out;
106    }
107
108    /**
109     * Checks if the the CAPTCHA was solved correctly
110     *
111     * @param  bool $msg when true, an error will be signalled through the msg() method
112     * @return bool true when the answer was correct, otherwise false
113     */
114    public function check($msg = true) {
115        global $INPUT;
116
117        $field_sec = $INPUT->str($this->field_sec);
118        $field_in  = $INPUT->str($this->field_in);
119        $field_hp  = $INPUT->str($this->field_hp);
120
121        // reconstruct captcha from provided $field_sec
122        $rand = $this->decrypt($field_sec);
123
124        if($this->getConf('mode') == 'math') {
125            $code = $this->_generateMATH($this->_fixedIdent(), $rand);
126            $code = $code[1];
127        } elseif($this->getConf('mode') == 'question') {
128            $code = $this->getConf('answer');
129        } else {
130            $code = $this->_generateCAPTCHA($this->_fixedIdent(), $rand);
131        }
132
133        // compare values
134        if(!$field_sec ||
135            !$field_in ||
136            $rand === false ||
137            utf8_strtolower($field_in) != utf8_strtolower($code) ||
138            trim($field_hp) !== '' ||
139            !$this->retrieveCaptchaCookie($this->_fixedIdent(), $rand)
140        ) {
141            if($msg) msg($this->getLang('testfailed'), -1);
142            return false;
143        }
144        return true;
145    }
146
147    /**
148     * Get the path where a capture cookie would be stored
149     *
150     * We use a daily temp directory which is easy to clean up
151     *
152     * @param $fixed string the fixed part, any string
153     * @param $rand  float  some random number between 0 and 1
154     * @return string the path to the cookie file
155     */
156    protected function getCaptchaCookiePath($fixed, $rand) {
157        global $conf;
158        $path = $conf['tmpdir'] . '/captcha/' . date('Y-m-d') . '/' . md5($fixed . $rand) . '.cookie';
159        io_makeFileDir($path);
160        return $path;
161    }
162
163    /**
164     * Creates a one time captcha cookie
165     *
166     * This is used to prevent replay attacks. It is generated when the captcha form
167     * is shown and checked with the captcha check. Since we can not be sure about the
168     * session state (might be closed or open) we're not using it.
169     *
170     * We're not using the stored values for displaying the captcha image (or audio)
171     * but continue to use our encryption scheme. This way it's still possible to have
172     * multiple captcha checks going on in parallel (eg. with multiple browser tabs)
173     *
174     * @param $fixed string the fixed part, any string
175     * @param $rand  float  some random number between 0 and 1
176     */
177    protected function storeCaptchaCookie($fixed, $rand) {
178        $cache = $this->getCaptchaCookiePath($fixed, $rand);
179        touch($cache);
180    }
181
182    /**
183     * Checks if the captcha cookie exists and deletes it
184     *
185     * @param $fixed string the fixed part, any string
186     * @param $rand  float  some random number between 0 and 1
187     * @return bool true if the cookie existed
188     */
189    protected function retrieveCaptchaCookie($fixed, $rand) {
190        $cache = $this->getCaptchaCookiePath($fixed, $rand);
191        if(file_exists($cache)) {
192            unlink($cache);
193            return true;
194        }
195        return false;
196    }
197
198    /**
199     * Build a semi-secret fixed string identifying the current page and user
200     *
201     * This string is always the same for the current user when editing the same
202     * page revision, but only for one day. Editing a page before midnight and saving
203     * after midnight will result in a failed CAPTCHA once, but makes sure it can
204     * not be reused which is especially important for the registration form where the
205     * $ID usually won't change.
206     *
207     * @return string
208     */
209    public function _fixedIdent() {
210        global $ID;
211        $lm = @filemtime(wikiFN($ID));
212        $td = date('Y-m-d');
213        return auth_browseruid().
214        auth_cookiesalt().
215        $ID.$lm.$td;
216    }
217
218    /**
219     * Adds random space characters within the given text
220     *
221     * Keeps subsequent numbers without spaces (for math problem)
222     *
223     * @param $text
224     * @return string
225     */
226    protected function _obfuscateText($text) {
227        $new = '';
228
229        $spaces = array(
230            "\r",
231            "\n",
232            "\r\n",
233            ' ',
234            "\xC2\xA0", // \u00A0    NO-BREAK SPACE
235            "\xE2\x80\x80", // \u2000    EN QUAD
236            "\xE2\x80\x81", // \u2001    EM QUAD
237            "\xE2\x80\x82", // \u2002    EN SPACE
238            //         "\xE2\x80\x83", // \u2003    EM SPACE
239            "\xE2\x80\x84", // \u2004    THREE-PER-EM SPACE
240            "\xE2\x80\x85", // \u2005    FOUR-PER-EM SPACE
241            "\xE2\x80\x86", // \u2006    SIX-PER-EM SPACE
242            "\xE2\x80\x87", // \u2007    FIGURE SPACE
243            "\xE2\x80\x88", // \u2008    PUNCTUATION SPACE
244            "\xE2\x80\x89", // \u2009    THIN SPACE
245            "\xE2\x80\x8A", // \u200A    HAIR SPACE
246            "\xE2\x80\xAF", // \u202F    NARROW NO-BREAK SPACE
247            "\xE2\x81\x9F", // \u205F    MEDIUM MATHEMATICAL SPACE
248
249            "\xE1\xA0\x8E\r\n", // \u180E    MONGOLIAN VOWEL SEPARATOR
250            "\xE2\x80\x8B\r\n", // \u200B    ZERO WIDTH SPACE
251            "\xEF\xBB\xBF\r\n", // \uFEFF    ZERO WIDTH NO-BREAK SPACE
252        );
253
254        $len = strlen($text);
255        for($i = 0; $i < $len - 1; $i++) {
256            $new .= $text{$i};
257
258            if(!is_numeric($text{$i + 1})) {
259                $new .= $spaces[array_rand($spaces)];
260            }
261        }
262        $new .= $text{$len - 1};
263        return $new;
264    }
265
266    /**
267     * Generate some numbers from a known string and random number
268     *
269     * @param $fixed string the fixed part, any string
270     * @param $rand  float  some random number between 0 and 1
271     * @return string
272     */
273    protected function _generateNumbers($fixed, $rand) {
274        $fixed   = hexdec(substr(md5($fixed), 5, 5)); // use part of the md5 to generate an int
275        $rand = $rand * 0xFFFFF; // bitmask from the random number
276        return md5($rand ^ $fixed); // combine both values
277    }
278
279    /**
280     * Generates a random char string
281     *
282     * @param $fixed string the fixed part, any string
283     * @param $rand  float  some random number between 0 and 1
284     * @return string
285     */
286    public function _generateCAPTCHA($fixed, $rand) {
287        $numbers = $this->_generateNumbers($fixed, $rand);
288
289        // now create the letters
290        $code = '';
291        $lettercount = $this->getConf('lettercount') * 2;
292        if($lettercount > strlen($numbers)) $lettercount = strlen($numbers);
293        for($i = 0; $i < $lettercount; $i += 2) {
294            $code .= chr(floor(hexdec($numbers[$i].$numbers[$i + 1]) / 10) + 65);
295        }
296
297        return $code;
298    }
299
300    /**
301     * Create a mathematical task and its result
302     *
303     * @param $fixed string the fixed part, any string
304     * @param $rand  float  some random number between 0 and 1
305     * @return array taks, result
306     */
307    protected function _generateMATH($fixed, $rand) {
308        $numbers = $this->_generateNumbers($fixed, $rand);
309
310        // first letter is the operator (+/-)
311        $op  = (hexdec($numbers[0]) > 8) ? -1 : 1;
312        $num = array(hexdec($numbers[1].$numbers[2]), hexdec($numbers[3]));
313
314        // we only want positive results
315        if(($op < 0) && ($num[0] < $num[1])) rsort($num);
316
317        // prepare result and task text
318        $res  = $num[0] + ($num[1] * $op);
319        $task = $num[0].(($op < 0) ? '-' : '+').$num[1].'=?';
320
321        return array($task, $res);
322    }
323
324    /**
325     * Create a CAPTCHA image
326     *
327     * @param string $text the letters to display
328     */
329    public function _imageCAPTCHA($text) {
330        $w = $this->getConf('width');
331        $h = $this->getConf('height');
332
333        $fonts = glob(dirname(__FILE__).'/fonts/*.ttf');
334
335        // create a white image
336        $img   = imagecreatetruecolor($w, $h);
337        $white = imagecolorallocate($img, 255, 255, 255);
338        imagefill($img, 0, 0, $white);
339
340        // add some lines as background noise
341        for($i = 0; $i < 30; $i++) {
342            $color = imagecolorallocate($img, rand(100, 250), rand(100, 250), rand(100, 250));
343            imageline($img, rand(0, $w), rand(0, $h), rand(0, $w), rand(0, $h), $color);
344        }
345
346        // draw the letters
347        $txtlen = strlen($text);
348        for($i = 0; $i < $txtlen; $i++) {
349            $font  = $fonts[array_rand($fonts)];
350            $color = imagecolorallocate($img, rand(0, 100), rand(0, 100), rand(0, 100));
351            $size  = rand(floor($h / 1.8), floor($h * 0.7));
352            $angle = rand(-35, 35);
353
354            $x       = ($w * 0.05) + $i * floor($w * 0.9 / $txtlen);
355            $cheight = $size + ($size * 0.5);
356            $y       = floor($h / 2 + $cheight / 3.8);
357
358            imagettftext($img, $size, $angle, $x, $y, $color, $font, $text[$i]);
359        }
360
361        header("Content-type: image/png");
362        imagepng($img);
363        imagedestroy($img);
364    }
365
366    /**
367     * Encrypt the given string with the cookie salt
368     *
369     * @param string $data
370     * @return string
371     */
372    public function encrypt($data) {
373        if(function_exists('auth_encrypt')) {
374            $data = auth_encrypt($data, auth_cookiesalt()); // since binky
375        } else {
376            $data = PMA_blowfish_encrypt($data, auth_cookiesalt()); // deprecated
377        }
378
379        return base64_encode($data);
380    }
381
382    /**
383     * Decrypt the given string with the cookie salt
384     *
385     * @param string $data
386     * @return string
387     */
388    public function decrypt($data) {
389        $data = base64_decode($data);
390        if($data === false || $data === '') return false;
391
392        if(function_exists('auth_decrypt')) {
393            return auth_decrypt($data, auth_cookiesalt()); // since binky
394        } else {
395            return PMA_blowfish_decrypt($data, auth_cookiesalt()); // deprecated
396        }
397    }
398}
399