xref: /plugin/captcha/helper.php (revision 478e363caef0fa7b3f049795cec41110614f36a4)
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     * Generates a random char string
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    public function _generateCAPTCHA($fixed, $rand) {
219        $fixed   = hexdec(substr(md5($fixed), 5, 5)); // use part of the md5 to generate an int
220        $numbers = md5($rand * $fixed); // combine both values
221
222        // now create the letters
223        $code = '';
224        for($i = 0; $i < ($this->getConf('lettercount') * 2); $i += 2) {
225            $code .= chr(floor(hexdec($numbers[$i].$numbers[$i + 1]) / 10) + 65);
226        }
227
228        return $code;
229    }
230
231    /**
232     * Create a mathematical task and its result
233     *
234     * @param $fixed string the fixed part, any string
235     * @param $rand  float  some random number between 0 and 1
236     * @return array taks, result
237     */
238    protected function _generateMATH($fixed, $rand) {
239        $fixed   = hexdec(substr(md5($fixed), 5, 5)); // use part of the md5 to generate an int
240        $numbers = md5($rand * $fixed); // combine both values
241
242        // first letter is the operator (+/-)
243        $op  = (hexdec($numbers[0]) > 8) ? -1 : 1;
244        $num = array(hexdec($numbers[1].$numbers[2]), hexdec($numbers[3]));
245
246        // we only want positive results
247        if(($op < 0) && ($num[0] < $num[1])) rsort($num);
248
249        // prepare result and task text
250        $res  = $num[0] + ($num[1] * $op);
251        $task = $num[0].(($op < 0) ? '-' : '+').$num[1].'=?';
252
253        return array($task, $res);
254    }
255
256    /**
257     * Create a CAPTCHA image
258     *
259     * @param string $text the letters to display
260     */
261    public function _imageCAPTCHA($text) {
262        $w = $this->getConf('width');
263        $h = $this->getConf('height');
264
265        $fonts = glob(dirname(__FILE__).'/fonts/*.ttf');
266
267        // create a white image
268        $img   = imagecreatetruecolor($w, $h);
269        $white = imagecolorallocate($img, 255, 255, 255);
270        imagefill($img, 0, 0, $white);
271
272        // add some lines as background noise
273        for($i = 0; $i < 30; $i++) {
274            $color = imagecolorallocate($img, rand(100, 250), rand(100, 250), rand(100, 250));
275            imageline($img, rand(0, $w), rand(0, $h), rand(0, $w), rand(0, $h), $color);
276        }
277
278        // draw the letters
279        $txtlen = strlen($text);
280        for($i = 0; $i < $txtlen; $i++) {
281            $font  = $fonts[array_rand($fonts)];
282            $color = imagecolorallocate($img, rand(0, 100), rand(0, 100), rand(0, 100));
283            $size  = rand(floor($h / 1.8), floor($h * 0.7));
284            $angle = rand(-35, 35);
285
286            $x       = ($w * 0.05) + $i * floor($w * 0.9 / $txtlen);
287            $cheight = $size + ($size * 0.5);
288            $y       = floor($h / 2 + $cheight / 3.8);
289
290            imagettftext($img, $size, $angle, $x, $y, $color, $font, $text[$i]);
291        }
292
293        header("Content-type: image/png");
294        imagepng($img);
295        imagedestroy($img);
296    }
297
298    /**
299     * Encrypt the given string with the cookie salt
300     *
301     * @param string $data
302     * @return string
303     */
304    public function encrypt($data) {
305        if(function_exists('auth_encrypt')) {
306            $data = auth_encrypt($data, auth_cookiesalt()); // since binky
307        } else {
308            $data = PMA_blowfish_encrypt($data, auth_cookiesalt()); // deprecated
309        }
310
311        return base64_encode($data);
312    }
313
314    /**
315     * Decrypt the given string with the cookie salt
316     *
317     * @param string $data
318     * @return string
319     */
320    public function decrypt($data) {
321        $data = base64_decode($data);
322
323        if(function_exists('auth_decrypt')) {
324            return auth_decrypt($data, auth_cookiesalt()); // since binky
325        } else {
326            return PMA_blowfish_decrypt($data, auth_cookiesalt()); // deprecated
327        }
328    }
329}
330