-
Notifications
You must be signed in to change notification settings - Fork 20
/
PostIndicator.php
89 lines (75 loc) · 2.07 KB
/
PostIndicator.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
<?php
namespace Gregwar\Formidable;
/**
* Manage the form posting, this managed the posted token which is used to indicate
* if the specific form has been posted.
*
* If the sessions are active, a CSRF token will be used.
*
* Else, a token depending on form name and installation directory will be used.
*
* @author Grégoire Passault <g.passault@gmail.com>
*/
class PostIndicator
{
public static $fieldName = 'posted_token';
protected $name;
/**
* CSRF token
*/
protected $token = null;
public function __construct($name = '')
{
$this->name = $name;
}
/**
* Get the token value
*/
public function getToken()
{
$this->generateToken();
return $this->token;
}
/**
* Generate the token or get it from the session
*/
protected function generateToken()
{
if ($this->token === null) {
$secret = array(
'install' => __DIR__,
'name' => $this->name,
);
if (isset($_SESSION)) {
$key = sha1(__DIR__ . '/' . 'formidable_secret');
if (isset($_SESSION[$key])) {
$secret['csrf'] = $_SESSION[$key];
} else {
$csrf = sha1(uniqid(mt_rand(), true).'|'.gettimeofday(true));
$_SESSION[$key] = $csrf;
$secret['csrf'] = $csrf;
}
}
$this->token = sha1(serialize($secret));
}
}
/**
* HTML render
*/
public function getHtml()
{
return '<input type="hidden" name="'.self::$fieldName.'" value="'.$this->getToken().'" />'."\n";
}
/**
* Tell if the given form was posted
*/
public function posted($method = 'post')
{
$origin = ($method == 'post' ? $_POST : $_GET);
return (isset($origin) && isset($origin[self::$fieldName]) && $this->getToken() && $this->getToken() == $origin[self::$fieldName]);
}
public function __toString()
{
return $this->getHtml();
}
}