1 <?php
2 3 4 5 6 7 8 9 10
11 class StealthFieldCaptcha extends SpamProtectorField {
12
13 14 15 16 17
18 static function generate_captcha() {
19 $length = 16;
20 $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ0123456789';
21 $numChars = strlen($chars);
22 $string = '';
23 for ($i = 0; $i < $length; $i++) {
24 $string .= substr($chars, rand(1, $numChars) - 1, 1);
25 }
26 return $string;
27 }
28
29 public function __construct($name = "StealthChkField", $title = '', $value = null, $form = null, $rightTitle = null) {
30 parent::__construct($name, '', '', $form, '');
31 }
32
33 34 35 36 37
38 public function Field() {
39 Requirements::javascript(JQUERY_PATH);
40 Requirements::javascript('stealth_captcha/javascript/script.js');
41 $capthaText = $this->getCode();
42
43 $emptyField = $this->createTag('input', array(
44 'type' => 'text',
45 'class' => 'text TextField',
46 'name' => $this->Name().'[_e]',
47 'style' => 'display: none',
48 'data-ctext' => $capthaText,
49 'value' => '',
50 ));
51
52 $filledField = $this->createTag('input', array(
53 'type' => 'hidden',
54 'class' => 'hidden stealth_filled',
55 'name' => $this->Name().'[_f]',
56 'data-ctext' => $capthaText,
57 'value' => '',
58 ));
59
60 return $emptyField . $filledField;
61 }
62
63 64 65 66 67 68
69 public function validate($validator) {
70 $capthaText = $this->getCode();
71 if ($this->securityTokenEnabled()) {
72 $capthaText .= Session::get('SecurityID');
73 }
74
75 if ((!$this->value['_e'] && $this->value['_f'] && $this->value['_f'] == $capthaText)) {
76 return true;
77 }
78
79 if ($validator) {
80 $validator->validationError(
81 $this->name,
82 _t('StealthCaptcha.WRONG', "The text you entered doesn't match the captcha. Please try again"),
83 "validation",
84 false
85 );
86 }
87 return false;
88 }
89
90 91 92 93 94 95 96 97
98 private function getCode($clear=false) {
99 $capthaText = Session::get('StealthCaptcha.CText');
100 if (!$capthaText) {
101 $capthaText = self::generate_captcha();
102 Session::Set('StealthCaptcha.CText', $capthaText);
103 }
104 if ($clear) {
105 Session::clear('StealthCaptcha.CText');
106 }
107 return $capthaText;
108 }
109 }
[Raise a SilverStripe Framework issue/bug](https://github.com/silverstripe/silverstripe-framework/issues/new)
- [Raise a SilverStripe CMS issue/bug](https://github.com/silverstripe/silverstripe-cms/issues/new)
- Please use the
Silverstripe Forums to ask development related questions.
-