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 function Field() {
39 Requirements::javascript(JQUERY_PATH);
40 return $this->renderWith($this->fieldTemplates());
41 }
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
68
69 70 71 72 73 74
75 public function validate($validator) {
76 $capthaText = $this->getCode();
77 if ($this->securityTokenEnabled()) {
78 $capthaText .= Session::get('SecurityID');
79 }
80
81 if ((!$this->value['_e'] && $this->value['_f'] && $this->value['_f'] == $capthaText)) {
82 return true;
83 }
84
85 if ($validator) {
86 $validator->validationError(
87 $this->name,
88 _t('StealthCaptcha.WRONG', "The text you entered doesn't match the captcha. Please try again"),
89 "validation",
90 false
91 );
92 }
93 return false;
94 }
95
96 97 98 99 100 101 102 103
104 function getCode($clear=false) {
105 $capthaText = Session::get('StealthCaptcha.CText');
106 if (!$capthaText) {
107 $capthaText = self::generate_captcha();
108 Session::Set('StealthCaptcha.CText', $capthaText);
109 }
110 if ($clear) {
111 Session::clear('StealthCaptcha.CText');
112 }
113 return $capthaText;
114 }
115 }
[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.
-