xref: /plugin/captcha/helper.php (revision 28c1464375855d34176c4c82b0af17bf2676f457)
1<?php
2/**
3 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
4 * @author     Andreas Gohr <andi@splitbrain.org>
5 */
6// must be run within Dokuwiki
7if(!defined('DOKU_INC')) die();
8if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
9require_once(DOKU_INC.'inc/blowfish.php');
10
11class helper_plugin_captcha extends DokuWiki_Plugin {
12
13    protected $field_in = 'plugin__captcha';
14    protected $field_sec = 'plugin__captcha_secret';
15    protected $field_hp = 'plugin__captcha_honeypot';
16
17    /**
18     * Constructor. Initializes field names
19     */
20    public function __construct() {
21        $this->field_in  = md5($this->_fixedIdent().$this->field_in);
22        $this->field_sec = md5($this->_fixedIdent().$this->field_sec);
23        $this->field_hp  = md5($this->_fixedIdent().$this->field_hp);
24    }
25
26    /**
27     * Check if the CAPTCHA should be used. Always check this before using the methods below.
28     *
29     * @return bool true when the CAPTCHA should be used
30     */
31    public function isEnabled() {
32        if(!$this->getConf('forusers') && $_SERVER['REMOTE_USER']) return false;
33        return true;
34    }
35
36    /**
37     * Returns the HTML to display the CAPTCHA with the chosen method
38     */
39    public function getHTML() {
40        global $ID;
41
42        $rand = (float) (rand(0, 10000)) / 10000;
43        if($this->getConf('mode') == 'math') {
44            $code = $this->_generateMATH($this->_fixedIdent(), $rand);
45            $code = $code[0];
46            $text = $this->getLang('fillmath');
47        } else {
48            $code = $this->_generateCAPTCHA($this->_fixedIdent(), $rand);
49            $text = $this->getLang('fillcaptcha');
50        }
51        $secret = PMA_blowfish_encrypt($rand, auth_cookiesalt());
52
53        $txtlen = $this->getConf('lettercount');
54
55        $out = '';
56        $out .= '<div id="plugin__captcha_wrapper">';
57        $out .= '<input type="hidden" name="'.$this->field_sec.'" value="'.hsc($secret).'" />';
58        $out .= '<label for="plugin__captcha">'.$text.'</label> ';
59
60        switch($this->getConf('mode')) {
61            case 'text':
62            case 'math':
63                $out .= $code;
64                break;
65            case 'js':
66                $out .= '<span id="plugin__captcha_code">'.$code.'</span>';
67                break;
68            case 'image':
69                $out .= '<img src="'.DOKU_BASE.'lib/plugins/captcha/img.php?secret='.rawurlencode($secret).'&amp;id='.$ID.'" '.
70                    ' width="'.$this->getConf('width').'" height="'.$this->getConf('height').'" alt="" /> ';
71                break;
72            case 'audio':
73                $out .= '<img src="'.DOKU_BASE.'lib/plugins/captcha/img.php?secret='.rawurlencode($secret).'&amp;id='.$ID.'" '.
74                    ' width="'.$this->getConf('width').'" height="'.$this->getConf('height').'" alt="" /> ';
75                $out .= '<a href="'.DOKU_BASE.'lib/plugins/captcha/wav.php?secret='.rawurlencode($secret).'&amp;id='.$ID.'"'.
76                    ' class="JSnocheck" title="'.$this->getLang('soundlink').'">';
77                $out .= '<img src="'.DOKU_BASE.'lib/plugins/captcha/sound.png" width="16" height="16"'.
78                    ' alt="'.$this->getLang('soundlink').'" /></a>';
79                break;
80            case 'figlet':
81                require_once(dirname(__FILE__).'/figlet.php');
82                $figlet = new phpFiglet();
83                if($figlet->loadfont(dirname(__FILE__).'/figlet.flf')) {
84                    $out .= '<pre>';
85                    $out .= rtrim($figlet->fetch($code));
86                    $out .= '</pre>';
87                } else {
88                    msg('Failed to load figlet.flf font file. CAPTCHA broken', -1);
89                }
90                break;
91        }
92        $out .= ' <input type="text" size="'.$txtlen.'" maxlength="'.$txtlen.'" name="'.$this->field_in.'" class="edit" /> ';
93
94        // add honeypot field
95        $out .= '<label class="no">Please keep this field empty: <input type="text" name="'.$this->field_hp.'" /></label>';
96        $out .= '</div>';
97        return $out;
98    }
99
100    /**
101     * Checks if the the CAPTCHA was solved correctly
102     *
103     * @param  bool $msg when true, an error will be signalled through the msg() method
104     * @return bool true when the answer was correct, otherwise false
105     */
106    public function check($msg = true) {
107        // compare provided string with decrypted captcha
108        $rand = PMA_blowfish_decrypt($_REQUEST[$this->field_sec], auth_cookiesalt());
109
110        if($this->getConf('mode') == 'math') {
111            $code = $this->_generateMATH($this->_fixedIdent(), $rand);
112            $code = $code[1];
113        } else {
114            $code = $this->_generateCAPTCHA($this->_fixedIdent(), $rand);
115        }
116
117        if(!$_REQUEST[$this->field_sec] ||
118            !$_REQUEST[$this->field_in] ||
119            strtoupper($_REQUEST[$this->field_in]) != $code ||
120            trim($_REQUEST[$this->field_hp]) !== ''
121        ) {
122            if($msg) msg($this->getLang('testfailed'), -1);
123            return false;
124        }
125        return true;
126    }
127
128    /**
129     * Build a semi-secret fixed string identifying the current page and user
130     *
131     * This string is always the same for the current user when editing the same
132     * page revision, but only for one day. Editing a page before midnight and saving
133     * after midnight will result in a failed CAPTCHA once, but makes sure it can
134     * not be reused which is especially important for the registration form where the
135     * $ID usually won't change.
136     *
137     * @return string
138     */
139    public function _fixedIdent() {
140        global $ID;
141        $lm = @filemtime(wikiFN($ID));
142        $td = date('Y-m-d');
143        return auth_browseruid().
144            auth_cookiesalt().
145            $ID.$lm.$td;
146    }
147
148    /**
149     * Generates a random char string
150     *
151     * @param $fixed string the fixed part, any string
152     * @param $rand  float  some random number between 0 and 1
153     * @return string
154     */
155    public function _generateCAPTCHA($fixed, $rand) {
156        $fixed   = hexdec(substr(md5($fixed), 5, 5)); // use part of the md5 to generate an int
157        $numbers = md5($rand * $fixed); // combine both values
158
159        // now create the letters
160        $code = '';
161        for($i = 0; $i < ($this->getConf('lettercount') * 2); $i += 2) {
162            $code .= chr(floor(hexdec($numbers[$i].$numbers[$i + 1]) / 10) + 65);
163        }
164
165        return $code;
166    }
167
168    /**
169     * Create a mathematical task and its result
170     *
171     * @param $fixed string the fixed part, any string
172     * @param $rand  float  some random number between 0 and 1
173     * @return array taks, result
174     */
175    protected function _generateMATH($fixed, $rand) {
176        $fixed   = hexdec(substr(md5($fixed), 5, 5)); // use part of the md5 to generate an int
177        $numbers = md5($rand * $fixed); // combine both values
178
179        // first letter is the operator (+/-)
180        $op  = (hexdec($numbers[0]) > 8) ? -1 : 1;
181        $num = array(hexdec($numbers[1].$numbers[2]), hexdec($numbers[3]));
182
183        // we only want positive results
184        if(($op < 0) && ($num[0] < $num[1])) rsort($num);
185
186        // prepare result and task text
187        $res  = $num[0] + ($num[1] * $op);
188        $task = $num[0].(($op < 0) ? '&nbsp;-&nbsp;' : '&nbsp;+&nbsp;').$num[1].'&nbsp;=&nbsp;?';
189
190        return array($task, $res);
191    }
192
193    /**
194     * Create a CAPTCHA image
195     *
196     * @param string $text the letters to display
197     */
198    public function _imageCAPTCHA($text) {
199        $w = $this->getConf('width');
200        $h = $this->getConf('height');
201
202        $fonts = glob(dirname(__FILE__).'/fonts/*.ttf');
203
204        // create a white image
205        $img = imagecreatetruecolor($w, $h);
206        $white = imagecolorallocate($img, 255, 255, 255);
207        imagefill($img, 0, 0, $white);
208
209        // add some lines as background noise
210        for($i = 0; $i < 30; $i++) {
211            $color = imagecolorallocate($img, rand(100, 250), rand(100, 250), rand(100, 250));
212            imageline($img, rand(0, $w), rand(0, $h), rand(0, $w), rand(0, $h), $color);
213        }
214
215        // draw the letters
216        $txtlen = strlen($text);
217        for($i = 0; $i < $txtlen; $i++) {
218            $font  = $fonts[array_rand($fonts)];
219            $color = imagecolorallocate($img, rand(0, 100), rand(0, 100), rand(0, 100));
220            $size  = rand(floor($h / 1.8), floor($h * 0.7));
221            $angle = rand(-35, 35);
222
223            $x       = ($w * 0.05) + $i * floor($w * 0.9 / $txtlen);
224            $cheight = $size + ($size * 0.5);
225            $y       = floor($h / 2 + $cheight / 3.8);
226
227            imagettftext($img, $size, $angle, $x, $y, $color, $font, $text[$i]);
228        }
229
230        header("Content-type: image/png");
231        imagepng($img);
232        imagedestroy($img);
233    }
234
235}
236