Compare commits

..

42 Commits

Author SHA1 Message Date
Felix Ivo
5ef5de9b98 fixed document upload location 2025-07-08 10:51:57 +02:00
Felix Ivo
92e162283e fixed directory location 2025-07-07 15:08:56 +02:00
Felix Ivo
26fb9b54b6 fixed upoad folder missing 2025-07-07 14:52:46 +02:00
Felix Ivo
b4fcc4892c fixed sorting 2025-07-07 14:50:48 +02:00
Felix Ivo
58e0f1eafd Merge branch 'main' of http://git.pb.bib.de/PBBFA23CIV/EIANotesApp 2025-07-07 14:42:47 +02:00
Felix Ivo
9bca8fd1d1 added admin page 2025-07-07 14:42:34 +02:00
bb9424232c Merge branch 'main' of http://git.pb.bib.de/PBBFA23CIV/EIANotesApp 2025-07-07 14:39:42 +02:00
e8766ecc26 added priority to notes 2025-07-07 14:28:11 +02:00
Felix Ivo
c5ebde8b20 fix filepath link 2025-07-07 10:54:32 +02:00
Felix Ivo
4ae6971b9c added gitignore 2025-07-07 10:50:51 +02:00
Felix Ivo
0799db48f0 add uploaded files to edit, note details, welcome page 2025-07-07 10:42:12 +02:00
Felix Ivo
9db4d93ce3 comment out test_write file 2025-07-07 10:27:19 +02:00
Felix Ivo
aabd6288fe Merge branch 'main' of http://git.pb.bib.de/PBBFA23CIV/EIANotesApp 2025-07-07 10:21:31 +02:00
Felix Ivo
48f1fb8923 added upload to createNotes 2025-07-07 10:21:15 +02:00
ce59837500 Deutsch --> Englisch 2025-07-03 16:57:26 +02:00
3c9d90ebb8 Merge branch 'main' of http://git.pb.bib.de/PBBFA23CIV/EIANotesApp 2025-06-30 11:11:58 +02:00
Felix Ivo
871ffe01d0 removed isEditMode 2025-06-30 10:37:43 +02:00
36ea386e04 Merge branch 'main' of http://git.pb.bib.de/PBBFA23CIV/EIANotesApp 2025-06-30 10:37:32 +02:00
31fff91725 removed comment 2025-06-30 10:36:48 +02:00
Felix Ivo
b92f7c1054 sanitized login form 2025-06-30 10:35:03 +02:00
Felix Ivo
6dbca7cbd4 Merge branch 'main' of http://git.pb.bib.de/PBBFA23CIV/EIANotesApp 2025-06-30 10:26:48 +02:00
Felix Ivo
ba9ec6b430 Willkommen statistik 2025-06-30 10:26:39 +02:00
63899ffa8f Merge branch 'main' of http://git.pb.bib.de/PBBFA23CIV/EIANotesApp 2025-06-30 10:11:06 +02:00
5c381740ff removed comment 2025-06-30 10:11:01 +02:00
Felix Ivo
fc17a1a312 fixed edit note 2025-06-30 10:10:42 +02:00
5eb3e30114 Merge branch 'main' of http://git.pb.bib.de/PBBFA23CIV/EIANotesApp 2025-06-27 11:02:11 +02:00
ab757adfbd Redirect and ErrorMessage for RegisterUser 2025-06-27 11:02:01 +02:00
Felix Ivo
95b7634901 fixed delete note 2025-06-27 10:54:24 +02:00
Felix Ivo
5a63cc66c5 redirects work for create and edit 2025-06-27 10:29:34 +02:00
1a5a069844 Redirect to login when clicking notes and no user logged in 2025-06-27 10:03:45 +02:00
Felix Ivo
24c8f38c4d added create and eedit note functionality (flawed) 2025-06-27 09:56:46 +02:00
Felix Ivo
1e9705aa13 fixed isAdmin 2025-06-23 14:19:04 +02:00
Felix Ivo
df103f9b86 enabled admin user column 2025-06-23 14:11:37 +02:00
Felix Ivo
5741783dbe give nav bar style 2025-06-23 13:56:24 +02:00
6cceae17d0 Merge branch 'main' of http://git.pb.bib.de/PBBFA23CIV/EIANotesApp 2025-06-23 11:13:55 +02:00
3d4e1532c7 Register 2025-06-23 11:13:48 +02:00
Felix Ivo
80cb9f2818 fixed margins 2025-06-23 11:12:35 +02:00
Felix Ivo
bcde6649b5 enabled live markdown preview 2025-06-23 11:06:11 +02:00
Felix Ivo
e54a8f241e fixed parsedown import, submit buttons are now shown 2025-06-23 11:04:08 +02:00
Felix Ivo
21aa81dbd3 removed user specified hardcode 2025-06-23 10:52:30 +02:00
Felix Ivo
7d1d48199a Merge branch 'main' of http://git.pb.bib.de/PBBFA23CIV/EIANotesApp 2025-06-23 10:49:07 +02:00
Felix Ivo
d21da71585 edit and create notes first push 2025-06-23 10:48:57 +02:00
17 changed files with 827 additions and 91 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
uploads

View File

