Added Posts

This commit is contained in:
Furentes
2019-05-10 11:13:38 +02:00
parent 135b0bb9c2
commit df4ba337d8
9 changed files with 472 additions and 22 deletions

View File

@ -1,6 +1,7 @@
<?php <?php
require_once(__DIR__."/lib/autoload.php"); require_once(__DIR__."/lib/autoload.php");
$posts = $auth->getAllPosts();
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
@ -12,6 +13,13 @@ require_once(__DIR__."/lib/autoload.php");
</head> </head>
<body> <body>
<?php <?php
if ($auth->hasRole([ \Bloggr\Roles::ADMIN, \Bloggr\Roles::AUTHOR ])) {
?>
<p>
<a href="/post.php?new">Neuer Beitrag</a>
</p>
<?php
}
if (!$auth->isLoggedIn()) { if (!$auth->isLoggedIn()) {
?> ?>
<p> <p>
@ -21,8 +29,7 @@ require_once(__DIR__."/lib/autoload.php");
<a href="/register.php">Registrieren</a> <a href="/register.php">Registrieren</a>
</p> </p>
<?php <?php
} } else {
if ($auth->isLoggedIn()) {
?> ?>
<p> <p>
<a href="/logout.php">Logout</a> <a href="/logout.php">Logout</a>
@ -30,5 +37,25 @@ require_once(__DIR__."/lib/autoload.php");
<?php <?php
} }
?> ?>
<div>
<?php
if ($posts) {
foreach($posts as $post) {
?>
<p>
<h2>Titel: <a href="/post.php?view=<?= $post['id'] ?>"><?= $post['title'] ?></a></h2>
<p>
Text:
<?= substr($post['text'], 0, 512) ?><?= (substr($post['text'], 0, 512) !== $post['text']) ? '... <br><a href="/post.php?view='.$post["id"].'">Weiterlesen...</a>' : '' ?>
</p>
<p>Author: <?= $post['user'] ?></p>
</p>
<?php
}
} else {
echo 'Noch kein Beitrag vorhanden. :(';
}
?>
</div>
</body> </body>
</html> </html>

View File

