forked from ulsdevteam/pkp-formHoneypot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFormHoneypotPlugin.inc.php
379 lines (338 loc) · 11.6 KB
/
FormHoneypotPlugin.inc.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
<?php
/**
* @file plugins/generic/formHoneypot/FormHoneypotPlugin.inc.php
*
* Copyright (c) University of Pittsburgh
* Distributed under the GNU GPL v2 or later. For full terms see the LICENSE file.
*
* @class FormHoneypotPlugin
* @ingroup plugins_generic_formHoneypot
*
* @brief Form Honeypot plugin class
*/
import('lib.pkp.classes.plugins.GenericPlugin');
class FormHoneypotPlugin extends GenericPlugin {
/**
* @var $settingNames array()
* This array represents the fields on the settings form
*/
public $settingNames = array(
'formHoneypotMinimumTime' => 'int',
'formHoneypotMaximumTime' => 'int',
);
/**
* @var $formTimerSetting string
* This is the name of the setting used to track a users time during registration
*/
public $formTimerSetting = 'registrationTimer';
/** $var $elementNames array() */
var $elementNames = array(
's' => array('user', 'admin', 'form', 'tool', 'system'),
'v' => array('Confirm', 'Validate', 'Assign', 'Agree', 'Add'),
'p' => array('Terms', 'Options', 'Activity', 'Access', 'URL', 'Link')
);
/**
* @copydoc Plugin::isSitePlugin()
*/
function isSitePlugin() {
return true;
}
/**
* Called as a plugin is registered to the registry
* @param $category String Name of category plugin was registered to
* @return boolean True iff plugin initialized successfully; if false,
* the plugin will not be registered.
*/
function register($category, $path, $mainContextId = null) {
$success = parent::register($category, $path, $mainContextId);
if (!Config::getVar('general', 'installed') || defined('RUNNING_UPGRADE')) return true;
if ($success && $this->getEnabled($mainContextId)) {
// Attach to the page footer
HookRegistry::register('Templates::Common::Footer::PageFooter', array($this, 'insertTag'));
// Attach to the registration form validation
HookRegistry::register('registrationform::validate', array($this, 'validateHoneypot'));
// Attach to the registration form display
HookRegistry::register('registrationform::display', array($this, 'initializeTimer'));
// Add custom field if desired
HookRegistry::register('TemplateManager::display', array($this, 'handleTemplateDisplay'));
HookRegistry::register('registrationform::readuservars', array($this, 'handleUserVar'));
$element = $this->getSetting(CONTEXT_SITE, 'customElement');
if(!$element) {
// generate new form field
$this->updateSetting(CONTEXT_SITE, 'customElement', $this->generateElementName());
}
}
return $success;
}
/**
* Get the display name of this plugin.
* @return String
*/
function getDisplayName() {
return __('plugins.generic.formHoneypot.displayName');
}
/**
* Get a description of the plugin.
* @return String
*/
function getDescription() {
return __('plugins.generic.formHoneypot.description');
}
/**
* Display verbs for the management interface.
* @return array of verb => description pairs
*/
function getManagementVerbs() {
$verbs = array();
if ($this->getEnabled()) {
$verbs[] = array('settings', __('manager.plugins.settings'));
}
return parent::getManagementVerbs($verbs);
}
/**
* Insert Form Honeypot page tag to footer, if page is the user registration
* @param $hookName string Name of hook calling function
* @param $params array of smarty and output objects
* @return boolean
*/
function insertTag($hookName, $args) {
$templateMgr = TemplateManager::getManager();
$element = $this->getSetting(CONTEXT_SITE, 'customElement');
// only operate on user registration
if (method_exists('Application', 'get')) {
// OJS 3.2 and later
$request = Application::get()->getRequest();
$page = $request->getRequestedPage();
$op = $request->getRequestedOp();
} else {
// OJS 3.1.2 and earlier
$page = Request::getRequestedPage();
$op = Request::getRequestedOp();
}
if (isset($element) && $page === 'user' && substr($op, 0, 8) === 'register') {
$templateMgr->assign('element', $element);
// Testing version once for conditionals below
if (method_exists($this, 'getTemplateResource')) {
// OJS 3.1.2 and later
$output =& $args[2];
$output .= $templateMgr->fetch($this->getTemplateResource('pageTagScript.tpl'));
} else {
// OJS 3.1.1 and earlier 3.x releases
// true passed as the fourth argument causes the template manager to display the resource passed as argument 1.
$templateMgr->fetch($this->getTemplatePath() . 'pageTagScript.tpl', null, null, true);
}
}
return false;
}
/**
* Add honeypot validation to the user registration form
* @param $hookName string Name of hook calling function
* @param $params array of field, requirement, and message
* @return boolean
*/
function validateHoneypot($hookName, $params) {
$element = $this->getSetting(CONTEXT_SITE, 'customElement');
$minTime = $this->getSetting(CONTEXT_SITE, 'formHoneypotMinimumTime');
$maxTime = $this->getSetting(CONTEXT_SITE, 'formHoneypotMaximumTime');
$form = $params[0];
// If we have an element selected as a honeypot, check it
if (isset($element) && isset($form)) {
$value = $form->getData($element);
// Is it localized?
if (is_array($value)) {
$value = implode('', array_values($value));
}
// If not empty, flag an error
if (!empty($value)) {
$elementName = 'plugins.generic.formHoneypot.leaveBlank';
$message = __('plugins.generic.formHoneypot.doNotUseThisField', array('element' => __($elementName)));
$form->addError(
$element,
$message
);
}
}
if ($form && $form->isValid() && ($minTime > 0 || $maxTime > 0)) {
// Get the initial access to this form within this session
$sessionManager = SessionManager::getManager();
$session = $sessionManager->getUserSession();
$started = $session->getSessionVar($this->getName()."::".$this->formTimerSetting);
$current = time();
if (!$started || ($minTime > 0 && $current - $started < $minTime) || ($maxTime > 0 && $current - $started > $maxTime)) {
$form->addError(
'username',
__('plugins.generic.formHoneypot.invalidSessionTime')
);
} else {
$started = $session->unsetSessionVar($this->getName()."::".$this->formTimerSetting);
}
}
return false;
}
/**
* Start monitoring for timing for form completion
* @param $hookName string Name of hook calling function
* @return boolean
*/
function initializeTimer($hookName) {
/*
* remember when this form was initialized for the user
* we'll store it as a user setting on form execution
*/
$sessionManager =& SessionManager::getManager();
$session =& $sessionManager->getUserSession();
$started = $session->getSessionVar($this->getName()."::".$this->formTimerSetting);
if (!$started) {
$session->setSessionVar($this->getName()."::".$this->formTimerSetting, time());
}
return false;
}
/**
* @copydoc Plugin::manage()
*/
function manage($args, $request) {
switch ($request->getUserVar('verb')) {
case 'settings':
AppLocale::requireComponents(LOCALE_COMPONENT_APP_COMMON, LOCALE_COMPONENT_PKP_MANAGER, LOCALE_COMPONENT_PKP_USER);
$templateMgr = TemplateManager::getManager($request);
$templateMgr->register_function('plugin_url', array($this, 'smartyPluginUrl'));
$this->import('FormHoneypotSettingsForm');
$form = new FormHoneypotSettingsForm($this, CONTEXT_SITE);
// This assigns select options
if ($request->getUserVar('save')) {
$form->readInputData();
if ($form->validate()) {
$form->execute();
return new JSONMessage(true);
}
} else {
$form->initData();
}
return new JSONMessage(true, $form->fetch($request));
default:
// Unknown management verb
assert(false);
return false;
}
}
/**
* Fetch the form.
* @copydoc Form::fetch()
*/
function fetch($request) {
$templateMgr = TemplateManager::getManager($request);
$templateMgr->assign('pluginName', $this->_plugin->getName());
return parent::fetch($request);
}
/**
* @copydoc Plugin::getActions()
*/
function getActions($request, $verb) {
$router = $request->getRouter();
import('lib.pkp.classes.linkAction.request.AjaxModal');
return array_merge(
$this->getEnabled()?array(
new LinkAction(
'settings',
new AjaxModal(
$router->url($request, null, null, 'manage', null, array('verb' => 'settings', 'plugin' => $this->getName(), 'category' => 'generic')),
$this->getDisplayName()
),
__('manager.plugins.settings'),
null
),
):array(),
parent::getActions($request, $verb)
);
}
/**
* @copydoc PKPPlugin::getTemplatePath
*/
function getTemplatePath($inCore = false) {
if(method_exists($this, 'getTemplateResource')) {
// OJS 3.1.2 and later
return parent::getTemplatePath($inCore);
} else {
// OJS 3.1.1 and earlier 3.x releases
return parent::getTemplatePath($inCore) . 'templates' . DIRECTORY_SEPARATOR;
}
}
/**
* Hook callback: register output filter to add a new registration field
* @see TemplateManager::display()
*/
function handleTemplateDisplay($hookName, $args) {
$templateMgr = $args[0];
$template = $args[1];
switch ($template) {
case 'frontend/pages/userRegister.tpl':
$customElement = $this->getSetting(CONTEXT_SITE, 'customElement');
if (!empty($customElement)) {
if (method_exists($templateMgr, 'registerFilter')) {
// OJS 3.1.2 and later (Smarty 3)
$templateMgr->registerFilter("output", array($this, 'addCustomElement'));
} else {
// OJS 3.1.1 and earlier (Smarty 2)
$templateMgr->register_outputfilter(array($this, 'addCustomElement'));
}
}
break;
}
return false;
}
/**
* Hook callback: assign user variable within Registration form
* @see Form::readUserVars()
*/
function handleUserVar($hookName, $args) {
$form = $args[0];
$element = $this->getSetting(CONTEXT_SITE, 'customElement');
$args[1][] = $element;
return false;
}
/**
* Output filter to create a new element in a registration form
* @param $output string
* @param $templateMgr TemplateManager
* @return $string
*/
function addCustomElement($output, $templateMgr) {
/*
* Testing if we have a form#register here? A way of confirming the template. (yes, a regular expression is not the ideal way to do this,
* but with only one attribute, a regular expression should work okay here)
*/
if (preg_match('/<form[^>]+id="register"[^>]+>/', $output, $matches, PREG_OFFSET_CAPTURE) === 1) {
$matches = array();
if (preg_match_all('/(\s*<div[^>]+class="fields"[^>]*>\s*)/', $output, $matches, PREG_OFFSET_CAPTURE/*, $formStart*/)) {
$placement = rand(0, count($matches[0])-1);
$templateMgr = TemplateManager::getManager();
$element = $this->getSetting(CONTEXT_SITE, 'customElement');
$templateMgr->assign('element', $element);
$offset = $matches[0][$placement][1] + trim(mb_strlen($matches[0][$placement][0]));
$newOutput = substr($output, 0, $offset);
if (method_exists($this, 'getTemplateResource')) {
// OJS 3.1.2 and later
$newOutput .= $templateMgr->fetch($this->getTemplateResource('pageTagForm.tpl'));
} else {
// OJS 3.1.1 and earlier
$newOutput .= $templateMgr->fetch($this->getTemplatePath() . 'pageTagForm.tpl');
}
$newOutput .= substr($output, $offset);
$output = $newOutput;
}
}
return $output;
}
/**
* Output filter to create a new element in a registration form
* @param $output string
* @param $templateMgr TemplateManager
* @return $string
*/
function generateElementName () {
return $this->elementNames['s'][rand(0, count($this->elementNames['s'])-1)] .
$this->elementNames['v'][rand(0, count($this->elementNames['v'])-1)] .
$this->elementNames['p'][rand(0, count($this->elementNames['p'])-1)];
}
}
?>