@@ -19,10 +19,39 @@ body {
}
.top-bar h1 {
margin: 0;
margin: 0 30px 0 0;
font-size: 1.5em;
}
.top-nav {
display: flex;
align-items: center;
justify-content: center;
margin-right: auto;
}
.top-nav ul {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-wrap: wrap;
}
.top-nav li {
margin-right: 15px;
}
.top-nav li a {
color: white;
text-decoration: none;
padding: 8px 12px;
border-radius: 4px;
background-color: transparent;
cursor: pointer;
font-size: 0.9em;
}
.user-info {
display: flex;
align-items: center;
@@ -309,4 +338,19 @@ button.danger {
font-size: 0.8em;
color: #6A5ACD;
display: inline-block;
}
.style_low {
background-color: darkseagreen;
font-weight: bold;
}
.style_mid {
background-color: moccasin;
font-weight: bold;
}
.style_high {
background-color: lightcoral;
font-weight: bold;
}

View File

@@ -18,6 +18,12 @@ class NotesController
public function showNotes()
{
# Redirect zum Login wenn kein User eingeloggt ist
if(!Isset($_SESSION['role']))
{
header("Location: ?controller=User&do=showUserLoginForm");
}
$sortBy = $_GET['sort_by'] ?? 'updated_at';
$sortOrder = strtoupper($_GET['sort_order'] ?? 'DESC');
$isAdmin = $_SESSION['role'] === 'admin';
@@ -36,4 +42,100 @@ class NotesController
"note" => $note
]);
}
public function createNote()
{
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Process form submission
$note = $this->notesModel->createNote(
$_POST['title'],
$_POST['content'],
$_SESSION['user_id'],
$_POST['priority']
);
if ($note) {
// Redirect to show notes page after successful creation
header('Location: ?controller=Notes&page=showNotes&do=showNotes');
exit();
} else {
// If creation failed, show error message and stay on the form
$this->view->setVars([
'error' => 'Failed to create note. Please try again.'
]);
}
}
}
public function editNote()
{
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Process form submission
$noteId = $_GET['id'];
$note = $this->notesModel->editNote(
$noteId,
$_POST['title'],
$_POST['content'],
$_SESSION['user_id'],
$_POST['priority']
);
if ($note) {
// Redirect to show notes page after successful update
header('Location: ?controller=Notes&page=showNotes&do=showNotes');
exit();
} else {
// If update failed, show error message and stay on the form
$this->view->setVars([
'error' => 'Failed to update note. Please try again.'
]);
}
}
}
public function deleteNote()
{
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['note_id'])) {
$noteId = $_POST['note_id'];
$this->notesModel->deleteNote($noteId, $_SESSION['user_id']);
}
header("Location: ?controller=Notes&page=showNotes&do=showNotes");
exit();
}
public function fileManager()
{
# Redirect zum Login wenn kein User eingeloggt ist
if(!Isset($_SESSION['role']))
{
header("Location: ?controller=User&do=showUserLoginForm");
}
# Redirect zum Welcome wenn kein User kein Admin ist
if(!Isset($_SESSION['role']) || $_SESSION['role'] !== 'admin')
{
header("Location: ?controller=Welcome&do=showWelcome");
}
$sortBy = $_GET['sort_by'] ?? 'uploaded_at';
$sortOrder = strtoupper($_GET['sort_order'] ?? 'DESC');
$isAdmin = $_SESSION['role'] === 'admin';
$userid = $_SESSION['user_id'];
$files = $this->notesModel->selectFiles($userid, true, $sortBy, $sortOrder);
$this->view->setVars([
"files" => $files
]);
}
public function deleteFile()
{
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['file_id'])) {
$fileId = $_POST['file_id'];
$this->notesModel->deleteFile($fileId, $_SESSION['user_id']);
}
header("Location: ?controller=Notes&do=fileManager");
exit();
}
}

View File

@@ -20,7 +20,7 @@ class UserController
public function loginUser()
{
$erg = array();
$erg = $this->userModel->verifyLogin($_POST["username"], $_POST["password"]);
$erg = $this->userModel->loginUser($this->sanitize($_POST["username"]), $this->sanitize($_POST["password"]) );
if ($erg["success"] == true) {
header("Location: ?controller=Welcome&do=showWelcome");
exit();
@@ -28,9 +28,6 @@ class UserController
}
else {
$this->view->setDoMethodName("showUserLoginForm");
$this->view->setVars([
"errmsg" => $erg["message"]
]);
$this->showUserLoginForm();
}
@@ -39,16 +36,41 @@ class UserController
public function logoutUser()
{
$this->userModel->logoutUser();
header("Location: ?controller=Welcome&do=showWelcome");
header("Location: ?controller=User&do=showUserLoginForm");
exit();
}
public function registerUser()
{
$erg = array();
$erg = $this->userModel->registerUser($this->sanitize($_POST["username"]), $this->sanitize($_POST["password"]) );
if ($erg["success"] == true) {
header("Location: ?controller=User&do=showUserLoginForm");
exit();
}
else {
$this->view->setDoMethodName("showUserRegisterForm");
$message = $this->sanitize($erg['message']);
echo "<script type='text/javascript'>alert(\"$message\");</script>";
$this->view->setVars([
"errmsg" => $message
]);
$this->showUserRegisterForm();
}
}
public function showUserLoginForm()
{
}
public function showUserRegisterForm()
{
}
function sanitize($data, $flags = ENT_QUOTES, $encoding = 'UTF-8') {
return htmlspecialchars((string)$data, $flags, $encoding);
}
}

View File

