Initial commit

This commit is contained in:
Nero 2019-08-14 19:22:54 +02:00
commit 40a2da38a2
7 changed files with 120 additions and 0 deletions

6
CsrfException.php Normal file
View File

@ -0,0 +1,6 @@
<?php
namespace Post;
class CsrfException extends \Exception {
}

17
FileUpload.php Normal file
View File

@ -0,0 +1,17 @@
<?php
namespace Post;
class FileUpload extends FormField {
protected $file;
protected $error=UPLOAD_ERR_NO_FILE;
public function loadFromEnv($name) {
$this->error=$_FILES[$name]['error'];
$this->value=$_FILES[$name]['name'];
$this->file=$_FILES[$name]['tmp_name'];
}
public function validate() {
return ($this->error==0);
}
}

47
Form.php Normal file
View File

@ -0,0 +1,47 @@
<?php
namespace Post;
class Form {
public $fields;
public $action;
public function __construct($fields) {
$this->fields=$fields;
}
public function denyCsrf() {
$this->fields["_csrf"]=new HiddenFormField();
$this->fields["_csrf"]->setValue($this->getCsrfToken());
}
public function getEnctype() {
foreach ($this->fields as $name=>$field) {
if ($field instanceof FileUpload) {
return "multipart/form-data";
}
}
return "application/x-www-form-urlencoded";
}
public function reset() {
foreach ($this->fields as $name=>$field) {
$field->reset();
}
}
public function loadFromEnv() {
foreach ($this->fields as $name=>$field) {
$field->loadFromEnv($name);
}
if (isset($this->fields['_csrf']) && $this->fields['_csrf']->getValue() !== $this->getCsrfToken()) {
throw new CsrfException();
}
}
public static function getCsrfToken() {
if (!isset($_SESSION['csrf'])) {
$_SESSION['csrf']=bin2hex(openssl_random_pseudo_bytes(16));
}
return $_SESSION['csrf'];
}
}

32
FormField.php Normal file
View File

@ -0,0 +1,32 @@
<?php
namespace Post;
class FormField {
protected $value="";
public function __construct($vars = array()) {
foreach($vars as $k=>$v) {
$this->$k = $vars[$k];
}
}
public function getValue() {
return $this->value;
}
public function setValue($val) {
$this->value=$val;
}
public function validate() {
return true;
}
public function reset() {
$this->value="";
}
public function loadFromEnv($name) {
$this->value=$_POST[$name];
}
}

6
HiddenFormField.php Normal file
View File

@ -0,0 +1,6 @@
<?php
namespace Post;
class HiddenFormField extends FormField {
}

6
SelectField.php Normal file
View File

@ -0,0 +1,6 @@
<?php
namespace Post;
class SelectField extends FormField {
public $options;
}

6
UploadException.php Normal file
View File

@ -0,0 +1,6 @@
<?php
namespace Post;
class UploadException extends \Exception {
// Used like parent class
}