xref: /plugin/captcha/helper.php (revision 7218f96ceebeadf8d318824c7833a4bda6f325c9)
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
12class helper_plugin_captcha extends DokuWiki_Plugin {
13
14    protected $field_in = 'plugin__captcha';
15    protected $field_sec = 'plugin__captcha_secret';
16    protected $field_hp = 'plugin__captcha_honeypot';
17
18    /**
19     * Constructor. Initializes field names
20     */
21    public function __construct() {
22        $this->field_in  = md5($this->_fixedIdent().$this->field_in);
23        $this->field_sec = md5($this->_fixedIdent().$this->field_sec);
24        $this->field_hp  = md5($this->_fixedIdent().$this->field_hp);
25    }
26
27    /**
28     * Check if the CAPTCHA should be used. Always check this before using the methods below.
29     *
30     * @return bool true when the CAPTCHA should be used
31     */
32    public function isEnabled() {
33        if(!$this->getConf('forusers') && $_SERVER['REMOTE_USER']) return false;
34        return true;
35    }
36
37    /**
38     * Returns the HTML to display the CAPTCHA with the chosen method
39     */
40    public function getHTML() {
41        global $ID;
42
43        $rand = (float) (rand(0, 10000)) / 10000;
44        if($this->getConf('mode') == 'math') {
45            $code = $this->_generateMATH($this->_fixedIdent(), $rand);
46            $code = $code[0];
47            $text = $this->getLang('fillmath');
48        } elseif($this->getConf('mode') == 'question') {
49            $text = $this->getConf('question');
50        } else {
51            $code = $this->_generateCAPTCHA($this->_fixedIdent(), $rand);
52            $text = $this->getLang('fillcaptcha');
53        }
54        $secret = $this->encrypt($rand);
55
56        $txtlen = $this->getConf('lettercount');
57
58        $out = '';
59        $out .= '<div id="plugin__captcha_wrapper">';
60        $out .= '<input type="hidden" name="'.$this->field_sec.'" value="'.hsc($secret).'" />';
61        $out .= '<label for="plugin__captcha">'.$text.'</label> ';
62
63        switch($this->getConf('mode')) {
64            case 'math':
65            case 'text':
66                $out .= $this->_obfuscateText($code);
67                break;
68            case 'js':
69                $out .= '<span id="plugin__captcha_code">'.$this->_obfuscateText($code).'</span>';
70                break;
71            case 'image':
72                $out .= '<img src="'.DOKU_BASE.'lib/plugins/captcha/img.php?secret='.rawurlencode($secret).'&amp;id='.$ID.'" '.
73                    ' width="'.$this->getConf('width').'" height="'.$this->getConf('height').'" alt="" /> ';
74                break;
75            case 'audio':
76                $out .= '<img src="'.DOKU_BASE.'lib/plugins/captcha/img.php?secret='.rawurlencode($secret).'&amp;id='.$ID.'" '.
77                    ' width="'.$this->getConf('width').'" height="'.$this->getConf('height').'" alt="" /> ';
78                $out .= '<a href="'.DOKU_BASE.'lib/plugins/captcha/wav.php?secret='.rawurlencode($secret).'&amp;id='.$ID.'"'.
79                    ' class="JSnocheck" title="'.$this->getLang('soundlink').'">';
80                $out .= '<img src="'.DOKU_BASE.'lib/plugins/captcha/sound.png" width="16" height="16"'.
81                    ' alt="'.$this->getLang('soundlink').'" /></a>';
82                break;
83            case 'figlet':
84                require_once(dirname(__FILE__).'/figlet.php');
85                $figlet = new phpFiglet();
86                if($figlet->loadfont(dirname(__FILE__).'/figlet.flf')) {
87                    $out .= '<pre>';
88                    $out .= rtrim($figlet->fetch($code));
89                    $out .= '</pre>';
90                } else {
91                    msg('Failed to load figlet.flf font file. CAPTCHA broken', -1);
92                }
93                break;
94        }
95        $out .= ' <input type="text" size="'.$txtlen.'" name="'.$this->field_in.'" class="edit" /> ';
96
97        // add honeypot field
98        $out .= '<label class="no">'.$this->getLang('honeypot').'<input type="text" name="'.$this->field_hp.'" /></label>';
99        $out .= '</div>';
100        return $out;
101    }
102
103    /**
104     * Checks if the the CAPTCHA was solved correctly
105     *
106     * @param  bool $msg when true, an error will be signalled through the msg() method
107     * @return bool true when the answer was correct, otherwise false
108     */
109    public function check($msg = true) {
110        // compare provided string with decrypted captcha
111        $rand = $this->decrypt($_REQUEST[$this->field_sec]);
112
113        if($this->getConf('mode') == 'math') {
114            $code = $this->_generateMATH($this->_fixedIdent(), $rand);
115            $code = $code[1];
116        } elseif($this->getConf('mode') == 'question') {
117            $code = $this->getConf('answer');
118        } else {
119            $code = $this->_generateCAPTCHA($this->_fixedIdent(), $rand);
120        }
121
122        if(!$_REQUEST[$this->field_sec] ||
123            !$_REQUEST[$this->field_in] ||
124            utf8_strtolower($_REQUEST[$this->field_in]) != utf8_strtolower($code) ||
125            trim($_REQUEST[$this->field_hp]) !== ''
126        ) {
127            if($msg) msg($this->getLang('testfailed'), -1);
128            return false;
129        }
130        return true;
131    }
132
133    /**
134     * Build a semi-secret fixed string identifying the current page and user
135     *
136     * This string is always the same for the current user when editing the same
137     * page revision, but only for one day. Editing a page before midnight and saving
138     * after midnight will result in a failed CAPTCHA once, but makes sure it can
139     * not be reused which is especially important for the registration form where the
140     * $ID usually won't change.
141     *
142     * @return string
143     */
144    public function _fixedIdent() {
145        global $ID;
146        $lm = @filemtime(wikiFN($ID));
147        $td = date('Y-m-d');
148        return auth_browseruid().
149        auth_cookiesalt().
150        $ID.$lm.$td;
151    }
152
153    /**
154     * Adds random space characters within the given text
155     *
156     * Keeps subsequent numbers without spaces (for math problem)
157     *
158     * @param $text
159     * @return string
160     */
161    protected function _obfuscateText($text) {
162        $new = '';
163
164        $spaces = array(
165            "\r",
166            "\n",
167            "\r\n",
168            ' ',
169            "\xC2\xA0", // \u00A0    NO-BREAK SPACE
170            "\xE2\x80\x80", // \u2000    EN QUAD
171            "\xE2\x80\x81", // \u2001    EM QUAD
172            "\xE2\x80\x82", // \u2002    EN SPACE
173            //         "\xE2\x80\x83", // \u2003    EM SPACE
174            "\xE2\x80\x84", // \u2004    THREE-PER-EM SPACE
175            "\xE2\x80\x85", // \u2005    FOUR-PER-EM SPACE
176            "\xE2\x80\x86", // \u2006    SIX-PER-EM SPACE
177            "\xE2\x80\x87", // \u2007    FIGURE SPACE
178            "\xE2\x80\x88", // \u2008    PUNCTUATION SPACE
179            "\xE2\x80\x89", // \u2009    THIN SPACE
180            "\xE2\x80\x8A", // \u200A    HAIR SPACE
181            "\xE2\x80\xAF", // \u202F    NARROW NO-BREAK SPACE
182            "\xE2\x81\x9F", // \u205F    MEDIUM MATHEMATICAL SPACE
183
184            "\xE1\xA0\x8E\r\n", // \u180E    MONGOLIAN VOWEL SEPARATOR
185            "\xE2\x80\x8B\r\n", // \u200B    ZERO WIDTH SPACE
186            "\xEF\xBB\xBF\r\n", // \uFEFF    ZERO WIDTH NO-BREAK SPACE
187        );
188
189        $len = strlen($text);
190        for($i = 0; $i < $len - 1; $i++) {
191            $new .= $text{$i};
192
193            if(!is_numeric($text{$i + 1})) {
194                $new .= $spaces[array_rand($spaces)];
195            }
196        }
197        $new .= $text{$len - 1};
198        return $new;
199    }
200
201    /**
202     * Generates a random char string
203     *
204     * @param $fixed string the fixed part, any string
205     * @param $rand  float  some random number between 0 and 1
206     * @return string
207     */
208    public function _generateCAPTCHA($fixed, $rand) {
209        $fixed   = hexdec(substr(md5($fixed), 5, 5)); // use part of the md5 to generate an int
210        $numbers = md5($rand * $fixed); // combine both values
211
212        // now create the letters
213        $code = '';
214        for($i = 0; $i < ($this->getConf('lettercount') * 2); $i += 2) {
215            $code .= chr(floor(hexdec($numbers[$i].$numbers[$i + 1]) / 10) + 65);
216        }
217
218        return $code;
219    }
220
221    /**
222     * Create a mathematical task and its result
223     *
224     * @param $fixed string the fixed part, any string
225     * @param $rand  float  some random number between 0 and 1
226     * @return array taks, result
227     */
228    protected function _generateMATH($fixed, $rand) {
229        $fixed   = hexdec(substr(md5($fixed), 5, 5)); // use part of the md5 to generate an int
230        $numbers = md5($rand * $fixed); // combine both values
231
232        // first letter is the operator (+/-)
233        $op  = (hexdec($numbers[0]) > 8) ? -1 : 1;
234        $num = array(hexdec($numbers[1].$numbers[2]), hexdec($numbers[3]));
235
236        // we only want positive results
237        if(($op < 0) && ($num[0] < $num[1])) rsort($num);
238
239        // prepare result and task text
240        $res  = $num[0] + ($num[1] * $op);
241        $task = $num[0].(($op < 0) ? '-' : '+').$num[1].'=?';
242
243        return array($task, $res);
244    }
245
246    /**
247     * Create a CAPTCHA image
248     *
249     * @param string $text the letters to display
250     */
251    public function _imageCAPTCHA($text) {
252        $w = $this->getConf('width');
253        $h = $this->getConf('height');
254
255        $fonts = glob(dirname(__FILE__).'/fonts/*.ttf');
256
257        // create a white image
258        $img   = imagecreatetruecolor($w, $h);
259        $white = imagecolorallocate($img, 255, 255, 255);
260        imagefill($img, 0, 0, $white);
261
262        // add some lines as background noise
263        for($i = 0; $i < 30; $i++) {
264            $color = imagecolorallocate($img, rand(100, 250), rand(100, 250), rand(100, 250));
265            imageline($img, rand(0, $w), rand(0, $h), rand(0, $w), rand(0, $h), $color);
266        }
267
268        // draw the letters
269        $txtlen = strlen($text);
270        for($i = 0; $i < $txtlen; $i++) {
271            $font  = $fonts[array_rand($fonts)];
272            $color = imagecolorallocate($img, rand(0, 100), rand(0, 100), rand(0, 100));
273            $size  = rand(floor($h / 1.8), floor($h * 0.7));
274            $angle = rand(-35, 35);
275
276            $x       = ($w * 0.05) + $i * floor($w * 0.9 / $txtlen);
277            $cheight = $size + ($size * 0.5);
278            $y       = floor($h / 2 + $cheight / 3.8);
279
280            imagettftext($img, $size, $angle, $x, $y, $color, $font, $text[$i]);
281        }
282
283        header("Content-type: image/png");
284        imagepng($img);
285        imagedestroy($img);
286    }
287
288    /**
289     * Encrypt the given string with the cookie salt
290     *
291     * @param string $data
292     * @return string
293     */
294    public function encrypt($data) {
295        if(function_exists('auth_encrypt')) {
296            $data = auth_encrypt($data, auth_cookiesalt()); // since binky
297        } else {
298            $data = PMA_blowfish_encrypt($data, auth_cookiesalt()); // deprecated
299        }
300
301        return base64_encode($data);
302    }
303
304    /**
305     * Decrypt the given string with the cookie salt
306     *
307     * @param string $data
308     * @return string
309     */
310    public function decrypt($data) {
311        $data = base64_decode($data);
312
313        if(function_exists('auth_decrypt')) {
314            return auth_decrypt($data, auth_cookiesalt()); // since binky
315        } else {
316            return PMA_blowfish_decrypt($data, auth_cookiesalt()); // deprecated
317        }
318    }
319}
320