forked from silverstripe/silverstripe-akismet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAkismetField.php
257 lines (229 loc) · 7.99 KB
/
AkismetField.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
<?php
namespace SilverStripe\Akismet;
use Exception;
use Psr\Log\LoggerInterface;
use SilverStripe\Akismet\Service\AkismetService;
use SilverStripe\Core\Config\Config;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\Forms\CheckboxField;
use SilverStripe\Forms\Validator;
use SilverStripe\ORM\ValidationResult;
use SilverStripe\Security\Permission;
use SilverStripe\ORM\DataObjectInterface;
use SilverStripe\Forms\FormField;
use SilverStripe\Security\Security;
/**
* Form field to handle akismet error display and handling
*
* @author Damian Mooyman
* @package akismet
*/
class AkismetField extends FormField
{
/**
* If the Akismet network response fails, it is neither true or false
* This is the value assigned on a 400
*
* @var boolean
*/
private static $is_spam_when_response_fails = false;
/**
* @var array
*/
private $fieldMapping = array();
/**
*
* @var boolean
*/
protected $isSpam = null;
/**
* Get the nested confirmation checkbox field
*
* @return CheckboxField
*/
protected function confirmationField()
{
// Check if confirmation is required
$requireConfirmation = Config::inst()->get(AkismetSpamProtector::class, 'require_confirmation');
if (empty($requireConfirmation)) {
return null;
}
// If confirmation is required then return a checkbox
return CheckboxField::create(
$this->getName(),
_t(
__CLASS__ . '.NOTIFICATION',
'I understand that, and give consent to, having this content submitted to '
. 'a third party for automated spam detection'
)
)
->setMessage($this->getMessage(), $this->getMessageType())
->setForm($this->getForm());
}
public function Field($properties = array())
{
$checkbox = $this->confirmationField();
if ($checkbox) {
return $checkbox->Field($properties);
}
}
public function FieldHolder($properties = array())
{
$checkbox = $this->confirmationField();
if ($checkbox) {
return $checkbox->FieldHolder($properties);
}
}
/**
* @return array
*/
public function getSpamMappedData()
{
if (empty($this->fieldMapping)) {
return null;
}
$result = array();
$data = $this->form->getData();
foreach ($this->fieldMapping as $fieldName => $mappedName) {
$result[$mappedName] = (isset($data[$fieldName])) ? $data[$fieldName] : null;
}
return $result;
}
/**
* This function first gets values from mapped fields and then checks these values against
* akismet and then notifies callback object with the spam checking result.
* @param Validator $validator
* @return boolean - True when akismet confirms that the submission is ham (not spam) or should be saved
* - False when akismet confirms that the submission is spam or permission was not given to
* check for spam
*/
public function validate($validator)
{
// Check that, if necessary, the user has given permission to check for spam
$requireConfirmation = Config::inst()->get(AkismetSpamProtector::class, 'require_confirmation');
if ($requireConfirmation && !$this->Value()) {
$validator->validationError(
$this->name,
_t(
__CLASS__ . '.NOTIFICATIONREQUIRED',
'You must give consent to submit this content to spam detection'
),
"error"
);
return false;
}
// Check result
$isSpam = $this->getIsSpam();
if (!$isSpam) {
return true;
}
// Save error message
$errorMessage = _t(
__CLASS__ . '.SPAM',
"Your submission has been rejected because it was treated as spam."
);
// If spam should be allowed, let it pass and save it for later
if (Config::inst()->get(AkismetSpamProtector::class, 'save_spam')) {
// In order to save spam but still display the spam message, we must mock a form message
// without failing the validation
$errors = array(array(
'fieldName' => $this->name,
'message' => $errorMessage,
'messageType' => 'error',
));
$formName = $this->getForm()->FormName();
$this->getForm()->sessionMessage($errorMessage, ValidationResult::TYPE_GOOD);
return true;
} else {
// Mark as spam
$validator->validationError($this->name, $errorMessage, "error");
return false;
}
}
/**
* Determine if this field is spam or not
*
* @return boolean
*/
public function getIsSpam()
{
// Prevent multiple API calls
if ($this->isSpam !== null) {
return $this->isSpam;
}
// Check bypass permission
$permission = Config::inst()->get(AkismetSpamProtector::class, 'bypass_permission');
if ($permission && Permission::check($permission)) {
return false;
}
// if the user has logged and there's no force check on member
$bypassMember = Config::inst()->get(AkismetSpamProtector::class, 'bypass_members');
if ($bypassMember && Security::getCurrentUser()) {
return false;
}
// Map input fields to spam fields
$mappedData = $this->getSpamMappedData();
$content = isset($mappedData['body']) ? $mappedData['body'] : null;
$author = isset($mappedData['authorName']) ? $mappedData['authorName'] : null;
$email = isset($mappedData['authorMail']) ? $mappedData['authorMail'] : null;
$url = isset($mappedData['authorUrl']) ? $mappedData['authorUrl'] : null;
// Check result
/** @var AkismetService $api */
$api = AkismetSpamProtector::singleton()->getService();
$this->isSpam = false;
try {
$this->isSpam = $api && $api->isSpam($content, $author, $email, $url);
} catch (Exception $e) {
//if the network response fails, it still needs to be true/false
$this->isSpam = (bool) $this->config()->is_spam_when_response_fails;
$errorMessage = sprintf(
"%s: %s",
$e->getMessage(),
_t(
__CLASS__ . '.SPAM',
"Your submission has been rejected because it was treated as spam."
)
);
Injector::inst()
->get(LoggerInterface::class)
->error($errorMessage);
}
return $this->isSpam;
}
/**
* Get the fields to map spam protection too
*
* @return array Associative array of Field Names, where the indexes of the array are
* the field names of the form and the values are the standard spamprotection
* fields used by the protector
*/
public function getFieldMapping()
{
return $this->fieldMapping;
}
/**
* Set the fields to map spam protection too
*
* @param array $fieldMapping array of Field Names, where the indexes of the array are
* the field names of the form and the values are the standard spamprotection
* fields used by the protector
* @return self
*/
public function setFieldMapping($fieldMapping)
{
$this->fieldMapping = $fieldMapping;
return $this;
}
/**
* Allow spam flag to be saved to the underlying data record
*
* @param DataObjectInterface $record
*/
public function saveInto(DataObjectInterface $record)
{
if (Config::inst()->get(AkismetSpamProtector::class, 'save_spam')) {
$dataValue = $this->getIsSpam() ? 1 : 0;
$record->setCastedField($this->name, $dataValue);
}
}
}