@ -129,11 +129,218 @@ class Auth
public function isLoggedIn() { public function isLoggedIn() {
return isset($_SESSION['id']); return isset($_SESSION['id']);
} }
public function getId() {
if (!$this->isLoggedIn()) return false;
return $_SESSION['id'];
}
public function logout() { public function logout() {
$_SESSION['id'] = ''; $_SESSION['id'] = '';
unset($_SESSION['id']); unset($_SESSION['id']);
session_unset(); session_unset();
return true; return true;
} }
public function getUsernameById($id) {
if (empty($id) || !\is_numeric($id)) {
return false;
}
try {
$s = $this->pdo->prepare("SELECT username FROM users WHERE id = :id LIMIT 1;");
$s->execute(array(
':id' => $id,
));
if ($s->rowCount() <= 0) {
return false;
}
while ($row = $s->fetch()) {
return $row['username'];
}
return false;
} catch (\PDOException $e) {
return false;
}
}
public function hasRole($role) {
if (empty($role) || !\is_numeric($role) && !\is_array($role)) {
return false;
}
if (empty($_SESSION['id'])) return false;
try {
$s = $this->pdo->prepare("SELECT roles_mask FROM users WHERE id = :id LIMIT 1;");
$s->execute(array(
':id' => $_SESSION['id']
));
if ($s->rowCount() <= 0) {
return false;
}
while ($row = $s->fetch()) {
$mask = $row['roles_mask'];
}
if (\is_array($role)) {
foreach ($role as $key => $value) {
if (($mask & $value) === $value) {
return true;
}
}
}
return ($mask & $role) === $role;
} catch (\PDOException $e) {
return false;
}
}
public function newPost($title, $text) {
if (!$this->isLoggedIn()) return false;
$errors = array();
$title = htmlspecialchars(trim(filter_var($title, FILTER_SANITIZE_STRING)));
$text = htmlspecialchars(trim($text, FILTER_SANITIZE_STRING));
$created_at = time();
$id = [ 'Something went wrong!' ];
if (strlen($title) < 3) {
array_push($errors, 'Title is too short! Min. 3');
}
if (strlen($title) > 64) {
array_push($errors, 'Title is too long! Max. 64');
}
if (strlen($text) < 8) {
array_push($errors, 'Text is too short! Min. 8');
}
if (strlen($text) > 12000000) {
array_push($errors, 'Text is too long! MAx. 10M');
}
if (count($errors) > 0) {
return $errors;
}
try {
$s = $this->pdo->prepare("INSERT INTO posts (user, title, text, created_at) VALUES(:user, :title, :text, :created_at);");
$r = $s->execute(array(
':user' => $this->getId(),
':title' => $title,
':text' => $text,
':created_at' => $created_at,
));
$id = $this->pdo->lastInsertId();
if(!$r) {
array_push($errors, 'Something went wrong!');
}
} catch (\PDOException $e) {
array_push($errors, 'Something went wrong!');
}
if (count($errors) > 0) {
return $errors;
}
return $id;
}
public function editPost($id, $title, $text) {
if (!$this->isLoggedIn()) return false;
$errors = array();
$title = htmlspecialchars(trim(filter_var($title, FILTER_SANITIZE_STRING)));
$text = htmlspecialchars(trim($text, FILTER_SANITIZE_STRING));
$updated_at = time();
try {
$s = $this->pdo->prepare("SELECT posts.* FROM posts INNER JOIN users ON posts.user = users.id WHERE posts.user = :user AND posts.id = :post LIMIT 1;");
$s->execute(array(
':user' => $this->getId(),
':post' => $id,
));
if ($s->rowCount() <= 0) {
return false;
}
} catch (\PDOException $e) {
array_push($errors, 'Something went wrong!');
}
if (strlen($title) < 3) {
array_push($errors, 'Title is too short! Min. 3');
}
if (strlen($title) > 64) {
array_push($errors, 'Title is too long! Max. 64');
}
if (strlen($text) < 8) {
array_push($errors, 'Text is too short! Min. 8');
}
if (strlen($text) > 12000000) {
array_push($errors, 'Text is too long! MAx. 10M');
}
if (count($errors) > 0) {
return $errors;
}
try {
$s = $this->pdo->prepare("UPDATE posts SET title = :title, text = :text, updated_at = :updated_at WHERE id = :id LIMIT 1;");
$r = $s->execute(array(
':title' => $title,
':text' => $text,
':updated_at' => $updated_at,
':id' => $id,
));
if(!$r) {
array_push($errors, 'Something went wrong!');
}
} catch (\PDOException $e) {
array_push($errors, 'Something went wrong!');
}
if (count($errors) > 0) {
return $errors;
}
return true;
}
public function getPost($id) {
if (empty($id) || !\is_numeric($id)) {
return false;
}
try {
$s = $this->pdo->prepare("SELECT * FROM posts WHERE id = :id LIMIT 1;");
$s->execute(array(
':id' => $id,
));
if ($s->rowCount() <= 0) {
return false;
}
while ($row = $s->fetch()) {
$row['user'] = $this->getUsernameById($row['user']);
return $row;
}
return false;
} catch (\PDOException $e) {
return false;
}
}
public function getAllPosts() {
try {
$posts = [];
$sql = "SELECT * FROM posts ORDER BY id ASC";
$result = $this->pdo->query($sql);
if (!$result) {
return false;
}
foreach ($result as $row) {
$row['user'] = $this->getUsernameById($row['user']);
array_push($posts, $row);
}
return $posts;
} catch (\PDOException $e) {
return $posts;
}
}
} }
?> ?>

View File

@ -24,6 +24,6 @@ if(!($request_uri == "/setup")) {
$auth = new \Bloggr\Auth($pdo); $auth = new \Bloggr\Auth($pdo);
} }
echo '<pre>'; if ($auth->isLoggedIn()) {
print_r($_SESSION); echo 'Eingeloggt als <b>'.$auth->getUsernameById($auth->getId()).'</b>';
echo '</pre>'; }

View File

