Merge remote-tracking branch 'origin/Dev'

This commit is contained in:
Hion-V 2021-03-01 12:21:28 +01:00
commit 12d084aa9e
109 changed files with 3985 additions and 1157 deletions

2
.gitattributes vendored
View File

@ -1,2 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
vendor/
.projectroot

1
.phpunit.result.cache Normal file
View File

@ -0,0 +1 @@
C:37:"PHPUnit\Runner\DefaultTestResultCache":508:{a:2:{s:7:"defects";a:4:{s:47:"TestUser::testCanBeCreatedFromValidEmailAddress";i:4;s:48:"TestEmail::testCanBeCreatedFromValidEmailAddress";i:4;s:53:"TestEmail::testCannotBeCreatedFromInvalidEmailAddress";i:4;s:32:"TestEmail::testCanBeUsedAsString";i:4;}s:5:"times";a:4:{s:48:"TestEmail::testCanBeCreatedFromValidEmailAddress";d:0.005;s:53:"TestEmail::testCannotBeCreatedFromInvalidEmailAddress";d:0.001;s:32:"TestEmail::testCanBeUsedAsString";d:0;s:47:"TestUser::testCanBeCreatedFromValidEmailAddress";d:0;}}}

24
.vscode/launch.json vendored
View File

@ -1,24 +0,0 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Listen for XDebug",
"type": "php",
"request": "launch",
"port": 9000
},
{
"name": "Launch currently open script",
"type": "php",
"request": "launch",
"program": "${file}",
"cwd": "${fileDirname}",
"port": 9000
}
],
"php.executablePath": "C:/xampp/php/php.exe",
"php.suggest.basic": "false"
}

10
composer.json Normal file
View File

@ -0,0 +1,10 @@
{
"autoload": {
"classmap": [
"dev_mvc/"
]
},
"require-dev": {
"phpunit/phpunit": "^8"
}
}

1535
composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,26 +0,0 @@
<?php
Class HUtils{
static function issetPost($arr_postvars){
for ($i=0; $i <sizeof($arr_postvars) ; $i++)
{
if(!isset($_POST[$arr_postvars[$i]])){
return false;
}
}
return true;
}
static function issetSession($arr_sessionvars)
{
for ($i=0; $i <sizeof($arr_sessionvars) ; $i++) {
if(!isset($_POST[$arr_sessionvars[$i]])){
return false;
}
}
return true;
}
static function sqlDateToPhpDate($date){
return new DateTime($date);
}
}
?>

View File

@ -1,17 +0,0 @@
<?php
class AssetHandler{
static function printAsset($image, $doSize=false, $size=128){
if($doSize){
echo '<img src="./img/'.$image.'" width='.$size.' height='.$size.' >';
}
else{
echo '<img src="./img/'.$image.'>';
}
}
}
?>

View File

@ -1,218 +0,0 @@
<?php
Class Database{
static function connectToDB(){
//Defineer vars
$sql_server = "localhost";
$sql_username = "root";
$sql_password = "kankerlow";
$sql_database = "webforum";
$dsn = "mysql:host=$sql_server;dbname=$sql_database";
//Maak verbinding
$con = new PDO($dsn, $sql_username, $sql_password);
return $con;
}
//Controleert of het email adres al in de database voorkomt. Returnt true indien wel.
static function checkUsedEmail($email){
//Verbind met de database
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM users where email = :email");
//Bind parameters
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
//Voer de query uit
$query->execute();
//Check de hoeveelheid rijen die de database returnt.
if($query->rowCount() == 0){
//Email adres is niet in gebruik, return false
return false;
}
else{
//Email is al in gebruik of komt meer dan een keer voor. Beide gevallen zijn een probleem dus return true.
return true;
}
}
//Controleert of de gebruikersnaam al in de database voorkomt. Returnt true indien wel.
static function checkUsedUsername($username){
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM users where username = :username");
//Bind parameters
$query->bindParam(':username', $username, PDO::PARAM_STR, 256);
//Voer de query uit
$query->execute();
//Check de hoeveelheid rijen die de database returnt.
if($query->rowCount() == 0){
//Username adres is niet in gebruik, return false
return false;
}
else{
//Username is al in gebruik of komt meer dan een keer voor. Beide gevallen zijn een probleem dus return true.
return true;
}
}
//Registreert een gebruiker. Neemt als invoer email, wachtwoord, gebruikersnaam.
static function registerUser($email, $password, $username){
$ip = $_SERVER['REMOTE_ADDR'];
//Initit db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("INSERT INTO users (username, email, password, reg_ip) VALUES (:username, :email, :password, :ip)");
//Bind parameters
$query->bindParam(':username', $username, PDO::PARAM_STR, 256);
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
$query->bindParam(':password', $password, PDO::PARAM_STR, 256);
$query->bindParam(':ip', $ip, PDO::PARAM_STR, 256);
//Voer query uit
$query->execute();
}
//Check of gegeven login info in de database voorkomt
static function isLoginValid($email, $password){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM users where email = :email AND password = :password");
//Bind params
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
$query->bindParam(':password', $password, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 1){
//login correct (komt voor in de db)
return true;
}
else{
//Incorrect
return false;
}
}
//Vraag gebruikers ID op doormiddel van email en pass
static function getUID($email, $password){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT id FROM users where email = :email AND password = :password");
//Bind params
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
$query->bindParam(':password', $password, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 1){
//login correct, return uid
$result = $query->fetch(PDO::FETCH_COLUMN);
return $result;
}
else{
//something went wrong, return -1
return -1;
}
}
static function getUsername($uid){
$con = Database::connectToDB();
$query = $con->prepare("SELECT username FROM users where id = :uid");
$query->bindParam(':uid', $uid, PDO::PARAM_STR, 256);
$query->execute();
if($query->rowCount() == 1){
//login correct, return uid
$result = $query->fetch(PDO::FETCH_COLUMN);
return $result;
}
else{
//something went wrong, return -1
return "dbfetcherror";
}
}
static function isSessionTokenInUse($token){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM usersessions where token = :token");
//Bind params
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 0){
return false;
}
else{
return true;
}
}
static function registerNewSession($uid, $token, $expires){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("INSERT INTO usersessions (uid, token, expires) VALUES (:uid, :token, :expires)");
//Bind params
$query->bindParam(':uid', $uid, PDO::PARAM_INT);
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
$query->bindParam(':expires', $expires, PDO::PARAM_STR);
//Voer query it
$query->execute();
}
static function isSessionValid($token, $uid){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM usersessions where token = :token AND uid = :uid AND expires > NOW()");
//Bind params
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
$query->bindParam(':uid', $uid, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 1){
return true;
}
else{
return false;
}
}
static function invalidateSession($token){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("DELETE FROM usersessions WHERE token = :token");
//Bind params
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
}
static function invalidateSessionByUID($uid){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("DELETE FROM usersessions WHERE uid = :uid");
//Bind params
$query->bindParam(':token', $uid, PDO::PARAM_INT);
//Voer query it
$query->execute();
}
static function deleteExpiredSessions(){
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("DELETE FROM usersessions WHERE expires < NOW()");
$query->execute();
}
static function getSessionExpiryDate($token){
$con = Database::connectToDB();
$query = $con->prepare("SELECT expires FROM usersessions where token = :token");
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
$query->execute();
if($query->rowCount() == 1){
//login correct, return uid
$result = $query->fetch(PDO::FETCH_COLUMN);
return $result;
}
else{
//something went wrong, return -1
return "2000-01-01 00:00:00";
}
}
static function createThread(){
}
}
?>

View File

@ -1,92 +0,0 @@
<?php
Class UserSession{
public $username = "undefined";
public $uid = -1;
public $token = "undefined";
public $expires;
public function UserSession($username, $uid, $token = "undefined"){
$this->username = $username;
$this->uid = $uid;
$this->token = $token;
$this->setExpiry();
//echo($username."<br>");
//echo($loginSessionToken);
$_SESSION['usersession'] = $this;
setcookie('usersession', $this->token);
setcookie('uid', $this->uid);
}
public function setSessionToken($token){
$this->token = $token;
}
public function getSessionToken(){
return $this->token;
}
public function getFormattedExpiry(){
return $this->expires->format('Y-m-d H:i:s');
}
public function setExpiry(){
$this->expires = new DateTime();
$this->expires->modify("+ 1 hour");
}
public static function generateToken(){
$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$token = "";
for ($i=0; $i < 32 ; $i++) {
$token .= $chars[rand(0, strlen($chars) - 1)];
}
return $token;
}
public static function isSessionValid(){
if(isset($_SESSION['usersession'])){
if(!UserSession::isSessionExpired($_SESSION['usersession'])){
//check if session also exists in database
return true;
}
}
else{
if(isset($_COOKIE['usersession'])){
$token = $_COOKIE['usersession'];
$uid = $_COOKIE['uid'];
if(Database::isSessionValid($token,$uid)){
$username = Database::getUsername($uid);
$session = new UserSession($username, $uid, $token);
$session->expires = new DateTime(Database::getSessionExpiryDate($token));
}
else{
return false;
}
if(!UserSession::isSessionExpired($session)){
return true;
}
}
return false;
}
}
public static function getSession()
{
return $_SESSION['usersession'];
}
public static function isSessionExpired($session){
//session is expired
if(new DateTime() > $session->expires){
return true;
}
//session is not expired
else{
return false;
}
}
public static function isUserSignedIn(){
if(UserSession::isSessionValid()){
if(!UserSession::isSessionExpired(UserSession::getSession())){
if(Database::isSessionValid(UserSession::getSession()->token, UserSession::getSession()->uid)){
return true;
}
}
else{
return false;
}
}
}
}
?>

View File

@ -1,46 +0,0 @@
<?php
$debuginfo = false;
include_once("./app/login/UserSession.php");
include_once("./app/db/Database.php");
include_once("./app/HUtils.php");
if(!UserSession::isSessionValid()){
if(HUtils::issetPost(['email','password'])){
if(Database::isLoginValid($_POST['email'], $_POST['password'])){
//obtain UID
$uid = Database::getUID($_POST['email'], $_POST['password']);
if($uid != -1){
//obtain username
$username = Database::getUsername($uid);
//gen unique session token
$token = UserSession::generateToken();
//regen if already in use
while(Database::isSessionTokenInUse($token)){
$token = UserSession::generateToken();
}
$a = new UserSession($username, $uid, $token);
if($debuginfo){
echo $a->getSessionToken();
echo "<br>";
echo $a->uid;
echo "<br>";
echo $a->username;
}
//clean up expired sessions from ANY users
Database::deleteExpiredSessions();
Database::registerNewSession($a->uid, $a->token, $a->getFormattedExpiry());
//logged in, time to continue with other stuff
}
else{
echo "uid returned -1 from db interface";
}
}
else{
echo("login invalid");
}
}
}
else{
//we're done, don't even need to log in, session already active
//echo($_SESSION['usersession']->uid);
}
?>

