xref: /plugin/captcha/helper.php (revision 9a516eda7386a5ec91d990aba0faaa514e5fa62d)
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        global $INPUT;
111
112        $code = '';
113        $field_sec = $INPUT->str($this->field_sec);
114        $field_in  = $INPUT->str($this->field_in);
115        $field_hp  = $INPUT->str($this->field_hp);
116
117        // reconstruct captcha from provided $field_sec
118        if($field_sec) {
119            $rand = $this->decrypt($field_sec);
120
121            if($this->getConf('mode') == 'math') {
122                $code = $this->_generateMATH($this->_fixedIdent(), $rand);
123                $code = $code[1];
124            } elseif($this->getConf('mode') == 'question') {
125                $code = $this->getConf('answer');
126            } else {
127                $code = $this->_generateCAPTCHA($this->_fixedIdent(), $rand);
128            }
129        }
130
131        // compare values
132        if(!$field_sec ||
133            !$field_in ||
134            utf8_strtolower($field_in) != utf8_strtolower($code) ||
135            trim($field_hp) !== ''
136        ) {
137            if($msg) msg($this->getLang('testfailed'), -1);
138            return false;
139        }
140        return true;
141    }
142
143    /**
144     * Build a semi-secret fixed string identifying the current page and user
145     *
146     * This string is always the same for the current user when editing the same
147     * page revision, but only for one day. Editing a page before midnight and saving
148     * after midnight will result in a failed CAPTCHA once, but makes sure it can
149     * not be reused which is especially important for the registration form where the
150     * $ID usually won't change.
151     *
152     * @return string
153     */
154    public function _fixedIdent() {
155        global $ID;
156        $lm = @filemtime(wikiFN($ID));
157        $td = date('Y-m-d');
158        return auth_browseruid().
159        auth_cookiesalt().
160        $ID.$lm.$td;
161    }
162
163    /**
164     * Adds random space characters within the given text
165     *
166     * Keeps subsequent numbers without spaces (for math problem)
167     *
168     * @param $text
169     * @return string
170     */
171    protected function _obfuscateText($text) {
172        $new = '';
173
174        $spaces = array(
175            "\r",
176            "\n",
177            "\r\n",
178            ' ',
179            "\xC2\xA0", // \u00A0    NO-BREAK SPACE
180            "\xE2\x80\x80", // \u2000    EN QUAD
181            "\xE2\x80\x81", // \u2001    EM QUAD
182            "\xE2\x80\x82", // \u2002    EN SPACE
183            //         "\xE2\x80\x83", // \u2003    EM SPACE
184            "\xE2\x80\x84", // \u2004    THREE-PER-EM SPACE
185            "\xE2\x80\x85", // \u2005    FOUR-PER-EM SPACE
186            "\xE2\x80\x86", // \u2006    SIX-PER-EM SPACE
187            "\xE2\x80\x87", // \u2007    FIGURE SPACE
188            "\xE2\x80\x88", // \u2008    PUNCTUATION SPACE
189            "\xE2\x80\x89", // \u2009    THIN SPACE
190            "\xE2\x80\x8A", // \u200A    HAIR SPACE
191            "\xE2\x80\xAF", // \u202F    NARROW NO-BREAK SPACE
192            "\xE2\x81\x9F", // \u205F    MEDIUM MATHEMATICAL SPACE
193
194            "\xE1\xA0\x8E\r\n", // \u180E    MONGOLIAN VOWEL SEPARATOR
195            "\xE2\x80\x8B\r\n", // \u200B    ZERO WIDTH SPACE
196            "\xEF\xBB\xBF\r\n", // \uFEFF    ZERO WIDTH NO-BREAK SPACE
197        );
198
199        $len = strlen($text);
200        for($i = 0; $i < $len - 1; $i++) {
201            $new .= $text{$i};
202
203            if(!is_numeric($text{$i + 1})) {
204                $new .= $spaces[array_rand($spaces)];
205            }
206        }
207        $new .= $text{$len - 1};
208        return $new;
209    }
210
211    /**
212     * Generate some numbers from a known string and random number
213     *
214     * @param $fixed string the fixed part, any string
215     * @param $rand  float  some random number between 0 and 1
216     * @return string
217     */
218    private function _generateNumbers($fixed, $rand) {
219        $fixed   = hexdec(substr(md5($fixed), 5, 5)); // use part of the md5 to generate an int
220        $rand = $rand * 0xFFFFF; // bitmask from the random number
221        return md5($rand ^ $fixed); // combine both values
222    }
223
224    /**
225     * Generates a random char string
226     *
227     * @param $fixed string the fixed part, any string
228     * @param $rand  float  some random number between 0 and 1
229     * @return string
230     */
231    public function _generateCAPTCHA($fixed, $rand) {
232        $numbers = $this->_generateNumbers($fixed, $rand);
233
234        // now create the letters
235        $code = '';
236        $lettercount = $this->getConf('lettercount') * 2;
237        if($lettercount > strlen($numbers)) $lettercount = strlen($numbers);
238        for($i = 0; $i < $lettercount; $i += 2) {
239            $code .= chr(floor(hexdec($numbers[$i].$numbers[$i + 1]) / 10) + 65);
240        }
241
242        return $code;
243    }
244
245    /**
246     * Create a mathematical task and its result
247     *
248     * @param $fixed string the fixed part, any string
249     * @param $rand  float  some random number between 0 and 1
250     * @return array taks, result
251     */
252    protected function _generateMATH($fixed, $rand) {
253        $numbers = $this->_generateNumbers($fixed, $rand);
254
255        // first letter is the operator (+/-)
256        $op  = (hexdec($numbers[0]) > 8) ? -1 : 1;
257        $num = array(hexdec($numbers[1].$numbers[2]), hexdec($numbers[3]));
258
259        // we only want positive results
260        if(($op < 0) && ($num[0] < $num[1])) rsort($num);
261
262        // prepare result and task text
263        $res  = $num[0] + ($num[1] * $op);
264        $task = $num[0].(($op < 0) ? '-' : '+').$num[1].'=?';
265
266        return array($task, $res);
267    }
268
269    /**
270     * Create a CAPTCHA image
271     *
272     * @param string $text the letters to display
273     */
274    public function _imageCAPTCHA($text) {
275        $w = $this->getConf('width');
276        $h = $this->getConf('height');
277
278        $fonts = glob(dirname(__FILE__).'/fonts/*.ttf');
279
280        // create a white image
281        $img   = imagecreatetruecolor($w, $h);
282        $white = imagecolorallocate($img, 255, 255, 255);
283        imagefill($img, 0, 0, $white);
284
285        // add some lines as background noise
286        for($i = 0; $i < 30; $i++) {
287            $color = imagecolorallocate($img, rand(100, 250), rand(100, 250), rand(100, 250));
288            imageline($img, rand(0, $w), rand(0, $h), rand(0, $w), rand(0, $h), $color);
289        }
290
291        // draw the letters
292        $txtlen = strlen($text);
293        for($i = 0; $i < $txtlen; $i++) {
294            $font  = $fonts[array_rand($fonts)];
295            $color = imagecolorallocate($img, rand(0, 100), rand(0, 100), rand(0, 100));
296            $size  = rand(floor($h / 1.8), floor($h * 0.7));
297            $angle = rand(-35, 35);
298
299            $x       = ($w * 0.05) + $i * floor($w * 0.9 / $txtlen);
300            $cheight = $size + ($size * 0.5);
301            $y       = floor($h / 2 + $cheight / 3.8);
302
303            imagettftext($img, $size, $angle, $x, $y, $color, $font, $text[$i]);
304        }
305
306        header("Content-type: image/png");
307        imagepng($img);
308        imagedestroy($img);
309    }
310
311    /**
312     * Encrypt the given string with the cookie salt
313     *
314     * @param string $data
315     * @return string
316     */
317    public function encrypt($data) {
318        if(function_exists('auth_encrypt')) {
319            $data = auth_encrypt($data, auth_cookiesalt()); // since binky
320        } else {
321            $data = PMA_blowfish_encrypt($data, auth_cookiesalt()); // deprecated
322        }
323
324        return base64_encode($data);
325    }
326
327    /**
328     * Decrypt the given string with the cookie salt
329     *
330     * @param string $data
331     * @return string
332     */
333    public function decrypt($data) {
334        $data = base64_decode($data);
335
336        if(function_exists('auth_decrypt')) {
337            return auth_decrypt($data, auth_cookiesalt()); // since binky
338        } else {
339            return PMA_blowfish_decrypt($data, auth_cookiesalt()); // deprecated
340        }
341    }
342}
343