@@ -2,13 +2,11 @@
namespace ppa\Controller;
/**
* Description of Welcome
*
* @author reich
*/
class WelcomeController
{
private $notesModel;
private $view;
public function setView(\ppa\Library\View $view)
{
$this->view = $view;
@@ -16,5 +14,8 @@ class WelcomeController
function showWelcome()
{
if ($this->notesModel === null) {
$this->notesModel = new \ppa\Model\NotesModel();
}
}
}

View File

@@ -1,4 +1,3 @@
// public/script.js
document.addEventListener('DOMContentLoaded', () => {
// --- Password Strength Checker for Registration ---
const passwordInput = document.getElementById('password');
@@ -58,60 +57,7 @@ document.addEventListener('DOMContentLoaded', () => {
if(passwordInput.value) passwordInput.dispatchEvent(new Event('input'));
}
// --- Delete Note Confirmation and AJAX ---
document.querySelectorAll('.delete-note-btn').forEach(button => {
button.addEventListener('click', function(e) {
e.preventDefault();
if (confirm('Are you sure you want to delete this note?')) {
const noteId = this.dataset.noteId;
// Create a temporary form to submit for delete
const tempForm = document.createElement('form');
tempForm.method = 'POST';
tempForm.style.display = 'none';
const actionInput = document.createElement('input');
actionInput.type = 'hidden';
actionInput.name = 'action';
actionInput.value = 'delete_note';
tempForm.appendChild(actionInput);
const noteIdInput = document.createElement('input');
noteIdInput.type = 'hidden';
noteIdInput.name = 'note_id';
noteIdInput.value = noteId;
tempForm.appendChild(noteIdInput);
document.body.appendChild(tempForm); // Form must be in DOM to submit
// Use handleAjaxForm for consistency
const formData = new FormData(tempForm);
fetch('index.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
displayMessage(data.message, data.success ? 'success' : 'danger');
if (data.success) {
// Refresh page or remove row dynamically for better UX
// For simplicity, reload. A more advanced way is to find and remove table row.
setTimeout(() => { window.location.reload(); }, 1000);
}
})
.catch(error => {
console.error('Error:', error);
displayMessage('An error occurred during deletion.', 'danger');
})
.finally(() => {
document.body.removeChild(tempForm); // Clean up
});
}
});
});
// --- Drag and Drop File Upload ---
// ... (no changes from previous, ensure it's present)
const dropZone = document.getElementById('drop-zone');
const noteTitleInput = document.getElementById('title');
const noteContentInput = document.getElementById('content');

View File

@@ -12,7 +12,7 @@ class NotesModel extends Database
$erg = array();
// Whitelist of allowed sort columns
$allowedSortColumns = ['id', 'title', 'owner_username', 'updated_at'];
$allowedSortColumns = ['id', 'title', 'owner_username', 'updated_at', 'priority'];
$allowedSortOrders = ['ASC', 'DESC'];
$sortBy = in_array($sortBy, $allowedSortColumns) ? $sortBy : 'updated_at';
@@ -20,15 +20,17 @@ class NotesModel extends Database
try {
if ($isAdmin) {
$sql = "SELECT n.*, u.username AS owner_username
$sql = "SELECT n.id, n.title, n.content, n.created_at, n.updated_at, u.username AS owner_username, p.name AS priority
FROM notes n
JOIN users u ON n.user_id = u.id
JOIN priority p ON n.priority = p.id
JOIN users u ON n.user_id = u.id
ORDER BY {$sortBy} {$sortOrder}";
$stmt = $pdo->prepare($sql);
$stmt->execute();
} else {
$sql = "SELECT id, title, content, created_at, updated_at
FROM notes
$sql = "SELECT n.id, n.title, n.content, n.created_at, n.updated_at, p.name AS priority
FROM notes n
JOIN priority p ON n.priority = p.id
WHERE user_id = :userid
ORDER BY {$sortBy} {$sortOrder}";
$stmt = $pdo->prepare($sql);
@@ -43,6 +45,37 @@ class NotesModel extends Database
return false;
}
}
public function selectFiles($userid, $isAdmin = false, $sortBy = 'updated_at', $sortOrder = 'DESC')
{
$pdo = $this->linkDB();
$erg = array();
// Whitelist of allowed sort columns
$allowedSortColumns = ['id', 'original_filename', 'stored_filename', 'note_id', 'owner_username', 'uploaded_at', 'file_size'];
$allowedSortOrders = ['ASC', 'DESC'];
$sortBy = in_array($sortBy, $allowedSortColumns) ? $sortBy : 'uploaded_at';
$sortOrder = in_array(strtoupper($sortOrder), $allowedSortOrders) ? strtoupper($sortOrder) : 'DESC';
try {
if ($isAdmin) {
$sql = "SELECT f.*, n.title AS note_title, u.username AS owner_username
FROM files f
JOIN notes n ON f.note_id = n.id
JOIN users u ON n.user_id = u.id
ORDER BY {$sortBy} {$sortOrder}";
$stmt = $pdo->prepare($sql);
$stmt->execute();
}
$erg = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $erg;
} catch (PDOException $e) {
error_log("Database Error in selectFiles: " . $e->getMessage());
return false;
}
}
function getNoteById($noteId) {
$pdo = $this->linkDB();
@@ -61,4 +94,203 @@ class NotesModel extends Database
return null;
}
}
function createNote($title, $content, $userId, $priority) {
$pdo = $this->linkDB();
if (!$pdo) return ['success' => false, 'message' => 'Database error.'];
if (empty(trim($title))) return ['success' => false, 'message' => 'Title is required.'];
try {
$stmt = $pdo->prepare("INSERT INTO notes (user_id, title, content, priority) VALUES (?, ?, ?, ?)");
$stmt->execute([$userId, trim($title), $content, $priority]); // user_id is current session user
$noteId = $pdo->lastInsertId();
$uploadResult = $this->uploadFiles($noteId);
if (!$uploadResult['success']) {
return $uploadResult;
}
return ['success' => true, 'message' => 'Note created successfully.'];
} catch (PDOException $e) {
error_log("Create Note Error: " . $e->getMessage());
return ['success' => false, 'message' => 'Failed to create note.'];
}
}
function editNote($noteId, $title, $content, $userId, $priority) {
$pdo = $this->linkDB();
if (!$pdo) return ['success' => false, 'message' => 'Database error.'];
if (empty(trim($title))) return ['success' => false, 'message' => 'Title is required.'];
try {
if ($this->isAdmin()) { // Admin can update any note, user_id for record not changed
$stmt = $pdo->prepare("UPDATE notes SET title = ?, content = ?, priority = ? WHERE id = ?");
$params = [trim($title), $content, $priority, $noteId];
} else { // User can only update their own note
$stmt = $pdo->prepare("UPDATE notes SET title = ?, content = ?, priority = ? WHERE id = ? AND user_id = ?");
$params = [trim($title), $content, $priority, $noteId, $userId];
}
$stmt->execute($params);
$uploadResult = $this->uploadFiles($noteId);
if (!$uploadResult['success']) {
return $uploadResult;
}
if ($stmt->rowCount() > 0) {
return ['success' => true, 'message' => 'Note updated successfully.'];
}
// Check if note exists if rowCount is 0
$checkStmt = $this->isAdmin() ? $pdo->prepare("SELECT id FROM notes WHERE id=?") : $pdo->prepare("SELECT id FROM notes WHERE id=? AND user_id=?");
$checkParams = $this->isAdmin() ? [$noteId] : [$noteId, $userId];
$checkStmt->execute($checkParams);
if ($checkStmt->fetch()) {
return ['success' => true, 'message' => 'No changes made to the note.'];
}
return ['success' => false, 'message' => 'Note not found or permission denied.'];
} catch (PDOException $e) {
error_log("Update Note Error: " . $e->getMessage());
return ['success' => false, 'message' => 'Failed to update note.'];
}
}
function deleteNote($noteId, $userId) {
$pdo = $this->linkDB();
if (!$pdo) return ['success' => false, 'message' => 'Database error.'];
try {
if ($this->isAdmin()) { // Admin can delete any note
$stmt = $pdo->prepare("DELETE FROM notes WHERE id = ?");
$params = [$noteId];
} else { // User can only delete their own note
$stmt = $pdo->prepare("DELETE FROM notes WHERE id = ? AND user_id = ?");
$params = [$noteId, $userId];
}
$stmt->execute($params);
if ($stmt->rowCount() > 0) {
return ['success' => true, 'message' => 'Note deleted successfully.'];
}
return ['success' => false, 'message' => 'Note not found or permission denied.'];
} catch (PDOException $e) {
error_log("Delete Note Error: " . $e->getMessage());
return ['success' => false, 'message' => 'Failed to delete note.'];
}
}
function getUploadedFiles($noteId) {
$pdo = $this->linkDB();
if (!$pdo) return [];
try {
$stmt = $pdo->prepare("SELECT * FROM files WHERE note_id = ?");
$stmt->execute([$noteId]);
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log("Get Uploaded Files Error: " . $e->getMessage());
return [];
}
}
function getFileCount() {
$pdo = $this->linkDB();
if (!$pdo) return 0;
try {
$stmt = $pdo->prepare("SELECT COUNT(*) FROM files");
$stmt->execute();
return $stmt->fetchColumn();
} catch (PDOException $e) {
error_log("Get Files Count Error: " . $e->getMessage());
return 0;
}
}
function getNoteCount() {
$pdo = $this->linkDB();
if (!$pdo) return 0;
try {
$stmt = $pdo->prepare("SELECT COUNT(*) FROM notes");
$stmt->execute();
return $stmt->fetchColumn();
} catch (PDOException $e) {
error_log("Get Notes Count Error: " . $e->getMessage());
return 0;
}
}
function isLoggedIn() {
return isset($_SESSION['user_id']);
}
function isAdmin() {
return $this->isLoggedIn() && isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}
public function uploadFiles($noteId) {
$pdo = $this->linkDB();
if (!$pdo) return ['success' => false, 'message' => 'Database error.'];
$uploadDir = __DIR__ . '/../Uploads/';
$uploadedFileNames = [];
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
if (isset($_FILES['attachments']) && !empty($_FILES['attachments']['name'][0])) {
$files = $_FILES['attachments'];
foreach ($files['name'] as $key => $name) {
if ($files['error'][$key] === UPLOAD_ERR_OK) {
$tmpName = $files['tmp_name'][$key];
$safeFilename = basename($name);
$uniqueFilename = time() . '-' . preg_replace('/[^A-Za-z0-9.\-]/', '_', $safeFilename);
$destination = $uploadDir . $uniqueFilename;
if (move_uploaded_file($tmpName, $destination)) {
$uploadedFileNames[] = $uniqueFilename;
$stmt = $pdo->prepare("INSERT INTO files (note_id, original_filename, stored_filename, file_type, file_size, uploaded_at) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->execute([$noteId, $safeFilename, $uniqueFilename, $files['type'][$key], $files['size'][$key], date('Y-m-d H:i:s')]);
} else {
$errmsg = "Error: Could not move uploaded file '$safeFilename'.";
}
} else {
$errmsg = "Error uploading file '$name'. Error code: " . $files['error'][$key];
}
}
}
if (isset($errmsg)) {
return ['success' => false, 'message' => $errmsg];
}
return ['success' => true, 'message' => 'Files uploaded successfully.', 'fileNames' => $uploadedFileNames];
}
public function deleteFile($fileId, $userId) {
$pdo = $this->linkDB();
if (!$pdo) return ['success' => false, 'message' => 'Database error.'];
try {
// Delete the local file
$stmt = $pdo->prepare("SELECT stored_filename FROM files WHERE id = ?");
$stmt->execute([$fileId]);
$file = $stmt->fetch();
if ($file) {
$filePath = __DIR__ . '/../Uploads/' . $file['stored_filename'];
if (file_exists($filePath)) {
unlink($filePath);
}
}
if ($this->isAdmin()) { // Admin can delete any file
$stmt = $pdo->prepare("DELETE FROM files WHERE id = ?");
$params = [$fileId];
} else { // User can only delete their own files
$stmt = $pdo->prepare("DELETE FROM files WHERE id = ? AND note_id IN (SELECT id FROM notes WHERE user_id = ?)");
$params = [$fileId, $userId];
}
$stmt->execute($params);
if ($stmt->rowCount() > 0) {
return ['success' => true, 'message' => 'File deleted successfully.'];
}
return ['success' => false, 'message' => 'File not found or permission denied.'];
} catch (PDOException $e) {
error_log("Delete File Error: " . $e->getMessage());
return ['success' => false, 'message' => 'Failed to delete file.'];
}
}
}

View File

@@ -7,7 +7,7 @@ use PDOException;
class UserModel extends Database
{
public function verifyLogin($username, $password)
public function loginUser($username, $password)
{
$pdo = $this->linkDB();
if (!$pdo) return ['success' => false, 'message' => 'Database connection error.'];
@@ -31,8 +31,55 @@ class UserModel extends Database
function logoutUser()
{
session_unset(); // Unset all session variables
session_unset();
session_destroy();
return ['success' => true, 'message' => 'Logged out successfully.'];
}
function registerUser($username, $password) {
$pdo = $this->linkDB();
if (!$pdo) return ['success' => false, 'message' => 'Database connection error.'];
$errors = [];
if (empty($username)) $errors[] = "Username is required.";
if (empty($password)) $errors[] = "Password is required.";
if (strlen($password) < 8) $errors[] = "Password must be at least 8 characters.";
if (!preg_match('/[A-Z]/', $password)) $errors[] = "Password needs an uppercase letter.";
if (!preg_match('/[a-z]/', $password)) $errors[] = "Password needs a lowercase letter.";
if (!preg_match('/[0-9]/', $password)) $errors[] = "Password needs a number.";
if (!preg_match('/[^A-Za-z0-9]/', $password)) $errors[] = "Password needs a special character.";
if (!empty($errors)) {
return ['success' => false, 'message' => implode("\\n", $errors)];
}
try {
$stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
$stmt->execute([$username]);
if ($stmt->fetch()) {
return ['success' => false, 'message' => 'Username already taken.'];
}
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)"); // Role defaults to 'user'
$stmt->execute([$username, $hashedPassword]);
return ['success' => true, 'message' => 'Registration successful! Please login.'];
} catch (PDOException $e) {
error_log("Registration Error: " . $e->getMessage());
return ['success' => false, 'message' => 'An error occurred during registration.'];
}
}
function getUserCount() {
$pdo = $this->linkDB();
if (!$pdo) return 0;
try {
$stmt = $pdo->prepare("SELECT COUNT(*) FROM users");
$stmt->execute();
return $stmt->fetchColumn();
} catch (PDOException $e) {
error_log("Get User Count Error: " . $e->getMessage());
return 0;
}
}
}

View File

@@ -0,0 +1,85 @@
<?php
use ppa\Model\NotesModel;
include dirname(__DIR__).'/header.phtml';
//// Test write permissions
//// This is the directory we will upload files to.
//$uploadDir = __DIR__ . '/../Uploads/';
//if (!file_exists($uploadDir)) {
// mkdir($uploadDir, 0777, true);
//}
//$testFile = $uploadDir . 'test_write.txt';
//$testContent = 'Test write operation at ' . date('Y-m-d H:i:s');
//$writeResult = file_put_contents($testFile, $testContent);
$parsedown = new Parsedown();
$parsedown->setSafeMode(true);
$this->notesModel = new \ppa\Model\NotesModel();
$note = null;
function isLoggedIn() {
return isset($_SESSION['user_id']);
}
function isAdmin() {
return isLoggedIn() && isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}
function sanitize($data, $flags = ENT_QUOTES, $encoding = 'UTF-8') {
return htmlspecialchars((string)$data, $flags, $encoding);
}
?>
<div class="container">
<div class="page-header">
<h2>Create New Note</h2>
<a href="?controller=Notes&page=showNotes&do=showNotes" class="button secondary">Cancel</a>
</div>
<label class="error-message"><?php if (isset($errmsg)):?>
<?php echo $errmsg;?>
<?php endif; ?></label>
<div id="drop-zone">Drag & drop a .txt or .md file here, or fill manually.</div>
<form id="note-form" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="create_note">
<div class="form-group">
<label for="title">Title:</label>
<input type="text" id="title" name="title" value="" required>
</div>
<div class="form-group">
<label for="content">Content (Markdown supported):</label>
<textarea id="content" name="content" rows="10" required></textarea>
</div>
<div class="form-group">
<label>Live Markdown Preview:</label>
<div id="markdown-preview" class="markdown-preview">
Start typing or drop a file to see preview...
</div>
</div>
<div class="form-group">
<label>Priorität:</label>
<select name="priority" id="priority">
<option value="1">LOW</option>
<option value="2">MID</option>
<option value="3">HIGH</option>
</select>
</div>
<div class="form-group">
<label for="attachments">Attach Files:</label>
<input type="file" id="attachments" name="attachments[]" multiple>
</div>
<div class="form-actions">
<button type="submit" class="button">Create Note</button>
</div>
<input type="hidden" name="controller" value="Notes">
<input type="hidden" name="do" value="createNote">
</form>
</div>

View File

@@ -0,0 +1,89 @@
<?php
use ppa\Model\NotesModel;
include dirname(__DIR__).'/header.phtml';
$parsedown = new Parsedown();
$parsedown->setSafeMode(true);
$this->notesModel = new \ppa\Model\NotesModel();
$note = null;
$noteId = $_GET['id'] ?? 0;
$note = $this->notesModel->getNoteById($noteId, $_SESSION['user_id']);
if (!$note) {
echo "<div class='alert alert-danger'>Note not found or you don't have permission to edit it.</div>";
echo "<a href='?controller=Notes&page=showNotes&do=showNotes' class='button secondary'>Back to Dashboard</a>";
}
$files = $this->notesModel->getUploadedFiles($noteId);
function isLoggedIn() {
return isset($_SESSION['user_id']);
}
function isAdmin() {
return isLoggedIn() && isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}
function sanitize($data, $flags = ENT_QUOTES, $encoding = 'UTF-8') {
return htmlspecialchars((string)$data, $flags, $encoding);
}
?>
<div class="container">
<div class="page-header">
<h2><?php echo 'Edit Note' . (isAdmin() && $note && $note['user_id'] != $_SESSION['user_id'] ? ' (Admin Edit - Owner: '.sanitize($note['owner_username']).')' : '') ?></h2>
<a href="?controller=Notes&page=showNotes&do=showNotes" class="button secondary">Cancel</a>
</div>
<div id="drop-zone">Drag & drop a .txt or .md file here, or fill manually.</div>
<form id="note-form" method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="update_note">
<input type="hidden" name="note_id" value="<?php echo sanitize($note['id']); ?>">
<div class="form-group">
<label for="title">Title:</label>
<input type="text" id="title" name="title" value="<?php echo $note ? sanitize($note['title']) : ''; ?>" required>
</div>
<div class="form-group">
<label for="content">Content (Markdown supported):</label>
<textarea id="content" name="content" rows="10" required><?php echo $note ? sanitize($note['content']) : ''; ?></textarea>
</div>
<div class="form-group">
<label>Live Markdown Preview:</label>
<div id="markdown-preview" class="markdown-preview">
<?php if($note && !empty($note['content'])) echo $parsedown->text(sanitize($note['content'])); else echo "Start typing or drop a file to see preview..."; ?>
</div>
</div>
<div class="form-group">
<label>Priorität:</label>
<select name="priority" id="priority">
<option value="1">LOW</option>
<option value="2">MID</option>
<option value="3">HIGH</option>
</select>
</div>
<div class="form-group">
<label for="attachments">Attach additional Files:</label>
<input type="file" id="attachments" name="attachments[]" multiple>
</div>
<?php if($files && count($files) > 0): ?>
<div class="form-group">
<label>Files currently attached:</label>
<ul>
<?php foreach($files as $file): ?>
<li>
<a href="<?php echo substr($_SERVER['PHP_SELF'], 0, -9).'Uploads/'.$file['stored_filename']; ?>" download target="_blank"><?php echo htmlspecialchars($file['original_filename']); ?></a>
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<div class="form-actions">
<button type="submit" class="button">Update Note</button>
</div>
<input type="hidden" name="controller" value="Notes">
<input type="hidden" name="do" value="editNote">
</form>
</div>

View File

@@ -0,0 +1,64 @@
<?php include dirname(__DIR__).'/header.phtml'; ?>
<div class="container">
<?php
function isLoggedIn() {
return isset($_SESSION['user_id']);
}
function isAdmin() {
return isLoggedIn() && isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}
function sanitize($data, $flags = ENT_QUOTES, $encoding = 'UTF-8') {
return htmlspecialchars((string)$data, $flags, $encoding);
}
$sortBy = $_GET['sort_by'] ?? 'uploaded_at';
$sortOrder = strtoupper($_GET['sort_order'] ?? 'DESC'); // Ensure uppercase for comparison
?>
<div class="page-header">
<h2>All Users' Files</h2>
</div>
<?php if (isset($errmsg)): ?>
<label class="error-message"><?php echo $errmsg; ?></label>
<?php endif; ?>
<table class="notes-table">
<thead>
<tr>
<th data-sort="id">File ID <span class="sort-icon"><?php if($sortBy === 'id') echo $sortOrder === 'ASC' ? '▲' : '▼'; ?></span></th>
<th data-sort="original_filename">Original File Name <span class="sort-icon"><?php if($sortBy === 'original_filename') echo $sortOrder === 'ASC' ? '▲' : '▼'; ?></span></th>
<th data-sort="stored_filename">Stored File Name <span class="sort-icon"><?php if($sortBy === 'stored_filename') echo $sortOrder === 'ASC' ? '▲' : '▼'; ?></span></th>
<th data-sort="note_id">Note ID <span class="sort-icon"><?php if($sortBy === 'note_id') echo $sortOrder === 'ASC' ? '▲' : '▼'; ?></span></th>
<th data-sort="owner_username">Owner <span class="sort-icon"><?php if($sortBy === 'owner_username') echo $sortOrder === 'ASC' ? '▲' : '▼'; ?></span></th>
<th data-sort="uploaded_at">Uploaded At <span class="sort-icon"><?php if($sortBy === 'uploaded_at') echo $sortOrder === 'ASC' ? '▲' : '▼'; ?></span></th>
<th data-sort="file_size">File Size <span class="sort-icon"><?php if($sortBy === 'file_size') echo $sortOrder === 'ASC' ? '▲' : '▼'; ?></span></th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($files as $file): ?>
<tr>
<td><?php echo sanitize($file['id']); ?></td>
<td><a href="<?php echo substr($_SERVER['PHP_SELF'], 0, -9).'Uploads/'.$file['stored_filename']; ?>"><?php echo sanitize($file['stored_filename']); ?></a></td>
<td><?php echo sanitize($file['stored_filename']); ?></td>
<td><?php echo sanitize($file['note_id']); ?></td>
<td><?php echo sanitize($file['owner_username']); ?></td>
<td><?php echo date("d.m.Y H:i", strtotime($file['uploaded_at'])); ?></td>
<td><?php echo round(sanitize($file['file_size']) / 1024, 2) . ' KB'; ?></td>
<td class="actions-cell">
<form method="POST" action="?controller=Notes&do=deleteFile" onsubmit="return confirm('Are you sure you want to delete this file?');" style="display: inline;">
<input type="hidden" name="file_id" value="<?php echo $file['id']; ?>">
<button type="submit" class="button danger">Delete</button>
<input type="hidden" name="controller" value="Notes">
<input type="hidden" name="do" value="deleteFile">
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php include dirname(__DIR__).'/footer.phtml'; ?>

View File

@@ -3,6 +3,9 @@
<?php
$parsedown = new Parsedown();
$parsedown->setSafeMode(true);
$this->notesModel = new \ppa\Model\NotesModel();
$files = $this->notesModel->getUploadedFiles($note['id']);
?>
<div class="container">
@@ -24,10 +27,23 @@ $parsedown->setSafeMode(true);
<?php echo $parsedown->text($note['content'] ?? ''); ?>
</div>
<div class="note-files">
<?php if (isset($files) && count($files) > 0): ?>
<h3>Attached Files:</h3>
<ul>
<?php foreach ($files as $file): ?>
<li>
<a href="<?php echo substr($_SERVER['PHP_SELF'], 0, -9).'Uploads/'.$file['stored_filename']; ?>" download target="_blank"><?php echo htmlspecialchars($file['original_filename']); ?></a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</div>
<div class="note-actions">
<a href="?controller=NotesController&page=showNotes" class="button">Back to Notes</a>
<a href="?controller=Notes&page=showNotes&do=showNotes" class="button">Back to Notes</a>
<?php if (isset($note['id'])): ?>
<a href="?controller=NotesController&page=editNote&note_id=<?php echo (int)$note['id']; ?>" class="button">Edit Note</a>
<a href="?controller=Notes&do=editNote&id=<?php echo (int)$note['id']; ?>" class="button">Edit Note</a>
<?php endif; ?>
</div>
</div>
@@ -35,7 +51,7 @@ $parsedown->setSafeMode(true);
<div class="error-message">
<h2>Note Not Found</h2>
<p><?php echo htmlspecialchars($error ?? 'The requested note could not be found.'); ?></p>
<a href="?controller=NotesController&page=showNotes" class="button">Back to Notes</a>
<a href="?controller=Notes&page=showNotes&do=showNotes" class="button">Back to Notes</a>
</div>
<?php endif; ?>
</div>

View File

@@ -1,7 +1,5 @@
<?php include dirname(__DIR__).'/header.phtml'; ?>
<h2>Notes</h2>
<div class="container">
<?php
$parsedown = new Parsedown();
@@ -12,8 +10,9 @@
}
function isAdmin() {
return false;// isLoggedIn() && isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
return isLoggedIn() && isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}
function sanitize($data, $flags = ENT_QUOTES, $encoding = 'UTF-8') {
return htmlspecialchars((string)$data, $flags, $encoding);
}
@@ -21,6 +20,15 @@
$sortBy = $_GET['sort_by'] ?? 'updated_at';
$sortOrder = strtoupper($_GET['sort_order'] ?? 'DESC'); // Ensure uppercase for comparison
?>
<div class="page-header">
<h2><?php echo isAdmin() ? "All Users' Notes" : "My Notes"; ?></h2>
<a href="?controller=Notes&do=createNote" class="button">Create New Note</a>
</div>
<?php if (isset($errmsg)): ?>
<label class="error-message"><?php echo $errmsg; ?></label>
<?php endif; ?>
<table class="notes-table">
<thead>
<tr>
@@ -31,6 +39,7 @@
<?php endif; ?>
<th>Content (Preview)</th>
<th data-sort="updated_at">Last Edited <span class="sort-icon"><?php if($sortBy === 'updated_at') echo $sortOrder === 'ASC' ? '▲' : '▼'; ?></span></th>
<th data-sort="priority">Priority<span class="sort-icon"><?php if($sortBy === 'priority') echo $sortOrder === 'ASC' ? '▲' : '▼'; ?></span></th>
<th>Actions</th>
</tr>
</thead>
@@ -50,9 +59,21 @@
?>
</td>
<td><?php echo date("d.m.Y H:i", strtotime($note['updated_at'])); ?></td>
<?php
if($note['priority'] === 'LOW') echo ('<td class="style_low";>');
elseif($note['priority'] === 'MID') echo ('<td class="style_mid";>');
elseif($note['priority'] === 'HIGH') echo ('<td class="style_high";>');
echo sanitize($note['priority']);
echo ('</td>')
?>
<td class="actions-cell">
<a href="index.php?page=edit_note&id=<?php echo $note['id']; ?>" class="button">Edit</a>
<button class="button danger delete-note-btn" data-note-id="<?php echo $note['id']; ?>">Delete</button>
<a href="?controller=Notes&do=editNote&id=<?php echo $note['id']; ?>" class="button">Edit</a>
<form method="POST" action="?controller=Notes&do=deleteNote" onsubmit="return confirm('Are you sure you want to delete this note?');" style="display: inline;">
<input type="hidden" name="note_id" value="<?php echo $note['id']; ?>">
<button type="submit" class="button danger">Delete</button>
<input type="hidden" name="controller" value="Notes">
<input type="hidden" name="do" value="deleteNote">
</form>
</td>
</tr>
<?php endforeach; ?>

View File

@@ -17,7 +17,7 @@
<?php echo $errmsg;?>
<?php endif; ?>
</label>
<p style="margin-top:15px; text-align:center;">Don't have an account? <a href="index.php?page=register">Register here</a></p>
<p style="margin-top:15px; text-align:center;">Don't have an account? <a href="?controller=User&do=showUserRegisterForm">Register here</a></p>
</div>
<input type="hidden" name="controller" value="User">
<input type="hidden" name="do" value="loginUser">

View File

@@ -0,0 +1,28 @@
<?php include dirname(__DIR__).'/header.phtml'; ?>
<div class="form-container">
<h2>Register</h2>
<form id="register-form" method="POST">
<input type="hidden" name="action" value="register">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<div class="password-strength-meter"><div id="strength-bar"></div></div>
<div id="password-strength"><ul></ul></div>
</div>
<div class="form-group">
<label for="confirm_password">Confirm Password:</label>
<input type="password" id="confirm_password" name="confirm_password" required>
</div>
<div class="form-actions">
<button type="submit" >Register</button>
<p style="margin-top:15px; text-align:center;">Already have an account? <a href="?controller=User&do=showUserLoginForm">Login here</a></p>
</div>
<input type="hidden" name="controller" value="User">
<input type="hidden" name="do" value="registerUser">
</form>
</div>
<?php include dirname(__DIR__).'/footer.phtml'; ?>

View File

@@ -1,6 +1,39 @@
<?php include dirname(__DIR__).'/header.phtml'; ?>
<?php
use ppa\Model\NotesModel;
include dirname(__DIR__).'/header.phtml';
$parsedown = new Parsedown();
$parsedown->setSafeMode(true);
$this->notesModel = new \ppa\Model\NotesModel();
$this->userModel = new \ppa\Model\UserModel();
?>
<h2>Welcome in out Notes App!</h2>
<p>To start, simply select an option in the navigation bar.</p>
<h2>Notes App statistics</h2>
<b style="font-size: 20px; margin: 20px">
<?php
echo $this->notesModel->getNoteCount();
?>
Notes
</b><br>
<b style="font-size: 20px; margin: 20px">
<?php
echo $this->userModel->getUserCount();
?>
Users
</b><br>
<b style="font-size: 20px; margin: 20px">
<?php
echo $this->notesModel->getFileCount();
?>
Files
</b><br>
<h2>Baustelle</h2>
<?php include dirname(__DIR__).'/footer.phtml'; ?>

View File

@@ -5,18 +5,29 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width">
<link href="CSS/style.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/2.1.0/showdown.min.js"></script>
<script src="JavaScript/script.js"></script>
</head>
<body>
<header class="top-bar">
<h1>Notes App <?php if(isset($_SESSION['role']) && $_SESSION['role'] === 'admin') echo "<span style='font-size:0.7em; color:#ffdd57;'>(Admin Panel)</span>"; ?></h1>
<nav class="top-nav">
<ul>
<li><a href="?controller=Welcome&do=showWelcome">Welcome!</a></li>
<li><a href="?controller=Notes&do=showNotes">Notes</a></li>
<?php if (isset($_SESSION['role']) && $_SESSION['role'] === 'admin'): ?>
<li><a href="?controller=Notes&do=fileManager">File Manager</a></li>
<?php endif; ?>
</ul>
</nav>
<?php if (isset($_SESSION['user_id'])): ?>
<div class="user-info">
<span>Welcome, <?php echo htmlspecialchars($_SESSION['username'], ENT_QUOTES, 'UTF-8'); ?>!</span>
<form id="logout-form" method="POST" style="display: inline;">
<a class="icon-button" href="?controller=User&do=logoutUser"></a>
</form>
<!-- <button class="icon-button" title="More options">⋮</button> -->
</div>
<?php else: ?>
<div class="user-info">
@@ -29,11 +40,5 @@
</div>
<?php endif; ?>
</header>
<nav>
<ul>
<li><a href="?controller=Welcome&do=showWelcome">Willkommen</a></li>
<li><a href="?controller=Notes&do=showNotes">Notizen</a></li>
</ul>
</nav>
<div class="wrapper">
<main>