@ -10,4 +10,17 @@ CREATE TABLE IF NOT EXISTS `users` (
PRIMARY KEY (`id`), PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`), UNIQUE KEY `email` (`email`),
UNIQUE KEY `username` (`username`) UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table `posts`
--
CREATE TABLE `posts` (
`id` int(11) UNSIGNED NOT NULL,
`user` int(11) UNSIGNED NOT NULL,
`title` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`text` longtext CHARACTER SET utf8mb4 NOT NULL,
`created_at` int(10) UNSIGNED NOT NULL,
`updated_at` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

73
lib/sql/posts.sql Normal file
View File

@ -0,0 +1,73 @@
-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 10, 2019 at 10:50 AM
-- Server version: 10.1.38-MariaDB
-- PHP Version: 7.3.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `bloggr`
--
-- --------------------------------------------------------
--
-- Table structure for table `posts`
--
CREATE TABLE `posts` (
`id` int(11) UNSIGNED NOT NULL,
`user` int(11) UNSIGNED NOT NULL,
`title` varchar(128) CHARACTER SET utf8mb4 NOT NULL,
`text` longtext CHARACTER SET utf8mb4 NOT NULL,
`created_at` int(10) UNSIGNED NOT NULL,
`updated_at` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `posts`
--
INSERT INTO `posts` (`id`, `user`, `title`, `text`, `created_at`, `updated_at`) VALUES
(1, 1, 'test', 'test title', 1557473772, NULL),
(2, 1, 'test', 'test title', 1557473835, 1557476392),
(3, 1, 'Title of doom', 'Lorem ipsum', 1557473940, 1557476222),
(4, 1, 'awdswetf', ' wteawstrsw tws4e sw t 4aeswtg w4s ', 1557474085, NULL);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `posts`
--
ALTER TABLE `posts`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `posts`
--
ALTER TABLE `posts`
MODIFY `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

View File

@ -1,9 +1,6 @@
<?php <?php
include_once(__DIR__."/lib/autoload.php"); include_once(__DIR__."/lib/autoload.php");
// print_r($auth->register('Furentes', 'furentes@furentes.de', '123456789'));
// print_r($auth->login('Furentes', '123456789'));
// echo $auth->isLoggedIn();
// echo $auth->logout();
if ($auth->isLoggedIn()) { if ($auth->isLoggedIn()) {
header('Location: /'); header('Location: /');
} }
@ -42,7 +39,7 @@ if (isset($_POST['login'])) {
<form action="/login.php" method="post" class="clearfix"> <form action="/login.php" method="post" class="clearfix">
<label for="user">Username/E-Mail</label> <label for="user">Username/E-Mail</label>
<input type="text" name="user" id="user" value="<?= (isset($_POST['user'])) ? $_POST['user'] : ''; ?>"> <input type="text" name="user" id="user" value="<?= (isset($_POST['user'])) ? htmlspecialchars($_POST['user']) : ''; ?>">
<label for="password">Password</label> <label for="password">Password</label>
<input type="password" name="password" id="password""> <input type="password" name="password" id="password"">
<input type="submit" name="login" value="login" class="float-right"> <input type="submit" name="login" value="login" class="float-right">

136
post.php Normal file
View File

@ -0,0 +1,136 @@
<?php
include_once(__DIR__."/lib/autoload.php");
if (isset($_GET['new']) || isset($_GET['edit']) || isset($_POST['new']) || isset($_POST['edit'])) {
if (!$auth->hasRole([ \Bloggr\Roles::ADMIN, \Bloggr\Roles::AUTHOR ])) {
header('Location: /');
die();
}
}
$errors = [];
$action = '';
$data = [];
$success = false;
if (isset($_GET['view'])) {
$result = $auth->getPost($_GET['view']);
if(!$result) {
array_push($errors, '404 Not Found');
} else {
$action = 'view';
$data = $result;
}
}
else if (isset($_GET['new'])) {
$action = 'new';
}
else if (isset($_GET['edit'])) {
$action = 'edit';
} else {
array_push($errors, '404 Not Found');
}
if ($action == 'new' && isset($_POST['new'])) {
$result = $auth->newPost($_POST['title'], $_POST['text']);
if (is_array($result)) {
$errors = $result;
} else {
header("Location: /post.php?view=".$result);
}
}
$title = "";
$text = "";
if ($action == 'edit' && isset($_POST['edit'])) {
$result = $auth->editPost($_GET['edit'], $_POST['title'], $_POST['text']);
if (is_array($result)) {
$errors = $result;
} else {
$success = true;
}
}
if ($action == 'edit') {
$result = $auth->getPost($_GET['edit']);
if(!$result) {
array_push($errors, '404 Not Found');
} else {
$data = $result;
}
}
if (isset($_POST['login'])) {
$login = $auth->login($_POST['user'], $_POST['password']);
if (is_array($login)) {
$errors = $login;
} else {
header('Location: /');
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Neuer Beitrag - <?= (defined("SITE_TITLE")) ? SITE_TITLE : 'A Bloggr Site' ?></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>
<div>
<a href="/">Home</a>
<?php
foreach ($errors as $key=>$value):
?>
<span style="color: red;">
<?= $value ?>
</span><br>
<?php
endforeach;
if($success == true) {
echo '<span style="color: green;">Post bearbeitet!</span><br>';
}
if ($action == 'view'):
?>
<h2>Titel: <?= $data['title'] ?></h2>
<p>Text: <?= nl2br($data['text']) ?></p>
<p>Author: <?= $data['user'] ?></p>
<?php
endif;
if ($action == 'new'):
?>
<h2>Neuer Beitrag</h2>
<form action="<?= htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post" class="clearfix">
<label for="title">Titel</label>
<input type="text" name="title" id="title" value="<?= (isset($_POST['title'])) ? htmlspecialchars($_POST['title']) : ''; ?>"><br>
<label for="text">Text</label>
<textarea rows="4" cols="50" name="text" id="text"><?= (isset($_POST['text'])) ? htmlspecialchars($_POST['text']) : ''; ?></textarea>
<input type="submit" name="new" value="new">
</form>
<?php
endif;
if ($action == 'edit' && (count($errors) <= 0)):
?>
<h2>Beitrag Bearbeiten</h2>
<form action="<?= htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post" class="clearfix">
<label for="title">Titel</label>
<input type="text" name="title" id="title" value="<?= (isset($data['title'])) ? $data['title'] : $title; ?>"><br>
<label for="text">Text</label>
<textarea rows="4" cols="50" name="text" id="text"><?= (isset($data['text'])) ? $data['text'] : $text; ?></textarea>
<input type="submit" name="edit" value="edit">
</form>
<?php
endif;
?>
</div>
</body>
</html>

View File

@ -1,9 +1,6 @@
<?php <?php
include_once(__DIR__."/lib/autoload.php"); include_once(__DIR__."/lib/autoload.php");
// print_r($auth->register('Furentes', 'furentes@furentes.de', '123456789'));
// print_r($auth->login('Furentes', '123456789'));
// echo $auth->isLoggedIn();
// echo $auth->logout();
if ($auth->isLoggedIn()) { if ($auth->isLoggedIn()) {
header('Location: /'); header('Location: /');
} }
@ -51,9 +48,9 @@ if (isset($_POST['register'])) {
<form action="/register.php" method="post" class="clearfix"> <form action="/register.php" method="post" class="clearfix">
<label for="username">Username</label> <label for="username">Username</label>
<input type="text" name="username" id="username" value="<?= (isset($_POST['username'])) ? $_POST['username'] : ''; ?>"><br> <input type="text" name="username" id="username" value="<?= (isset($_POST['username'])) ? htmlspecialchars($_POST['username']) : ''; ?>"><br>
<label for="email">E-Mail</label> <label for="email">E-Mail</label>
<input type="text" name="email" id="email" value="<?= (isset($_POST['email'])) ? $_POST['email'] : ''; ?>"><br> <input type="text" name="email" id="email" value="<?= (isset($_POST['email'])) ? htmlspecialchars($_POST['email']) : ''; ?>"><br>
<label for="password">Password</label> <label for="password">Password</label>
<input type="password" name="password" id="password""><br> <input type="password" name="password" id="password""><br>
<label for="password2">Password wiederholen</label> <label for="password2">Password wiederholen</label>

View File

@ -17,13 +17,13 @@ $pass = "";
if (isset($_POST['check']) || isset($_POST['submit'])) { if (isset($_POST['check']) || isset($_POST['submit'])) {
$siteTitle = trim($_POST['SITE_TITLE']); $siteTitle = trim($_POST['SITE_TITLE']);
$dbHost = $_POST['DB_HOST']; $dbHost = htmlspecialchars($_POST['DB_HOST']);
$dbName = $_POST['DB_NAME']; $dbName = htmlspecialchars($_POST['DB_NAME']);
$dbUser = $_POST['DB_USER']; $dbUser = htmlspecialchars($_POST['DB_USER']);
$dbPass = $_POST['DB_PASS']; $dbPass = $_POST['DB_PASS'];
$user = $_POST['ADMIN_USER']; $user = htmlspecialchars($_POST['ADMIN_USER']);
$email = $_POST['ADMIN_EMAIL']; $email =htmlspecialchars($_POST['ADMIN_EMAIL']);
$pass = $_POST['ADMIN_PASS']; $pass = $_POST['ADMIN_PASS'];
if($siteTitle == "" || strlen($siteTitle) < 1) { if($siteTitle == "" || strlen($siteTitle) < 1) {