View File

@ -1,12 +0,0 @@
<?php
include_once("UserSession.php");
if(UserSession::isSessionValid()){
Database::invalidateSession(UserSession::getSession()->token);
session_destroy();
}
?>

View File

@ -1,3 +0,0 @@
<?php
session_destroy();
?>

View File

@ -1,7 +0,0 @@
<?php
include_once("./app/assets/AssetHandler.php");
AssetHandler::printAsset("logo.png", true, 128);
?>
<nav>
<a href="?p=login">log in</a> <a href="?p=register">register</a> <a href="?p=">home</a>
</nav>

View File

@ -1,6 +0,0 @@
<?php
include("./app/assets/logo.php");
?>
<nav>
<a href="?p=attempt_logout">log out</a> <a href="?p=">home</a> <a href="?p=destroy">simulate browser session expiry</a>
</nav>

View File

@ -1,3 +0,0 @@
<article>
<h1>Welkom op hForumPHP. Log in of registreer om iets te doen.</h1>
</article>

View File

@ -1,57 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>
<?=$sSiteTitle?>
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="css/main.css" />
</head>
<body>
<header>
<?php
if(UserSession::isUserSignedIn()){
include("./app/pagecontent/content_header_signedin.php");
}else{
include("./app/pagecontent/content_header.php");
}
?>
</header>
<main>
<?php
//Laad juiste pagina content
switch($p){
case '':
include("./app/pagecontent/content_index.php");
break;
case 'register':
include("./app/pagecontent/login/content_register.php");
break;
case 'login':
include("./app/pagecontent/login/content_login.php");
break;
case 'attempt_reg':
include("We signed you up (probably)");
break;
case 'attempt_login':
if(UserSession::isUserSignedIn()){
include("./app/pagecontent/login/content_login_succesful.php");
}else{
include("./app/pagecontent/login/content_login_unsuccesful.php");
}
break;
case 'attempt_logout':
break;
case 'destroy':
include("./app/pagecontent/login/content_destroy.php");
break;
default:
echo "404";
break;
}
?>
</main>
</body>
</html>

View File

@ -1,3 +0,0 @@
<article>
<h1>You're still signed in thanks to our cookies!</h1>
</article>

View File

@ -1,10 +0,0 @@
<article>
<form action="?p=attempt_login" method="post">
E-mail: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit">
</form>
</article>
<?php
?>

View File

@ -1,8 +0,0 @@
<article>
<h1>Login succesful :DDDDDDDD</h1>
</article>
<?php
//print_r($_COOKIE['usersession']);
?>

View File

@ -1,3 +0,0 @@
<article>
<h1>UNEXPECTED LOGIN ERROR. OUR CODEMONKEYS DID SOMETHING VERY WRONG :(</h1>
</article>

View File

@ -1,9 +0,0 @@
<article>
<form action="attempt_register.php" method="post">
Username: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
Password: <input type="password" name="pass"><br>
Verify Password: <input type="password" name="pass2"><br>
<input type="submit">
</form>
</article>

View File

@ -1,19 +0,0 @@
<?php
//Include classes
include_once("./app/db/Database.php");
include_once("./app/HUtils.php");
if(HUtils::issetPost(['email', 'pass', 'name'])){
if($_POST['pass'] == $_POST['pass2']){
//Check of email aanwezig is in de database
if(!Database::checkUsedEmail($_POST['email']) && !Database::checkUsedUsername($_POST['name'])){
Database::registerUser($_POST['email'], $_POST['pass'], $_POST['name']);
}
}
else{
echo("REGISTRATION FAILED: PASSWORD VERIFICATION MISSMATCH");
}
}
else{
echo "POST UNSUCCESFUL: POST DATA INCOMPLETE OR NOT FOUND";
}
?>

View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

View File

@ -1,32 +0,0 @@
<?php
//include class lib.
include_once("./app/db/Database.php");
include_once("./app/login/UserSession.php");
include_once("./app/HUtils.php");
session_start();
//initialiseer standaard variabelen
$p="";
//check of pagina gespecificeerd is in de
if(isset($_GET['p'])){
$p = $_GET['p'];
}
//Doe server-side operaties die afgerond moeten worden voordat de pagina is geladen.
switch($p){
case 'destroy':
include("./app/login/destroy.php");
break;
case 'attempt_login':
include("./app/login/attempt_login.php");
break;
case 'attempt_logout':
include("./app/login/attempt_logout.php");
break;
case 'attempt_reg':
include("./app/registration/attempt_register.php");
break;
default:
break;
}
//laad de pagina
include("./app/pagecontent/content_page.php");
?>

5
dev_mvc/.buildpath Normal file
View File

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<buildpath>
<buildpathentry kind="src" path=""/>
<buildpathentry kind="con" path="org.eclipse.php.core.LANGUAGE"/>
</buildpath>

View File

@ -0,0 +1 @@
C:30:"PHPUnit\Runner\TestResultCache":44:{a:2:{s:7:"defects";a:0:{}s:5:"times";a:0:{}}}

22
dev_mvc/.project Normal file
View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>dev</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.validation.validationbuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.dltk.core.scriptbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.php.core.PHPNature</nature>
</natures>
</projectDescription>

View File

@ -1,12 +0,0 @@
<?php
class AssetHandler{
static function printAsset($image, $doSize=false, $size=128){
if($doSize){
echo '<img src="./view/img/'.$image.'" width='.$size.' height='.$size.' >';
}
else{
echo '<img src="./view/img/'.$image.'>';
}
}
}
?>

View File

@ -1,218 +0,0 @@
<?php
Class Database{
static function connectToDB(){
//Defineer vars
$sql_server = "localhost";
$sql_username = "root";
$sql_password = "kankerlow";
$sql_database = "webforum";
$dsn = "mysql:host=$sql_server;dbname=$sql_database";
//Maak verbinding
$con = new PDO($dsn, $sql_username, $sql_password);
return $con;
}
//Controleert of het email adres al in de database voorkomt. Returnt true indien wel.
static function checkUsedEmail($email){
//Verbind met de database
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM users where email = :email");
//Bind parameters
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
//Voer de query uit
$query->execute();
//Check de hoeveelheid rijen die de database returnt.
if($query->rowCount() == 0){
//Email adres is niet in gebruik, return false
return false;
}
else{
//Email is al in gebruik of komt meer dan een keer voor. Beide gevallen zijn een probleem dus return true.
return true;
}
}
//Controleert of de gebruikersnaam al in de database voorkomt. Returnt true indien wel.
static function checkUsedUsername($username){
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM users where username = :username");
//Bind parameters
$query->bindParam(':username', $username, PDO::PARAM_STR, 256);
//Voer de query uit
$query->execute();
//Check de hoeveelheid rijen die de database returnt.
if($query->rowCount() == 0){
//Username adres is niet in gebruik, return false
return false;
}
else{
//Username is al in gebruik of komt meer dan een keer voor. Beide gevallen zijn een probleem dus return true.
return true;
}
}
//Registreert een gebruiker. Neemt als invoer email, wachtwoord, gebruikersnaam.
static function registerUser($email, $password, $username){
$ip = $_SERVER['REMOTE_ADDR'];
//Initit db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("INSERT INTO users (username, email, password, reg_ip) VALUES (:username, :email, :password, :ip)");
//Bind parameters
$query->bindParam(':username', $username, PDO::PARAM_STR, 256);
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
$query->bindParam(':password', $password, PDO::PARAM_STR, 256);
$query->bindParam(':ip', $ip, PDO::PARAM_STR, 256);
//Voer query uit
$query->execute();
}
//Check of gegeven login info in de database voorkomt
static function isLoginValid($email, $password){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM users where email = :email AND password = :password");
//Bind params
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
$query->bindParam(':password', $password, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 1){
//login correct (komt voor in de db)
return true;
}
else{
//Incorrect
return false;
}
}
//Vraag gebruikers ID op doormiddel van email en pass
static function getUID($email, $password){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT id FROM users where email = :email AND password = :password");
//Bind params
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
$query->bindParam(':password', $password, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 1){
//login correct, return uid
$result = $query->fetch(PDO::FETCH_COLUMN);
return $result;
}
else{
//something went wrong, return -1
return -1;
}
}
static function getUsername($uid){
$con = Database::connectToDB();
$query = $con->prepare("SELECT username FROM users where id = :uid");
$query->bindParam(':uid', $uid, PDO::PARAM_STR, 256);
$query->execute();
if($query->rowCount() == 1){
//login correct, return uid
$result = $query->fetch(PDO::FETCH_COLUMN);
return $result;
}
else{
//something went wrong, return -1
return "dbfetcherror";
}
}
static function isSessionTokenInUse($token){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM usersessions where token = :token");
//Bind params
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 0){
return false;
}
else{
return true;
}
}
static function registerNewSession($uid, $token, $expires){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("INSERT INTO usersessions (uid, token, expires) VALUES (:uid, :token, :expires)");
//Bind params
$query->bindParam(':uid', $uid, PDO::PARAM_INT);
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
$query->bindParam(':expires', $expires, PDO::PARAM_STR);
//Voer query it
$query->execute();
}
static function isSessionValid($token, $uid){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM usersessions where token = :token AND uid = :uid AND expires > NOW()");
//Bind params
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
$query->bindParam(':uid', $uid, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 1){
return true;
}
else{
return false;
}
}
static function invalidateSession($token){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("DELETE FROM usersessions WHERE token = :token");
//Bind params
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
}
static function invalidateSessionByUID($uid){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("DELETE FROM usersessions WHERE uid = :uid");
//Bind params
$query->bindParam(':token', $uid, PDO::PARAM_INT);
//Voer query it
$query->execute();
}
static function deleteExpiredSessions(){
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("DELETE FROM usersessions WHERE expires < NOW()");
$query->execute();
}
static function getSessionExpiryDate($token){
$con = Database::connectToDB();
$query = $con->prepare("SELECT expires FROM usersessions where token = :token");
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
$query->execute();
if($query->rowCount() == 1){
//login correct, return uid
$result = $query->fetch(PDO::FETCH_COLUMN);
return $result;
}
else{
//something went wrong, return -1
return "2000-01-01 00:00:00";
}
}
static function createThread(){
}
}
?>

View File

@ -1,4 +1,5 @@
<?php
namespace controller;
Class HUtils{
static function issetPost($arr_postvars){
for ($i=0; $i <sizeof($arr_postvars) ; $i++)
@ -19,18 +20,19 @@ Class HUtils{
return true;
}
static function sqlDateToPhpDate($date){
return new DateTime($date);
}
static function getPage(){
$p = "";
if(isset($_GET['p'])){
$p = $_GET['p'];
}
return $p;
}
static function getSiteTitle(){
return "hPHPForum";
}
static function generateRandomKey(){
$token = "";
$chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$verificationKey = "";
for ($i=0; $i < 32 ; $i++) {
$token .= $chars[rand(0, strlen($chars) - 1)];
}
return $token;
}
}
?>

View File

@ -0,0 +1,111 @@
<?php
namespace controller;
class MVCController{
private $model;
private $testaction;
private $viewmodel;
private $view;
private $viewOverridden = false;
private $timesOverridden = 0;
private static $mvcController;
public static $viewData = [];
function __construct(){
self::$mvcController = $this;
//prepare current view and view model
if(isset($_GET['p']) && $_GET['p'] != ''){
$this->view = ROOT_DIR."/view/webcontent/content_".$_GET['p'].".php";
$this->viewmodel = ROOT_DIR."/viewmodel/viewmodel_".$_GET['p'].".php";
}
else{
$this->view = ROOT_DIR."/view/webcontent/content_home.php";
$this->viewmodel = ROOT_DIR."/viewmodel/viewmodel_home.php";
}
//prepare current action model
if(isset($_POST['action'])){
$this->model = ROOT_DIR."/model/actions/model_".$_POST['action'].".php";
}
else if(isset($_GET['action'])){
$this->model = ROOT_DIR."/model/actions/model_".$_GET['action'].".php";
}
else{
$this->model = ROOT_DIR."/model/actions/model_empty.php";
}
if(isset($_POST['testaction'])){
$this->testaction = ROOT_DIR."/model/testactions/TA_".$_POST['testaction'].".php";
}
}
static function getMVCController():MVCController
{
return self::$mvcController;
}
function overrideView($view_target):void
{
$this->view = ROOT_DIR."/view/webcontent/content_".$view_target.".php";
$this->viewmodel = ROOT_DIR."/viewmodel/viewmodel_".$view_target.".php";
$this->viewOverridden = true;
}
function executeAction():void
{
//check if action model is valid
if(file_exists($this->model)){
//execute action model
include_once($this->model);
}
//model doesn't exist and will not be called
else{
//debug message
echo("caught call on non-existant model file.");
}
//TESTACTION LAYER
//check if testaction is valid
if(file_exists($this->testaction)){
//execute testaction
//require_once($this->testaction);
$testactionClassname = '\model\testactions\\'. "TA_".$_POST['testaction'];
$testactionInstance = new $testactionClassname();
}
}
function executeViewmodel():void
{
if(file_exists($this->viewmodel))
{
include_once($this->viewmodel);
}
}
function executeModel():void
{
$this->executeAction();
//check if the view was overridden by action.
if($this->viewOverridden){
//don't need to run the viewmodel twice if it was overridden by action
$this->viewOverridden = false;
}
//run viewmodel
$this->executeViewmodel();
//run viewmodel again if overridden by viewmodel
if($this->viewOverridden)
{
$this->executeViewmodel();
}
}
function loadView(){
if(file_exists($this->view)){
include_once($this->view);
}
else{
include_once(ROOT_DIR."/view/webcontent/content_404.php");
echo("view: ".$this->view." not found.");
}
}
}
?>

View File

@ -1,15 +1,16 @@
<?php
namespace controller;
use controller\db\Database;
use DateTime;
Class UserSession{
public $username = "undefined";
public $uid = -1;
public $token = "undefined";
public $expires;
public function UserSession($username, $uid, $token = "undefined"){
$this->username = $username;
public static $session;
public function __construct($uid, $token = "undefined"){
$this->uid = $uid;
$this->token = $token;
$this->setExpiry();
//echo($username."<br>");
//echo($loginSessionToken);
$_SESSION['usersession'] = $this;
setcookie('usersession', $this->token);
@ -39,7 +40,6 @@ Class UserSession{
public static function isSessionValid(){
if(isset($_SESSION['usersession'])){
if(!Database::isSessionValid($_SESSION['usersession']->token, $_SESSION['usersession']->uid)){
include_once("./model/model_attempt_logout.php");
return false;
}
if(!UserSession::isSessionExpired($_SESSION['usersession'])){
@ -52,8 +52,7 @@ Class UserSession{
$token = $_COOKIE['usersession'];
$uid = $_COOKIE['uid'];
if(Database::isSessionValid($token,$uid)){
$username = Database::getUsername($uid);
$session = new UserSession($username, $uid, $token);
$session = new UserSession($uid, $token);
$session->expires = new DateTime(Database::getSessionExpiryDate($token));
}
else{
@ -68,8 +67,10 @@ Class UserSession{
}
public static function getSession()
{
if(isset($_SESSION['usersession'])){
return $_SESSION['usersession'];
}
}
public static function isSessionExpired($session){
//session is expired
if(new DateTime() > $session->expires){
@ -81,16 +82,46 @@ Class UserSession{
}
}
public static function isUserSignedIn(){
/*
if(UserSession::isSessionValid()){
if(!UserSession::isSessionExpired(UserSession::getSession())){
if(Database::isSessionValid(UserSession::getSession()->token, UserSession::getSession()->uid)){
return true;
}
}
else{
return false;
}
}
else{
return false;
}
*/
//session exists, no need to do anything
if(isset($_SESSION['usersession'])){
return true;
}
else{
if(isset($_COOKIE['usersession'])){
//check if the session exists in the database
if(Database::isSessionTokenInUse($_COOKIE['usersession'])){
//check if database expiration datetime is still valid
$expirationDateTime = Database::getSessionExpiryDate($_COOKIE['usersession']);
if(new DateTime($expirationDateTime) >= new DateTime()){
//user is signed in. Restore session
$userSession = new UserSession($_COOKIE['uid'], $_COOKIE['usersession']);
return true;
}
else{
//remove session from the database
Database::invalidateSession($_COOKIE['usersession']);
}
}
}
}
//session either doesn't exist, doesn't exist in cookie, doesn't exist in database, or is expired in the database.
return false;
}
}
?>

View File

@ -0,0 +1,33 @@
<?php
namespace controller\db;
use model\forum\Board;
use PDO;
class DBBoard extends Database{
static function getBoards():array
{
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM board");
$query->execute();
$boardArray = [];
while($result = $query->fetch(PDO::FETCH_BOTH)){
$board = new Board($result['ID'], $result['name'], $result['description'], $result['permLevel']);
array_push($boardArray, $board);
}
return $boardArray;
}
static function registerBoard(Board $board)
{
$con = self::connectToDB();
$name = $board->getName();
$description = $board->getDescription();
$permLevel = $board->getPermLevel();
$query = $con->prepare("INSERT INTO board (name, description, permLevel) VALUES (:name, :description, :permLevel)");
$query->bindParam(":name", $name);
$query->bindParam(":description", $description);
$query->bindParam(":permLevel", $permLevel);
$query->execute();
}
}

View File

@ -0,0 +1,53 @@
<?php
namespace controller\db;
use model\forum\Reply;
use PDO;
class DBReply extends Database{
static function createReply($uid, $threadID, $content){
$con = self::connectToDB();
$query = $con->prepare("INSERT INTO reply (thread_ID, users_ID, content) VALUES (:tid, :uid, :content);");
$query->bindParam(":uid", $uid);
$query->bindParam(":tid", $threadID);
$query->bindParam(":content", $content);
echo "$uid, $threadID, $content";
$query->execute();
}
static function getAllReplies():array
{
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM reply");
$query->bindParam(":id", $id);
$query->execute();
$replyArray = [];
while ($result = $query->fetch(PDO::FETCH_BOTH)) {
$reply = new Reply($result['ID'], $result['thread_ID'], $result['users_ID'], $result['content'], $result['date_created']);
array_push($replyArray, $reply);
}
return $replyArray;
}
static function getReplyByID($id):array
{
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM reply WHERE id = :id");
$query->bindParam(":id", $id);
$query->execute();
return $query->fetch(PDO::FETCH_BOTH);
}
static function getRepliesByThreadID($tid):array
{
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM reply WHERE thread_ID = :tid");
$query->bindParam(":tid", $tid);
$query->execute();
return $query->fetchAll(PDO::FETCH_BOTH);
}
static function getLastReplyByThreadID():array
{
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM reply WHERE thread_ID = :tid ORDER BY date_created DESC LIMIT 1");
$query->bindParam(":tid", $tid);
$query->execute();
return $query->fetch(PDO::FETCH_BOTH);
}
}

View File

@ -0,0 +1,94 @@
<?php
namespace controller\db;
use PDO;
Class DBTables extends Database{
static function createAllTables(){
$con = self::connectToDB();
self::createUserTable($con);
self::createEmailActivationKeyTable($con);
self::createBoardTable($con);
self::createThreadTable($con);
self::createReplyTable($con);
}
static function createUserTable($con){
$table = 'users';
if(!self::checkTableExists($table, $con)){
$query = $con->query(
" CREATE TABLE `users` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(256) NOT NULL,
`email` varchar(256) NOT NULL,
`password` varchar(256) NOT NULL,
`reg_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`login_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`reg_ip` varchar(256) NOT NULL DEFAULT '127.0.0.1',
`permissions` int(11) NOT NULL DEFAULT '-1',
`active` tinyint(1) DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
}
}
static function createEmailActivationKeyTable($con){
$table = 'email_activation_keys';
if(!self::checkTableExists($table, $con)){
$query = $con->query(
" CREATE TABLE `email_activation_keys` (
`id` int(16) NOT NULL AUTO_INCREMENT,
`users_id` int(16) NOT NULL,
`activationkey` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
}
}
static function createBoardTable($con){
$table = 'board';
if(!self::checkTableExists($table, $con)){
$query = $con->query(
" CREATE TABLE `board` (
`ID` int(16) NOT NULL AUTO_INCREMENT,
`name` varchar(256) NOT NULL,
`description` text NOT NULL,
`permLevel` int(16) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
}
}
static function createThreadTable($con){
$table = 'thread';
if(!self::checkTableExists($table, $con)){
$query = $con->query(
" CREATE TABLE `thread` (
`ID` int(16) NOT NULL AUTO_INCREMENT,
`users_ID` int(16) NOT NULL,
`board_ID` int(16) NOT NULL,
`title` varchar(256) NOT NULL,
`text` text NOT NULL,
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
}
}
static function createReplyTable($con){
$table = 'reply';
if(!self::checkTableExists($table, $con)){
$query = $con->query(
" CREATE TABLE `reply` (
`ID` int(16) NOT NULL AUTO_INCREMENT,
`thread_ID` int(16) NOT NULL,
`users_ID` int(16) NOT NULL,
`content` text NOT NULL,
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
}
}
static function checkTableExists($table, $con){
$query = $con->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'");
//table doesn't exist
if($query->fetchColumn() != 1){
return false;
}else{
return true;
}
}
}

View File

@ -0,0 +1,56 @@
<?php
namespace controller\db;
use model\forum\Thread;
use PDO;
class DBThread extends Database {
static function getThreadByID($id){
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM thread WHERE ID = :id");
$query->bindParam(":id", $id);
$query->execute();
$result = $query->fetch(PDO::FETCH_BOTH);
return new Thread($result['ID'], $result['users_ID'], $result['board_ID'], $result['title'], $result['text'], $result['date_created']);
}
static function getAllThreads(){
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM thread");
$query->execute();
$threadArray = [];
while($result = $query->fetch(PDO::FETCH_BOTH)){
$thread = new Thread($result['ID'], $result['users_ID'], $result['board_ID'], $result['title'], $result['text'], $result['date_created']);
array_push($threadArray, $thread);
}
return $threadArray;
}
static function getThreadsByBoard($boardID){
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM thread WHERE board_ID = :boardID");
$query->bindParam(":boardID", $boardID);
$query->execute();
$threadArray = [];
while($result = $query->fetch(PDO::FETCH_BOTH)){
$thread = new Thread($result['ID'], $result['users_ID'], $result['board_ID'], $result['title'], $result['text'], $result['date_created']);
array_push($threadArray, $thread);
}
return $threadArray;
}
static function createThread($threadObject){
$con = self::connectToDB();
$query = $con->prepare( "INSERT INTO thread" .
"(users_ID, board_ID, title, text)" .
"VALUES (:uid, :bid, :title, :content);");
$uid = $threadObject->getUserID();
$bid = $threadObject->getBoardID();
$title = $threadObject->getTitle();
$content = $threadObject->getContent();
$query->bindParam(":uid", $uid);
$query->bindParam(":bid", $bid);
$query->bindParam(":title", $title);
$query->bindParam(":content", $content);
$query->execute();
}
}

View File

@ -0,0 +1,168 @@
<?php
namespace controller\db;
use model\forum\User;
use PDO;
class DBUser extends Database
{
static function getUserByUID($uid){
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM users WHERE ID = :uid");
$query->bindParam(":uid", $uid);
$query->execute();
$result = $query->fetch(PDO::FETCH_BOTH);
$user = new User($result['ID'], $result['username'], $result['email'], $result['password'], $result['reg_date'], $result['login_date'], $result['reg_ip'], $result['permissions'], $result['active']);
return $user;
}
/**
* @return array
*/
static function getAllUsers():array
{
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM users");
$query->bindParam(":uid", $uid);
$query->execute();
$query->rowCount();
$userArray = [];
while ($result = $query->fetch(PDO::FETCH_BOTH)) {
$user = new User($result['ID'], $result['username'], $result['email'], $result['password'], $result['reg_date'], $result['login_date'], $result['reg_ip'], $result['permissions'], $result['active']);
array_push($userArray, $user);
}
return $userArray;
}
static function getUserByEmail($email){
$con = self::connectToDB();
$query = $con->prepare("SELECT * FROM users WHERE email = :email");
$query->bindParam(":email", $email);
$query->execute();
$result = $query->fetch(PDO::FETCH_BOTH);
$user = new User($result['ID'], $result['username'], $result['email'], $result['password'], $result['reg_date'], $result['login_date'], $result['reg_ip'], $result['permissions'], $result['active']);
if($query->rowCount() == 1){
//Email adres is niet in gebruik, return false
return $user;
}
else if($query->rowCount() == 0){
trigger_error("Email $email not found in DB", E_USER_ERROR);
}
else{
//Email is al in gebruik of komt meer dan een keer voor. Beide gevallen zijn een probleem dus return true.
trigger_error("Multiple users for email $email returned by DB, value should be unique", E_USER_ERROR);
}
}
//Controleert of het email adres al in de database voorkomt. Returnt true indien wel.
static function checkUsedEmail($email){
//Verbind met de database
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM users where email = :email");
//Bind parameters
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
//Voer de query uit
$query->execute();
//Check de hoeveelheid rijen die de database returnt.
if($query->rowCount() == 0){
//Email adres is niet in gebruik, return false
return false;
}
else{
//Email is al in gebruik of komt meer dan een keer voor. Beide gevallen zijn een probleem dus return true.
return true;
}
}
//Controleert of de gebruikersnaam al in de database voorkomt. Returnt true indien wel.
static function checkUsedUsername($username){
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM users where username = :username");
//Bind parameters
$query->bindParam(':username', $username, PDO::PARAM_STR, 256);
//Voer de query uit
$query->execute();
//Check de hoeveelheid rijen die de database returnt.
if($query->rowCount() == 0){
//Username adres is niet in gebruik, return false
return false;
}
else{
//Username is al in gebruik of komt meer dan een keer voor. Beide gevallen zijn een probleem dus return true.
return true;
}
}
//Registreert een gebruiker. Neemt als invoer email, wachtwoord, gebruikersnaam. en email activation key. Nog niet volledig geimplementeerd
static function registerUser($email, $password, $username){
$ip = $_SERVER['REMOTE_ADDR'];
//Initit db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("INSERT INTO users (username, email, password, reg_ip) VALUES (:username, :email, :password, :ip)");
//Bind parameters
$query->bindParam(':username', $username, PDO::PARAM_STR, 256);
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
$query->bindParam(':password', $password, PDO::PARAM_STR, 256);
$query->bindParam(':ip', $ip, PDO::PARAM_STR, 256);
//Voer query uit
$query->execute();
}
//Check of gegeven login info in de database voorkomt
static function isLoginValid($email, $password){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM users where email = :email AND password = :password");
//Bind params
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
$query->bindParam(':password', $password, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 1){
//login correct (komt voor in de db)
return true;
}
else{
//Incorrect
return false;
}
}
//Vraag gebruikers ID op doormiddel van email en pass
static function getUID($email, $password){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT id FROM users where email = :email AND password = :password");
//Bind params
$query->bindParam(':email', $email, PDO::PARAM_STR, 256);
$query->bindParam(':password', $password, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 1){
//login correct, return uid
$result = $query->fetch(PDO::FETCH_COLUMN);
return $result;
}
else{
//something went wrong, return -1
return -1;
}
}
static function getUsername($uid){
$con = Database::connectToDB();
$query = $con->prepare("SELECT username FROM users where id = :uid");
$query->bindParam(':uid', $uid, PDO::PARAM_STR, 256);
$query->execute();
if($query->rowCount() == 1){
//login correct, return uid
$result = $query->fetch(PDO::FETCH_COLUMN);
return $result;
}
else{
//something went wrong, return -1
return "db_user_invalid";
}
}
}

View File

@ -0,0 +1,226 @@
<?php
namespace controller\db;
use controller\db\DBTables;
use PDO;
Class Database{
static function connectToDB(){
try{
//Defineer vars
if(getenv("SQL_CREDENTIALS") !== false){
$sql_server = getenv("SQL_SERVER");
$sql_username = getenv("SQL_USERNAME");
$sql_password = getenv("SQL_PASSWORD");
$sql_database = getenv("SQL_DATABASE");
}
else{
$sql_server = "localhost";
$sql_username = "root";
$sql_password = "kankerlow";
$sql_database = "webforum";
}
$dsn = "mysql:host=$sql_server;dbname=$sql_database";
//Maak verbinding
$con = new PDO($dsn, $sql_username, $sql_password);
return $con;
}
catch(PDOException $e){
echo("PDO Exception, can't connect to database.");
die($e);
}
}
static function connectToSQL(){
try{
//Defineer vars
if(getenv("SQL_CREDENTIALS") !== false){
$sql_server = getenv("SQL_SERVER");
$sql_username = getenv("SQL_USERNAME");
$sql_password = getenv("SQL_PASSWORD");
}
else{
$sql_server = "localhost";
$sql_username = "root";
$sql_password = "kankerlow";
}
$dsn = "mysql:host=$sql_server;";
//Maak verbinding
$con = new PDO($dsn, $sql_username, $sql_password);
return $con;
}
catch(PDOException $e){
echo("PDO Exception, can't connect to database.");
die($e);
}
}
static function createDBIfNotPresent(){
$con = self::connectToSQL();
$dbName = getenv("SQL_DATABASE");
$query = $con->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = $dbName");
$result = (bool) $query;
if($result == 1){
echo('db exists');
}
else{
$query = $con->query("CREATE DATABASE $dbName");
DBTables::createAllTables();
}
}
/***
* ______ __ __ _____ _ _____ _______ _______ __ _______ _____ ____ _ _
* | ____| \/ | /\ |_ _| | /\ / ____|__ __|_ _\ \ / /\|__ __|_ _/ __ \| \ | |
* | |__ | \ / | / \ | | | | / \ | | | | | | \ \ / / \ | | | || | | | \| |
* | __| | |\/| | / /\ \ | | | | / /\ \| | | | | | \ \/ / /\ \ | | | || | | | . ` |
* | |____| | | |/ ____ \ _| |_| |____ / ____ \ |____ | | _| |_ \ / ____ \| | _| || |__| | |\ |
* |______|_| |_/_/ \_\_____|______| /_/ \_\_____| |_| |_____| \/_/ \_\_| |_____\____/|_| \_|
*
*
***/
//Kijk of de user activation key al bestaat in de databse.
static function doesUserActivationKeyExist($activationKey){
$con = Database::connectToDB();
$query = $con->prepare("SELECT * FROM email_activation_keys WHERE activationkey = :activationKey");
$query->bindParam(':activationKey', $activationKey, PDO::PARAM_STR, 256);
$query->execute();
if($query->rowCount() == 0){
//bestaat nog niet
return false;
}
else{
//bestaat al
return true;
}
}
static function registerActivationKey($users_id, $activationKey){
$con = Database::connectToDB();
$query = $con->prepare("INSERT INTO email_activation_keys (users_id, activationkey) VALUES (:users_id, :activationkey)");
$query->bindParam(':users_id', $users_id);
$query->bindParam(':activationkey', $activationKey);
$query->execute();
}
//Activeer gebruiker en verwijder activation key uit de activation key tabel
static function activateUser($activationKey){
$con = Database::connectToDb();
$query = $con->prepare("SELECT users_id FROM email_activation_keys WHERE activationKey = :activationKey");
$query->bindParam('activationKey', $activationKey);
$query->execute();
$result = -1;
if($query->rowCount() == 1){
//login correct, return uid
$result = $query->fetch(PDO::FETCH_COLUMN);
}
else{
//activation key komt niet voor in de db, return -1
return -1;
}
$id = $result;
$query = null;
$query = $con->prepare("UPDATE users SET active = 1 WHERE id = :id and active = 0");
$query->bindParam(':id',$id,PDO::PARAM_INT);
$query->execute();
}
/***
* _____ ______ _____ _____ _____ ____ _ _ _______ ____ _ ________ _ _ _____
* / ____| ____|/ ____/ ____|_ _/ __ \| \ | | |__ __/ __ \| |/ / ____| \ | |/ ____|
* | (___ | |__ | (___| (___ | || | | | \| | | | | | | | ' /| |__ | \| | (___
* \___ \| __| \___ \\___ \ | || | | | . ` | | | | | | | < | __| | . ` |\___ \
* ____) | |____ ____) |___) |_| || |__| | |\ | | | | |__| | . \| |____| |\ |____) |
* |_____/|______|_____/_____/|_____\____/|_| \_| |_| \____/|_|\_\______|_| \_|_____/
*
***/
static function isSessionTokenInUse($token){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM usersessions where token = :token");
//Bind params
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 0){
return false;
}
else{
return true;
}
}
static function registerNewSession($uid, $token, $expires){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("INSERT INTO usersessions (uid, token, expires) VALUES (:uid, :token, :expires)");
//Bind params
$query->bindParam(':uid', $uid, PDO::PARAM_INT);
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
$query->bindParam(':expires', $expires, PDO::PARAM_STR);
//Voer query it
$query->execute();
}
static function isSessionValid($token, $uid){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("SELECT * FROM usersessions where token = :token AND uid = :uid AND expires > NOW()");
//Bind params
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
$query->bindParam(':uid', $uid, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
//Check hoeveelheid teruggestuurde rijen
if($query->rowCount() == 1){
return true;
}
else{
return false;
}
}
static function invalidateSession($token){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("DELETE FROM usersessions WHERE token = :token");
//Bind params
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
//Voer query it
$query->execute();
}
static function invalidateSessionByUID($uid){
//Init db connection
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("DELETE FROM usersessions WHERE uid = :uid");
//Bind params
$query->bindParam(':token', $uid, PDO::PARAM_INT);
//Voer query it
$query->execute();
}
static function deleteExpiredSessions(){
$con = Database::connectToDB();
//Bereid query voor
$query = $con->prepare("DELETE FROM usersessions WHERE expires < NOW()");
$query->execute();
}
static function getSessionExpiryDate($token){
$con = Database::connectToDB();
$query = $con->prepare("SELECT expires FROM usersessions where token = :token");
$query->bindParam(':token', $token, PDO::PARAM_STR, 256);
$query->execute();
if($query->rowCount() == 1){
//login correct, return uid
$result = $query->fetch(PDO::FETCH_COLUMN);
return $result;
}
else{
//something went wrong, return an invalid date.
return "2000-01-01 00:00:00";
}
}
}

View File

@ -1,27 +1,59 @@
<?php
/*Code door Andreas Schaafsma ITA4-1b
*
* Notities voor bij nakijken
* $_POST[] is gebruikt binnen de model_attempt_login.php en model_attempt_register.php bestanden
* Alle regeling van de database connectie zit in ./controller/Database.php doormiddel van static class members om alles makkelijk te groeperen
* Er is ook een rudimentair login token systeem om ervoor te zorgen dat gebruikers ingelogd blijven zelfs als de $_SESSION[] vervalt.
* Deze login status verdwijnt weer na ongeveer een uurtje
*
*/
//include class lib.
include_once("./controller/Database.php");
include_once("./controller/UserSession.php");
include_once("./controller/HUtils.php");
session_start();
//Store de geselecteerde pagina in variabele $page
$page=HUtils::getPage();
//Model side operaties die afgerond moeten worden voor de paginacontent in wordt geladen
$path = "./model/model_".$page.".php";
if($page != ""){
if(file_exists($path)){
include_once($path);
define('ROOT_DIR', __DIR__);
function autoload($className){
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if($lastNsPos = strrpos($className, '\\')){
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= $className . '.php';
//echo $fileName;
require ROOT_DIR . '/' . $fileName;
}
//laad de pagina view
include("./view/pagecontent/content_page.php");
spl_autoload_register('autoload');
use model\testactions\TestAction;
use controller\MVCController;
use controller\UserSession;
use controller\HUtils;
use controller\db\Database;
error_reporting(E_ALL);
ini_set('log_errors','1');
ini_set('display_errors','1');
session_start();
$redis = new Redis();
$redis->connect('sc-redis','6379');
$redis->auth("password");
$redis->set('DB_CREATED', false);
echo $redis->get('DB_CREATED');
if(!$redis->get('DB_CREATED') || $redis->get('DB_CREATED') == ''){
Database::createDBIfNotPresent();
$redis->set('DB_CREATED', true);
}
//date_default_timezone_set('Europe/Amsterdam');
$mvcController = new MVCController();
$mvcController->executeModel();
if(!isset($_POST['testaction'])){
include_once(ROOT_DIR."/view/content_pagetemplate.php");
}
//require_once('aaaadea');
//http_response_code(200);
TestAction::returnLogAsText();
?>

View File

@ -0,0 +1,15 @@
<?php
use controller\UserSession;
use controller\HUtils;
use controller\db\DBReply;
Use model\forum\Reply;
//dit bestand bestaat grotendeels uit dummy code.
//Ik heb onvoldoende tijd gehad tijdens de afgelopen paar weken en het was extreem druk in de klas tijdens de les.
$uid = $_SESSION['usersession']->uid;
if(HUtils::issetPost(['thread', 'content']));
{
$reply = new Reply(-1, $_POST['thread'], $uid, $_POST['content']);
print_r($reply);
DBReply::createReply($reply->getUserid(), $reply->getThreadID(), $reply->getContent());
}
?>

View File

@ -0,0 +1,14 @@
<?php
use controller\UserSession;
use controller\HUtils;
use controller\db\DBThread;
use model\forum\Thread;
//dit bestand bestaat grotendeels uit dummy code.
//Ik heb onvoldoende tijd gehad tijdens de afgelopen paar weken en het was extreem druk in de klas tijdens de les.
$uid = $_SESSION['usersession']->uid;
if(HUtils::issetPost(['title', 'content', 'board']));
{
$thread = new Thread(-1, $uid, $_POST['board'], $_POST['title'], $_POST['content']);
DBThread::createThread($thread);
}
?>

View File

@ -0,0 +1,39 @@
<?php
//Include classes
require_once(ROOT_DIR."/controller/db/Database.php");
require_once(ROOT_DIR."/controller/db/DBUser.php");
require_once(ROOT_DIR."/controller/HUtils.php");
use controller\db\Database;
use controller\db\DBUser;
use controller\HUtils;
if(HUtils::issetPost(['email', 'pass', 'pass2', 'name'])){
$email = $_POST['email'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];
$name = $_POST['name'];
if($pass == $pass2){
//Check of email aanwezig is in de database
if(!DBUser::checkUsedEmail($email) && !DBUser::checkUsedUsername($name)){
$verificationKey = HUtils::generateRandomKey();
while(DBUser::doesUserActivationKeyExist($verificationKey)){
$verificationKey = HUtils::generateRandomKey();
}
//TO DO: Create verification key
DBUser::registerUser($email, $pass, $name);
$user = DBUser::getUserByEmail($email);
DBUser::registerActivationKey($user->getId(),$verificationKey);
$message = 'Please follow the link to verify your account: http://localhost/webforum_redux/hforumphp/dev_mvc/index.php?p=verify&key='.$verificationKey;
$headers = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($email, "Account Verification", $message, $headers);
}
}
else{
echo("REGISTRATION FAILED: PASSWORD VERIFICATION MISSMATCH");
}
}
else{
echo "POST UNSUCCESFUL: POST DATA INCOMPLETE OR NOT FOUND";
}
?>

View File

@ -0,0 +1,3 @@
<?php
//Nothing to see here
?>

View File

@ -0,0 +1,62 @@
<?php
$debuginfo = false;
use controller\UserSession;
use controller\db\Database;
use controller\db\DBUser;
use controller\HUtils;
use controller\MVCController;
use model\forum\User;
$skipoverride = false;
if(!UserSession::isUserSignedIn()){
if(HUtils::issetPost(['email','password'])){
if(DBUser::isLoginValid($_POST['email'], $_POST['password'])){
//obtain UID
$uid = DBUser::getUID($_POST['email'], $_POST['password']);
if($uid != -1){
//check if user account has been activated
if(DBUser::getUserByUID($uid)->getActive()){
//obtain username
//$username = DBUser::getUsername($uid);
//gen unique session token
$token = UserSession::generateToken();
//regen if already in use
while(Database::isSessionTokenInUse($token)){
$token = UserSession::generateToken();
}
$a = new UserSession($uid, $token);
if($debuginfo){
echo $a->getSessionToken();
echo "<br>";
echo $a->uid;
echo "<br>";
echo $a->username;
}
//clean up expired sessions from ANY users
Database::deleteExpiredSessions();
Database::registerNewSession($a->uid, $a->token, $a->getFormattedExpiry());
//logged in, time to continue with other stuff
}
else{
MVCController::getMVCController()->overrideView("account_inactive");
$skipoverride = true;
echo('ree');
}
}
else{
echo "uid returned -1 from db interface";
}
}
else{
echo("login invalid");
}
}
}
else{
//we're done, don't even need to log in, session already active
}
if(!UserSession::isUserSignedIn() &&!$skipoverride){
MVCController::getMVCController()->overrideView("error_login");
}
?>

View File

@ -0,0 +1,8 @@
<?php
use controller\db\Database;
use controller\UserSession;
$_SESSION['usersession'] = null;
Database::invalidateSession($_COOKIE['usersession']);
session_destroy();
?>

View File

@ -0,0 +1,40 @@
<?php
namespace model\forum;
class Board {
public $id;
public $name;
public $description;
public $permLevel;
function __construct($id, $name, $description, $permLevel){
$this->id = $id;
$this->name = $name;
$this->description = $description;
$this->permLevel = $permLevel;
}
function setId($id){
$this->id = $id;
}
function setName($name){
$this->name = $name;
}
function setDescription($description){
$this->description = $description;
}
function setPermLevel($permLevel){
$this->permLevel = $permLevel;
}
function getId(){
return $this->id;
}
function getName(){
return $this->name;
}
function getDescription(){
return $this->description;
}
function getPermLevel(){
return $this->permLevel;
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace model\forum;
class Email{
private $email;
private $valid;
function __construct($email){
$sanitized_email = filter_var($email, FILTER_SANITIZE_EMAIL);
if(filter_var($sanitized_email, FILTER_VALIDATE_EMAIL)){
$this->email = $sanitized_email;
$this->valid = true;
}
else{
$this->email = 'invalid';
$this->valid = false;
}
}
public function getEmail(){
return $this->email;
}
public function getValid(){
return $this->valid;
}
public function __toString(): string
{
return $this->email;
}
}

View File

@ -0,0 +1,104 @@
<?php
namespace model\forum;
use DateTime;
class Reply {
public $id;
public $threadID;
public $userID;
public $content;
public $date;
public $owner;
function __construct($id, $threadID, $userID, $content, $date = null){
$this->id = $id;
$this->threadID = $threadID;
$this->userID = $userID;
$this->content = $content;
$dateTime = new DateTime($date);
$this->date = $dateTime;
}
/**
* @return mixed
*/
public function getOwner():User {
return $this->owner;
}
/**
* @param mixed $owner
*/
public function setOwner($owner) {
$this->owner = $owner;
}
/**
* @return mixed
*/
public function getId() {
return $this->id;
}
/**
* @return mixed
*/
public function getThreadID() {
return $this->threadID;
}
/**
* @return mixed
*/
public function getUserID() {
return $this->userID;
}
/**
* @return mixed
*/
public function getContent() {
return $this->content;
}
/**
* @return mixed
*/
public function getDate() {
return $this->date;
}
/**
* @param mixed $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* @param mixed $threadID
*/
public function setThreadID($threadID) {
$this->threadID = $threadID;
}
/**
* @param mixed $userID
*/
public function setUserID($userID) {
$this->userID = $userID;
}
/**
* @param mixed $content
*/
public function setContent($content) {
$this->content = $content;
}
/**
* @param mixed $date
*/
public function setDate($date) {
$this->date = $date;
}
}

View File

@ -0,0 +1,145 @@
<?php
namespace model\forum;
use DateTime;
class Thread {
public $id;
public $title;
public $boardID;
public $userID;
public $content;
public $date_created;
public $replies = [];
public $lastReplyDate;
public $owner;
function __construct($id, $userID, $boardID, $title, $content, $date_created = null) {
$this->id = $id;
$this->title = $title;
$this->boardID = $boardID;
$this->userID = $userID;
$this->content = $content;
$dateTime = new DateTime($date_created);
$this->date_created = $dateTime;
/*
if(isset($threadData)){
$this->id = $threadData['id'];
$this->title = $threadData['title'];
$this->boardID = $threadData['boardID'];
$this->userID = $threadData['userID'];
$this->content = $threadData['content'];
}
*/
}
/**
* @return multitype:
*/
public function getReplies() {
return $this->replies;
}
/**
* @return mixed
*/
public function getOwner():User {
return $this->owner;
}
/**
* @param multitype: $replies
*/
public function setReplies($replies) {
$this->replies = $replies;
}
/**
* @param mixed $owner
*/
public function setOwner($owner) {
$this->owner = $owner;
}
public function getId() {
return $this->id;
}
/**
* @return string $title
*/
public function getTitle():string {
return $this->title;
}
/**
* @return int $boardID
*/
public function getBoardID() {
return $this->boardID;
}
/**
* @return int $userID
*/
public function getUserID() {
return $this->userID;
}
/**
* @return string $content
*/
public function getContent():string {
return $this->content;
}
/**
* @param string $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* @param string $title
*/
public function setTitle($title) {
$this->title = $title;
}
/**
* @param string $boardID
*/
public function setBoardID($boardID) {
$this->boardID = $boardID;
}
/**
* @param string $userID
*/
public function setUserID($userID) {
$this->userID = $userID;
}
/**
* @param string $content
*/
public function setContent($content) {
$this->content = $content;
}
/**
* @return DateTime
*/
public function getDate_created() {
return $this->date_created;
}
/**
* @param DateTime $date_created
*/
public function setDate_created($date_created) {
$this->date_created = $date_created;
}
}

View File

@ -0,0 +1,153 @@
<?php
namespace model\forum;
class User {
public $id;
public $username;
public $email;
public $password;
public $reg_date;
public $login_date;
public $reg_ip;
public $permissions;
public $active;
function __construct($id, $username, $email, $password, $reg_date, $login_date, $reg_ip, $permissions, $active){
$this->id = $id;
$this->username = $username;
$this->email = $email;
$this->password = $password;
$this->reg_date = $reg_date;
$this->login_date = $login_date;
$this->reg_ip=$reg_ip;
$this->permissions=$permissions;
$this->active = $active;
}
/**
* @return mixed
*/
public function getId():int {
return $this->id;
}
/**
* @return mixed
*/
public function getUsername():string {
return $this->username;
}
/**
* @return mixed
*/
public function getEmail():string {
return $this->email;
}
/**
* @return mixed
*/
public function getPassword():string {
return $this->password;
}
/**
* @return mixed
*/
public function getReg_date() {
return $this->reg_date;
}
/**
* @return mixed
*/
public function getLogin_date() {
return $this->login_date;
}
/**
* @return mixed
*/
public function getReg_ip() {
return $this->reg_ip;
}
/**
* @return mixed
*/
public function getPermissions() {
return $this->permissions;
}
/**
* @param mixed
*/
public function getActive() {
return $this->active;
}
/**
* @param mixed $id
*/
public function setId($id) {
$this->id = $id;
}
/**
* @param mixed $username
*/
public function setUsername($username) {
$this->username = $username;
}
/**
* @param mixed $email
*/
public function setEmail($email) {
$this->email = $email;
}
/**
* @param mixed $password
*/
public function setPassword($password) {
$this->password = $password;
}
/**
* @param mixed $reg_date
*/
public function setReg_date($reg_date) {
$this->reg_date = $reg_date;
}
/**
* @param mixed $login_date
*/
public function setLogin_date($login_date) {
$this->login_date = $login_date;
}
/**
* @param mixed $reg_ip
*/
public function setReg_ip($reg_ip) {
$this->reg_ip = $reg_ip;
}
/**
* @param mixed $permissions
*/
public function setPermissions($permissions) {
$this->permissions = $permissions;
}
/**
* @param mixed $active
*/
public function setActive($active) {
$this->active = $active;
}
}

View File

@ -1,46 +0,0 @@
<?php
$debuginfo = false;
include_once("./controller/UserSession.php");
include_once("./controller/Database.php");
include_once("./controller/HUtils.php");
if(!UserSession::isSessionValid()){
if(HUtils::issetPost(['email','password'])){
if(Database::isLoginValid($_POST['email'], $_POST['password'])){
//obtain UID
$uid = Database::getUID($_POST['email'], $_POST['password']);
if($uid != -1){
//obtain username
$username = Database::getUsername($uid);
//gen unique session token
$token = UserSession::generateToken();
//regen if already in use
while(Database::isSessionTokenInUse($token)){
$token = UserSession::generateToken();
}
$a = new UserSession($username, $uid, $token);
if($debuginfo){
echo $a->getSessionToken();
echo "<br>";
echo $a->uid;
echo "<br>";
echo $a->username;
}
//clean up expired sessions from ANY users
Database::deleteExpiredSessions();
Database::registerNewSession($a->uid, $a->token, $a->getFormattedExpiry());
//logged in, time to continue with other stuff
}
else{
echo "uid returned -1 from db interface";
}
}
else{
echo("login invalid");
}
}
}
else{
//we're done, don't even need to log in, session already active
//echo($_SESSION['usersession']->uid);
}
?>

View File

@ -1,12 +0,0 @@
<?php
include_once("./controller/UserSession.php");
if(UserSession::isSessionValid()){
Database::invalidateSession(UserSession::getSession()->token);
session_destroy();
}
?>

View File

@ -1,19 +0,0 @@
<?php
//Include classes
include_once("./controller/Database.php");
include_once("./controller/HUtils.php");
if(HUtils::issetPost(['email', 'pass', 'name'])){
if($_POST['pass'] == $_POST['pass2']){
//Check of email aanwezig is in de database
if(!Database::checkUsedEmail($_POST['email']) && !Database::checkUsedUsername($_POST['name'])){
Database::registerUser($_POST['email'], $_POST['pass'], $_POST['name']);
}
}
else{
echo("REGISTRATION FAILED: PASSWORD VERIFICATION MISSMATCH");
}
}
else{
echo "POST UNSUCCESFUL: POST DATA INCOMPLETE OR NOT FOUND";
}
?>

View File

@ -1,3 +0,0 @@
<?php
session_destroy();
?>

View File

@ -0,0 +1,186 @@
<?php
namespace model\testactions;
use PDO;
use PDOException;
class TA_CreateDB extends TestAction{
function TA_CreateDB(){
parent::__construct();
}
function execute(){
try{
if(getenv("SQL_CREDENTIALS") !== false){
$sql_server = getenv("SQL_SERVER");
$sql_username = getenv("SQL_USERNAME");
$sql_password = getenv("SQL_PASSWORD");
$sql_database = getenv("SQL_DATABASE");
}
else{
$sql_server = "localhost";
$sql_username = "root";
$sql_password = "kankerlow";
$sql_database = "webforum";
}
$host = $sql_server;
$db = $sql_database;
$user = $sql_username;
$pass = $sql_password;
//connect to sql server
$con = new PDO( "mysql:host=$host;charset=utf8", $user, $pass );
//check if db exists
$query = $con->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$db'");
//db exists
if($query->fetchColumn() != 1){
$query = $con->query("CREATE DATABASE $db");
self::logMessage('db doesnt exist');
}
//db doesn't exist
else{
self::logMessage('db already exists, skipping');
}
//select db
$con->exec("USE $db");
//test if table exists
$table = 'users';
$query = $con->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'");
self::logMessage($query->fetchColumn());
//table doesn't exist
if($query->fetchColumn() != 4){
self::logMessage('table doesnt exist');
$query = $con->query(
" CREATE TABLE `users` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(256) NOT NULL,
`email` varchar(256) NOT NULL,
`password` varchar(256) NOT NULL,
`reg_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`login_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`reg_ip` varchar(256) NOT NULL DEFAULT '127.0.0.1',
`permissions` int(11) NOT NULL DEFAULT '-1',
`active` tinyint(1) DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
self::logMessage("created table $table");
}
//table exists
else{
self::logMessage("table $table already exists, skipping");
}
$table = 'usersessions';
$query = $con->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'");
if($query->fetchColumn() != 4){
self::logMessage('table doesnt exist');
$query = $con->query(
" CREATE TABLE `usersessions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(11) NOT NULL,
`token` varchar(256) NOT NULL,
`expires` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
self::logMessage("created table $table");
}
//table exists
else{
self::logMessage("table $table already exists, skipping");
}
$table = 'email_activation_keys';
$query = $con->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'");
if($query->fetchColumn() != 4){
self::logMessage('table doesnt exist');
$query = $con->query(
" CREATE TABLE `email_activation_keys` (
`id` int(16) NOT NULL AUTO_INCREMENT,
`users_id` int(16) NOT NULL,
`activationkey` varchar(256) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
self::logMessage("created table $table");
}
//table exists
else{
self::logMessage("table $table already exists, skipping");
}
$table = 'board';
$query = $con->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'");
if($query->fetchColumn() != 4){
self::logMessage('table doesnt exist');
$query = $con->query(
" CREATE TABLE `board` (
`ID` int(16) NOT NULL AUTO_INCREMENT,
`name` varchar(256) NOT NULL,
`description` text NOT NULL,
`permLevel` int(16) NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
self::logMessage("created table $table");
}
//table exists
else{
self::logMessage("table $table already exists, skipping");
}
$table = 'thread';
$query = $con->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'");
if($query->fetchColumn() != 4){
self::logMessage('table doesnt exist');
$query = $con->query(
" CREATE TABLE `thread` (
`ID` int(16) NOT NULL AUTO_INCREMENT,
`users_ID` int(16) NOT NULL,
`board_ID` int(16) NOT NULL,
`title` varchar(256) NOT NULL,
`text` text NOT NULL,
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
self::logMessage("created table $table");
}
//table exists
else{
self::logMessage("table $table already exists, skipping");
}
$table = 'reply';
$query = $con->query("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '$table'");
if($query->fetchColumn() != 4){
self::logMessage('table doesnt exist');
$query = $con->query(
" CREATE TABLE `reply` (
`ID` int(16) NOT NULL AUTO_INCREMENT,
`thread_ID` int(16) NOT NULL,
`users_ID` int(16) NOT NULL,
`content` text NOT NULL,
`date_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1");
self::logMessage("created table $table");
}
//table exists
else{
self::logMessage("table $table already exists, skipping");
}
}
catch(PDOException $e){
self::logMessage('PDO ERROR', "FAILURE");
die("pdo exception, cannot connect to sql:<br> $e");
}
}
}
?>

View File

@ -0,0 +1,66 @@
<?php
namespace model\testactions;
use controller\db\Database;
use controller\db\DBBoard;
use controller\db\DBReply;
use controller\db\DBThread;
use controller\db\DBUser;
use model\forum\Board;
use model\forum\Thread;
use PDO;
use PDOException;
class TA_PopulateDB extends TestAction{
function TA_PopulateDB(){
parent::__construct();
}
function registerUser($email, $password, $username){
DBUser::registerUser($email,$password,$username);
$user = DBUser::getUserByEmail($email);
Database::registerActivationKey($user->getId(), $username);
Database::activateUser($username);
}
function execute(){
try{
//connect to sql server
$con = Database::connectToDB();
self::logMessage('table doesnt exist', "OK");
$this->registerUser('andreas@andreas.nl','jenk', 'andreas');
$this->registerUser('bram@bram.nl','jenk', 'bram');
self::logMessage("created test users", "OK");
DBBoard::registerBoard(new Board(-1, 'General Discussion', 'Plek om algemene discussie te voeren.', 0));
DBBoard::registerBoard(new Board(-1, 'Off Topic', 'Voor alle irrelevante zooi.', 0));
self::logMessage("created test boards", "OK");
DBThread::createThread(new Thread(-1, 1, 1, 'Test Thread', 'Deze thread is een test.', '1337-04-20 13:37:00'));
DBThread::createThread(new Thread(-1, 1, 2, 'Frits', 'Frits niffo', '1337-04-20 13:37:00'));
self::logMessage("created test threads", "OK");
DBReply::createReply(1, 1, 'heehee eks dee');
DBReply::createReply(1, 1, 'sup');
DBReply::createReply(2, 2, 'fritselitsel');
DBReply::createReply(2, 1, 'heb je daar prebleem mee ofzo');
self::logMessage("created test replies", "OK");
}
catch(PDOException $e){
self::logMessage("created test replies", "FAILURE");
die("pdo exception, cannot connect to sql:<br> $e");
//test change 7
}
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace model\testactions;
use controller\db\DBReply;
use model\forum\Reply;
class TA_TestDBReply extends TestAction{
public function __construct()
{
parent::__construct();
}
public function execute()
{
$replies = DBReply::getAllReplies();
echo "<div id='response_json'>";
echo (json_encode($replies));
echo "</div>";
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace model\testactions;
use controller\db\DBThread;
use model\forum\Thread;
class TA_TestDBThread extends TestAction{
function __construct(){
parent::__construct();
}
function execute(){
$threads = DBThread::getAllThreads();
echo "<div id='response_json'>";
echo (json_encode($threads));
echo "</div>";
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace model\testactions;
use controller\db\DBUser;
use model\forum\User;
class TA_TestDBUser extends TestAction{
public function __construct()
{
parent::__construct();
}
public function execute()
{
$users = DBUser::getAllUsers();
echo "<div id='response_json'>";
echo (json_encode($users));
echo "</div>";
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace model\testactions;
use PDO;
use PDOException;
class TA_TestSQLConnection extends TestAction{
function __construct(){
parent::__construct();
}
function execute(){
echo $this->testSQLConnection();
}
function testSQLConnection(){
$connectionStatus = false;
try{
//Defineer vars
if(getenv("SQL_CREDENTIALS") !== false){
$sql_server = getenv("SQL_SERVER");
$sql_username = getenv("SQL_USERNAME");
$sql_password = getenv("SQL_PASSWORD");
}
else{
//test
$sql_server = "localhost";
$sql_username = "root";
$sql_password = "kankerlow";
}
$dsn = "mysql:host=$sql_server";
//Maak verbinding
$con = new PDO($dsn, $sql_username, $sql_password);
$connectionStatus = true;
}
catch(PDOException $e){
echo("PDO Exception, can't connect to database.");
die($e);
$connectionStatus = false;
}
return $connectionStatus;
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace model\testactions;
class TestAction{
function __construct(){
if(isset($_POST['auth'])){
if($_POST['auth'] == getenv('ADMIN_ACTION_KEY')){
$this->execute();
}else{
self::logMessage('you have no authorization to do that', 'FAILURE');
}
}else{
self::logMessage('you have no authorization to do that', 'FAILURE');
}
}
function execute(){
self::logMessage('Unoverridden execute called on TestAction: '.$this, 'FAILURE');
}
public static $log = [];
public static $status;
public static function logMessage($message, $status = "OK"){
$loginput = [];
$loginput['message'] = $message;
$loginput['status'] = $status;
array_push(self::$log, $loginput);
return;
}
public static function returnLogAsJson(){
echo(json_encode(self::$log));
return;
}
public static function returnLogAsText(){
for($i = 0; $i<sizeof(self::$log); $i++){
echo("[".self::$log[$i]['status']."] ".self::$log[$i]['message']."\n");
if(self::$log[$i]['status'] == 'FAILURE'){
echo('<div id="test_exitstatus">ACTION FAILED</div>');
return;
}
}
echo('<div id="test_exitstatus">ACTION SUCCESSFUL</div>');
}
}

View File

@ -0,0 +1,26 @@
<?php
require_once(ROOT_DIR."/controller/MVCController.php");
require_once("index.php");
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="./view/css/main.css">
</head>
<body>
<header class="row">
<?php
include_once(ROOT_DIR."/view/webcontent/content_header.php");
?>
</header>
<div class="main">
<?php
$mvcController->loadView();
?>
</div>
<footer>
</footer>
</body>
</html>

View File

@ -1,10 +1,123 @@
*{
font-family: Arial, Helvetica, sans-serif;
}
header{
background-color: bisque;
html, body{
width: 100%;
height: 100%;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
align-items: center;
background-color: #333333;
}
a{
body{
}
loginForm{
}
.logo{
height: 100px;
width: 100px;
box-sizing: border-box;
border-radius: 10px;
justify-self: left;
font-size: 50pt;
padding: 10pt;
color: white;
margin-right: 10px;
text-decoration: none;
/* Permalink - use to edit and share this gradient: https://colorzilla.com/gradient-editor/#1e5799+0,45427a+100 */
background: #1e5799; /* Old browsers */
background: -moz-linear-gradient(-45deg, #1e5799 0%, #45427a 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(-45deg, #1e5799 0%,#45427a 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(135deg, #1e5799 0%,#45427a 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#45427a',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently supported by Chrome and Opera */
box-shadow: 0px 0px 20px black;
}
.row{
display: flex;
flex-direction: row;
flex-basis: auto;
}
header{
margin-top: 10px;
}
nav{
border-radius: 10px;
display:flex;
flex-direction: flex-row;
flex-basis: auto;
flex-shrink: 0;
flex-grow: 0;
background-color: gray;
width: 80%;
height: 100px;
max-height: 100px;
align-items: center;
justify-items: center;
align-content: center;
justify-content: center;
align-self: center;
justify-self: center;
box-shadow: 0px 0px 20px black;
}
nav a{
padding-left: 10px;
padding-right: 10px;
text-decoration: none;
font-size: 20pt;
font-weight: bold;
color: white;
}
.main{
border-radius: 15px;
margin-top: 10px;
display: flex;
flex-direction: column;
flex-grow: 0;
flex-shrink: 1;
background-color: white;
padding: 15px;
margin-bottom: 20px;
box-shadow: 0px 0px 20px black;
}
input{
padding: 5px;
margin: 5px;
}
textarea{
padding: 5px;
margin: 5px;
resize: none;
width: 50vw;
height: 20vw;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
width: 80vw;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

View File

@ -1,3 +0,0 @@
<article>
<h1>This page does not exist!</h1>
</article>

View File

@ -1,7 +0,0 @@
<?php
if(UserSession::isUserSignedIn()){
include("./view/pagecontent/login/content_login_succesful.php");
}else{
include("./view/pagecontent/login/content_login_unsuccesful.php");
}
?>

View File

@ -1,3 +0,0 @@
<article>
<h1>You've been succesfully logged out</h1>
</article>

View File

@ -1,3 +0,0 @@
<article>
<h1>Successfully registered!</h1>
</article>

View File

@ -1,6 +0,0 @@
<?php
?>

View File

@ -1,3 +0,0 @@
<article>
<h1>You're still signed in thanks to our cookies!</h1>
</article>

View File

@ -1,7 +0,0 @@
<?php
if(UserSession::isUserSignedIn()){
include("./view/pagecontent/header/content_header_signedin.php");
}else{
include("./view/pagecontent/header/content_header_signedout.php");
}
?>

View File

@ -1,3 +0,0 @@
<article>
<h1>Welkom op hForumPHP. Log in of registreer om iets te doen.</h1>
</article>

View File

@ -1,10 +0,0 @@
<article>
<form action="?p=attempt_login" method="post">
E-mail: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
<input type="submit">
</form>
</article>
<?php
?>

View File

@ -1,36 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>
<?=HUtils::getSiteTitle();?>
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="./view/css/main.css" />
</head>
<body>
<header>
<?php
include_once("./view/pagecontent/content_header.php");
?>
</header>
<main>
<?php
//Store de geselecteerde pagina in variabele $page
$page=HUtils::getPage();
//Laad de juiste view
$path = "./view/pagecontent/content_".$page.".php";
if($page != ""){
if(file_exists($path)){
include_once($path);
}
else{
include_once("./view/pagecontent/content_404.php");
}
}
?>
</main>
</body>
</html>

View File

@ -1,11 +0,0 @@
<script type="text/javascript" src="./view/js/checkform.js"></script>
<article>
<form action="?p=attempt_register" method="post">
Username: <input type="text" name="name" id="name" onkeyup="checkInputs()"><br>
E-mail: <input type="text" name="email" id="email" onkeyup="checkInputs()"><br>
Password: <input type="password" name="pass" id="pass" onkeyup="checkInputs()"><br>
Verify Password: <input type="password" name="pass2" id="pass2" onkeyup="checkInputs()"><br>
<input type="submit" id="submitButton" disabled>
</form>
<div id="jsSignupAlert"></div>
</article>

View File

@ -1,7 +0,0 @@
<?php
include_once("./controller/AssetHandler.php");
AssetHandler::printAsset("logo.png", true, 128);
?>
<nav>
<a href="?p=attempt_logout">log out</a> <a href="?p=">home</a> <a href="?p=destroy">simulate $_SESSION expiry</a>
</nav>

View File

@ -1,7 +0,0 @@
<?php
include_once("./controller/AssetHandler.php");
AssetHandler::printAsset("logo.png", true, 128);
?>
<nav>
<a href="?p=login">log in</a> <a href="?p=register">register</a> <a href="?p=">home</a>
</nav>

View File

@ -1,3 +0,0 @@
<article>
<h1>Successfully logged in!</h1>
</article>

View File

@ -1,3 +0,0 @@
<article>
<h1>UNEXPECTED LOGIN ERROR. OUR CODEMONKEYS DID SOMETHING VERY WRONG :(</h1>
</article>

View File

@ -0,0 +1,6 @@
<?php
?>
<h1>
404
</h1>

View File

@ -0,0 +1,5 @@
<?php
?>
<h1>
Your account appears to be inactive. Check your email for the verification mail.
</h1>

View File

@ -0,0 +1,6 @@
<?php
use controller\MVCController;
foreach (MVCController::$viewData['boards'] as $board){
include ROOT_DIR.'/view/webcontent/modules/modules_boards/module_boardtable.php';
}
?>

View File

@ -0,0 +1,9 @@
<?php
use controller\MVCController;
?>
<form action="./?p=showthread&thread=<?=MVCController::$viewData['threadid'];?>" method="post">
<textarea placeholder="post content" name="content"></textarea><br>
<input type="submit" value="Create Reply">
<input type="hidden" name="thread" value="<?=MVCController::$viewData['threadid'];?>">
<input type="hidden" name="action" value="create_reply">
</form>

View File

@ -0,0 +1,7 @@
<form action="./" method="post">
<input type="text" placeholder="Title" name="title"><br>
<textarea placeholder="post content" name="content"></textarea><br>
<input type="submit" value="Create Thread">
<input type="hidden" name="board" value="<?= isset($_GET['board']) ? $_GET['board'] : "-1" ?>">
<input type="hidden" name="action" value="create_thread">
</form>

View File

@ -0,0 +1,4 @@
Incorrect Email or Password.
<?php
include_once(ROOT_DIR.'/view/webcontent/content_signin.php');
?>

View File

@ -0,0 +1,9 @@
<?php
use controller\UserSession;
if(UserSession::isUserSignedIn()){
include(ROOT_DIR.'/view/webcontent/header/header_signedin.php');
}
else{
include(ROOT_DIR.'/view/webcontent/header/header_signedout.php');
}
?>

View File

@ -0,0 +1,3 @@
<h1>
Please sign in to access our forum
</h1>

View File

@ -0,0 +1,12 @@
<script type="text/javascript" src="./view/js/checkform.js"></script>
<article>
<form action="?p=attempt_register" method="post">
<input type="text" name="name" id="name" placeholder="Username" onkeyup="checkInputs()"><br>
<input type="text" name="email" id="email" placeholder="E-mail" onkeyup="checkInputs()"><br>
<input type="password" name="pass" id="pass" placeholder="Password" onkeyup="checkInputs()"><br>
<input type="password" name="pass2" id="pass2" placeholder="Verify Password" onkeyup="checkInputs()"><br>
<input type="hidden" name="action" value="do_register" />
<input type="submit" id="submitButton" disabled>
</form>
<div id="jsSignupAlert"></div>
</article>

View File

@ -0,0 +1,46 @@
<?php
use controller\MVCController;
use model\forum\Thread;
use model\forum\Reply;
use model\forum\User;
//$thread = new Thread();
$thread = MVCController::$viewData['thread'];
$replies = $thread->getReplies();
?>
<table>
<h1>
<?=$thread->getTitle()?>
</h1>
<tr>
<th width="10%">user</th>
<th width="80%">content</th>
<th width="10%">date</th>
</tr>
<tr>
<td>
<?=$thread->getOwner()->getUsername();?>
</td>
<td>
<?=$thread->getContent()?>
</td>
<td>
<?=$thread->getDate_created()->format("Y M d H:i:s")?>
</td>
</tr>
<?php
foreach($replies as $reply){
$owner = $reply->getOwner()->getUsername();
$content = $reply->getContent();
$date_created = $reply->getDate()->format("Y M d H:i:s");
echo("<tr>");
echo("<td>$owner</td>");
echo("<td>$content</td>");
echo("<td>$date_created</td>");
echo("</tr>");
}
?>
</table>
<?php
$threadID = $thread->getId();
echo "<a href=\"?p=createreply&thread=$threadID\">Create Reply</a>"
?>

View File

@ -0,0 +1,6 @@
<form action="./" method="post">
<input type="text" placeholder="Email" name="email"><br>
<input type="password" placeholder="password" name="password"><br>
<input type="submit" value="Sign in">
<input type="hidden" name="action" value="login">
</form>

View File

@ -0,0 +1 @@
Signed out succesfully!

View File

@ -0,0 +1,2 @@
<?php
echo("questionmark");

View File

@ -0,0 +1,7 @@
<div class="logo">
hF
</div>
<nav>
<a href="./">Home</a>
<a href="?action=signout">Sign out</a>
</nav>

View File

@ -0,0 +1,8 @@
<div class="logo">
hF
</div>
<nav>
<a href="./">Home</a>
<a href="?p=register">Register</a>
<a href="?p=signin">Sign in</a>
</nav>

View File

@ -0,0 +1,52 @@
<?php
use controller\MVCController;
?>
<h2><?=$board->name?></h2>
<a href="?p=createthread&board=<?=$board->id?>">Create Thread</a>
<table>
<tr>
<th>Thread</th>
<th width=10%>Started by</th>
<th width=15%>Last reply</th>
</tr>
<?php
foreach (MVCController::$viewData['threads'] as $thread){
if($thread->getBoardID() == $board->id){
$currentRow = [];
$currentRow['threadID'] = $thread->getID();
$currentRow['threadTitle'] = $thread->getTitle();
foreach(MVCController::$viewData['users'] as $user){
if($user->getID() == $thread->getUserID()){
$currentRow['username'] = $user->getUsername();
break;
}
}
foreach(MVCController::$viewData['replies'] as $reply){
if(isset($reply)){
if($reply->getThreadID() == $thread->getId())
{
break;
}else{
$currentRow['lastUpdated'] = $thread->getDate_created()->format("Y M d H:i:s");
}
}
}
?>
<tr>
<td>
<a href="?p=showthread&thread=<?=$currentRow['threadID']?>"><?=$currentRow['threadTitle']?></a>
</td>
<td>
<?=$currentRow['username'] ?>
</td>
<td>
<?=$currentRow['lastUpdated']?>
</td>
</tr>
<?php
}
}
?>
</table>

View File

@ -0,0 +1,33 @@
<?php
use controller\MVCController;
use controller\db\DBBoard;
use controller\db\DBThread;
use controller\db\DBUser;
use model\forum\Board;
use model\forum\Thread;
use model\forum\User;
use model\forum\Reply;
$boards = DBBoard::getBoards();
$users = [];
$threads = [];
$threadUsers = [];
foreach ($boards as $board)
{
$threads = array_merge($threads, DBThread::getThreadsByBoard($board->getId()));
}
foreach($threads as $thread)
{
array_push($users, DBUser::getUserByUID($thread->getUserID()));
}
//MVCController::$viewData['boards'] = [new Board(0, "General", 0),new Board(1, "Admin board", 10)];
MVCController::$viewData['boards'] = $boards;
MVCController::$viewData['threads'] = $threads;
MVCController::$viewData['users'] = $users;
MVCController::$viewData['replies'] = [new Reply(0, 0, 0, "op is gay","01-01-1990")];
?>

View File

@ -0,0 +1,6 @@
<?php
use controller\MVCController;
if(isset($_GET['thread'])){
MVCController::$viewData['threadid'] = $_GET['thread'];
}
?>

Some files were not shown because too many files have changed in this diff Show More