ok, anyone role as admin can delete or edit (post, plan and note) and type full codes please and this old codes (<?php
// /public/workspace/delete_note.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Include authentication and database connection
require_once DIR . '/../../includes/auth.php';
require_once DIR . '/../../includes/db_connect.php';
// Get plan ID from GET parameter
planid=isset(_GET['id']) ? intval($_GET['id']) : 0;
// Get current user ID
userid=_SESSION['user_id'];
if (plan_id > 0) {
// Verify that the plan belongs to the user
sql = "SELECT id FROM workspace_plans WHERE id = ? AND user_id = ?";
if (stmt=conn->prepare(sql)) {
stmt->bind_param("ii", planid,user_id);
stmt−>execute();stmt->store_result();
if (stmt->num_rows > 0) {
// Proceed to delete
stmt->close();
deletesql=delete_stmt = conn−>prepare(delete_sql)) {
deletestmt−>bindpaplan_id, userid);if(delete_stmt->execute()) {
// Success, redirect to plans.php with success message
header("Location: plans.php?message=Plan+deleted+successfully");
exit();
} else {
// Deletion failed
header("Location: plans.php?error=Failed+to+delete+plan");
exit();
}
} else {
// Prepare failed
header("Location: plans.php?error=Database+error");
exit();
}
} else {
// Plan not found or doesn't belong to user
header("Location: plans.php?error=Plan+not+found");
exit();
}
} else {
// Prepare failed
header("Location: plans.php?error=Database+error");
exit();
}
} else {
// Invalid plan ID
header("Location: plans.php?error=Invalid+plan+ID");
exit();
}
// Flush the output buffer
ob_end_flush();
?>)(<?php
// /public/workspace/delete_post.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Include authentication and database connection
require_once DIR . '/../../includes/auth.php';
require_once DIR . '/../../includes/db_connect.php';
// Get post ID from GET parameter
postid=isset(_GET['id']) ? intval($_GET['id']) : 0;
// Get current user ID
userid=_SESSION['user_id'];
if (post_id > 0) {
// Verify that the post belongs to the user
sql = "SELECT id, media_url FROM workspace_posts WHERE id = ? AND user_id = ?";
if (stmt=conn->prepare(sql)) {
stmt->bind_param("ii", postid,user_id);
stmt−>execute();stmt->bind_result(id,media_url);
if (stmt->fetch()) {
// Proceed to delete
stmt->close();
deletesql=delete_stmt = conn−>prepare(delete_sql)) {
deletestmt−>bindpapost_id, userid);if(delete_stmt->execute()) {
// If media exists, delete the file
if (media_url) {
file_path = DIR . '/../../' . ltrim(mediaurl,′/file_path)) {
unlink($file_path);
}
}
// Success, redirect to posts.php with success message
header("Location: posts.php?message=Post+deleted+successfully");
exit();
} else {
// Deletion failed
header("Location: posts.php?error=Failed+to+delete+post");
exit();
}
} else {
// Prepare failed
header("Location: posts.php?error=Database+error");
exit();
}
} else {
// Post not found or doesn't belong to user
header("Location: posts.php?error=Post+not+found");
exit();
}
} else {
// Prepare failed
header("Location: posts.php?error=Database+error");
exit();
}
} else {
// Invalid post ID
header("Location: posts.php?error=Invalid+post+ID");
exit();
}
// Flush the output buffer
ob_end_flush();
?>)(<?php
// /public/workspace/edit_note.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Include authentication, database connection, and utility functions
require_once DIR . '/../../includes/auth.php';
require_once DIR . '/../../includes/db_connect.php';
require_once DIR . '/../../includes/functions.php'; // Contains sanitize_input()
// Handle GET request to fetch existing note data
if (_SERVER['REQUEST_METHOD'] === 'GET') {
if (note_id > 0) {
sql="SELECTtitle,contentFROMworkspacenotesWHEREid=?ANDuserid=?";if(stmt = conn−>prepare(sql)) {
stmt−>bindparam("ii",note_id, userid);stmt->execute();
stmt−>bindresult(title, content);if(!stmt->fetch()) {
errors[] = "Note not found.";
}
stmt->close();
} else {
errors[] = "Database error: Unable to prepare statement.";
}
} else {
errors[] = "Invalid note ID.";
}
}
// Handle POST request to update the note
if (_SERVER['REQUEST_METHOD'] === 'POST') {
title = sanitize_input(POST[′title′]??′′);content = sanitize_input($_POST['content'] ?? '');
code
// Validation
if (empty($title)) {
$errors[] = "Title is required.";
}
if (empty($content)) {
$errors[] = "Content is required.";
}
if ($note_id > 0) {
// Verify that the note belongs to the user
$sql_check = "SELECT id FROM workspace_notes WHERE id = ? AND user_id = ?";
if ($stmt_check = $conn->prepare($sql_check)) {
$stmt_check->bind_param("ii", $note_id, $user_id);
$stmt_check->execute();
$stmt_check->store_result();
if ($stmt_check->num_rows > 0) {
$stmt_check->close();
// Update the note
$update_sql = "UPDATE workspace_notes SET title = ?, content = ?, updated_at = CURRENT_TIMESTAMP() WHERE id = ? AND user_id = ?";
if ($stmt_update = $conn->prepare($update_sql)) {
$stmt_update->bind_param("ssii", $title, $content, $note_id, $user_id);
if ($stmt_update->execute()) {
// Success, redirect to view_note.php with success message
header("Location: view_note.php?id=$note_id&message=Note+updated+successfully");
exit();
} else {
$errors[] = "Failed to update note. Please try again.";
}
$stmt_update->close();
} else {
$errors[] = "Database error: Unable to prepare update statement.";
}
} else {
$errors[] = "Note not found or you do not have permission to edit this note.";
}
} else {
$errors[] = "Database error: Unable to prepare statement.";
}
} else {
$errors[] = "Invalid note ID.";
}
// Include authentication, database connection, and utility functions
require_once DIR . '/../../includes/auth.php';
require_once DIR . '/../../includes/db_connect.php';
require_once DIR . '/../../includes/functions.php'; // Contains sanitize_input()
// Handle GET request to fetch existing plan data
if (_SERVER['REQUEST_METHOD'] === 'GET') {
if (plan_id > 0) {
sql="SELECTtitle,description,duedate,statusFROMworks?ANDuserid=?";if(stmt = conn−>prepare(sql)) {
stmt−>bindparam("ii",plan_id, userid);stmt->execute();
stmt−>bindresult(title, description,due_date, status);if(!stmt->fetch()) {
errors[] = "Plan not found.";
}
stmt->close();
} else {
errors[] = "Database error: Unable to prepare statement.";
}
} else {
errors[] = "Invalid plan ID.";
}
}
// Handle POST request to update the plan
if (_SERVER['REQUEST_METHOD'] === 'POST') {
title = sanitize_input(POST[′title′]??′′);description = sanitize_input(POST[′descriptiondue_date = sanitize_input(POST[′duedstatus = sanitize_input($_POST['status'] ?? 'Not Started');
code
// Validation
if (empty($title)) {
$errors[] = "Title is required.";
}
if (empty($due_date)) {
$errors[] = "Due date is required.";
}
// Validate status
$valid_statuses = ['Not Started', 'In Progress', 'Completed'];
if (!in_array($status, $valid_statuses)) {
$errors[] = "Invalid status selected.";
}
// Validate due_date format
if (!strtotime($due_date)) {
$errors[] = "Invalid due date format.";
}
if ($plan_id > 0) {
// Verify that the plan belongs to the user
$sql_check = "SELECT id FROM workspace_plans WHERE id = ? AND user_id = ?";
if ($stmt_check = $conn->prepare($sql_check)) {
$stmt_check->bind_param("ii", $plan_id, $user_id);
$stmt_check->execute();
$stmt_check->store_result();
if ($stmt_check->num_rows > 0) {
$stmt_check->close();
// Update the plan
$update_sql = "UPDATE workspace_plans SET title = ?, description = ?, due_date = ?, status = ?, updated_at = CURRENT_TIMESTAMP() WHERE id = ? AND user_id = ?";
if ($stmt_update = $conn->prepare($update_sql)) {
$stmt_update->bind_param("ssssis", $title, $description, $due_date, $status, $plan_id, $user_id);
if ($stmt_update->execute()) {
// Success, redirect to view_plan.php with success message
header("Location: view_plan.php?id=$plan_id&message=Plan+updated+successfully");
exit();
} else {
$errors[] = "Failed to update plan. Please try again.";
}
$stmt_update->close();
} else {
$errors[] = "Database error: Unable to prepare update statement.";
}
} else {
$errors[] = "Plan not found or you do not have permission to edit this plan.";
}
} else {
$errors[] = "Database error: Unable to prepare statement.";
}
} else {
$errors[] = "Invalid plan ID.";
}
// Include authentication, database connection, and utility functions
require_once DIR . '/../../includes/auth.php';
require_once DIR . '/../../includes/db_connect.php';
require_once DIR . '/../../includes/functions.php'; // Contains sanitize_input()
// Handle GET request to fetch existing post data
if (_SERVER['REQUEST_METHOD'] === 'GET') {
if (post_id > 0) {
sql="SELECTplatform,content,mediaurl,scheduled?ANDuserid=?";if(stmt = conn−>prepare(sql)) {
stmt−>bindparam("ii",post_id, userid);stmt->execute();
stmt−>bindresult(platform, content,media_url, scheduleddatetime,status);
if (!stmt->fetch()) {
errors[] = "Post not found.";
}
stmt->close();
} else {
errors[] = "Database error: Unable to prepare statement.";
}
} else {
$errors[] = "Invalid post ID.";
}
}
// Handle POST request to update the post
if (_SERVER['REQUEST_METHOD'] === 'POST') {
platform = sanitize_input(POST[′platform′]??′′);content = sanitize_input(POST[′contentscheduled_datetime = sanitize_input(POST[′scheduledstatus = 'Scheduled'; // This can be modified if needed
code
// Handle media upload if any
$new_media_url = $media_url; // Existing media_url
if (isset($_FILES['media']) && $_FILES['media']['error'] !== UPLOAD_ERR_NO_FILE) {
if ($_FILES['media']['error'] === UPLOAD_ERR_OK) {
$allowed_types = ['image/jpeg', 'image/png', 'video/mp4', 'image/gif'];
if (in_array($_FILES['media']['type'], $allowed_types)) {
$upload_dir = __DIR__ . '/../../assets/uploads/workspace_posts/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0755, true);
}
// Generate a unique filename
$file_ext = pathinfo($_FILES['media']['name'], PATHINFO_EXTENSION);
$filename = time() . '_' . bin2hex(random_bytes(8)) . '.' . $file_ext;
$filepath = $upload_dir . $filename;
if (move_uploaded_file($_FILES['media']['tmp_name'], $filepath)) {
// Delete old media file if exists
if ($media_url) {
$old_file_path = __DIR__ . '/../../' . ltrim($media_url, '/');
if (file_exists($old_file_path)) {
unlink($old_file_path);
}
}
// Store relative path
$new_media_url = '/assets/uploads/workspace_posts/' . $filename;
} else {
$errors[] = "Failed to upload media.";
}
} else {
$errors[] = "Unsupported media type. Allowed types: JPEG, PNG, GIF, MP4.";
}
} else {
$errors[] = "Error uploading media.";
}
}
// Validation
if (empty($platform)) {
$errors[] = "Platform is required.";
}
if (empty($content)) {
$errors[] = "Content is required.";
}
if (empty($scheduled_datetime)) {
$errors[] = "Scheduled date and time are required.";
}
// Validate platform
$valid_platforms = ['Instagram', 'Facebook', 'Twitter', 'Other'];
if (!in_array($platform, $valid_platforms)) {
$errors[] = "Invalid platform selected.";
}
// Validate scheduled_datetime
if (!strtotime($scheduled_datetime)) {
$errors[] = "Invalid scheduled date and time.";
}
if (empty($errors)) {
if ($post_id > 0) {
// Verify ownership
$sql_check = "SELECT id, media_url FROM workspace_posts WHERE id = ? AND user_id = ?";
if ($stmt_check = $conn->prepare($sql_check)) {
$stmt_check->bind_param("ii", $post_id, $user_id);
$stmt_check->execute();
$stmt_check->bind_result($id, $existing_media_url);
if ($stmt_check->fetch()) {
$stmt_check->close();
// Update the post
$update_sql = "UPDATE workspace_posts SET platform = ?, content = ?, media_url = ?, scheduled_datetime = ?, status = ?, updated_at = CURRENT_TIMESTAMP() WHERE id = ? AND user_id = ?";
if ($stmt_update = $conn->prepare($update_sql)) {
$stmt_update->bind_param("ssssiii", $platform, $content, $new_media_url, $scheduled_datetime, $status, $post_id, $user_id);
if ($stmt_update->execute()) {
// Success, redirect to view_post.php with success message
header("Location: view_post.php?id=$post_id&message=Post+updated+successfully");
exit();
} else {
$errors[] = "Failed to update post. Please try again.";
}
$stmt_update->close();
} else {
$errors[] = "Database error: Unable to prepare update statement.";
}
} else {
$errors[] = "Post not found or you do not have permission to edit this post.";
}
} else {
$errors[] = "Database error: Unable to prepare statement.";
}
} else {
$errors[] = "Invalid post ID.";
}
}
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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: u406552082_kaakalia
--
-- Table structure for table customers
CREATE TABLE customers (
id int(11) NOT NULL,
name varchar(100) NOT NULL,
contact varchar(50) DEFAULT NULL,
delivery_address text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table drivers
CREATE TABLE drivers (
id int(11) NOT NULL,
name varchar(100) NOT NULL,
number varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table orders
CREATE TABLE orders (
id int(11) NOT NULL,
customer_id int(11) NOT NULL,
status enum('Pending','In Progress','Completed','Delivered') DEFAULT 'Pending',
priority enum('Normal','Important','Quick') DEFAULT 'Normal',
order_date datetime DEFAULT current_timestamp(),
delivery_datetime datetime DEFAULT NULL,
delivery_date date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table order_items
CREATE TABLE order_items (
id int(11) NOT NULL,
order_id int(11) NOT NULL,
product_id int(11) NOT NULL,
quantity int(11) NOT NULL DEFAULT 1,
packaging_preferences varchar(255) DEFAULT NULL,
discount_percentage decimal(5,2) DEFAULT 0.00,
discount_reason varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table products
CREATE TABLE products (
id int(11) NOT NULL,
name varchar(100) NOT NULL,
size varchar(50) DEFAULT NULL,
price decimal(10,2) NOT NULL,
category varchar(50) DEFAULT NULL,
thumbnail varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table users
CREATE TABLE users (
id int(11) NOT NULL,
username varchar(50) NOT NULL,
password varchar(255) NOT NULL,
role enum('admin','staff') NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table workspace_notes
CREATE TABLE workspace_notes (
id int(11) NOT NULL,
user_id int(11) NOT NULL,
title varchar(255) NOT NULL,
content text NOT NULL,
created_at datetime DEFAULT current_timestamp(),
updated_at datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table workspace_plans
CREATE TABLE workspace_plans (
id int(11) NOT NULL,
user_id int(11) NOT NULL,
title varchar(255) NOT NULL,
description text DEFAULT NULL,
due_date datetime DEFAULT NULL,
status enum('Not Started','In Progress','Completed') DEFAULT 'Not Started',
created_at datetime DEFAULT current_timestamp(),
updated_at datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Table structure for table workspace_posts
CREATE TABLE workspace_posts (
id int(11) NOT NULL,
user_id int(11) NOT NULL,
platform enum('Instagram','Facebook','Twitter','Other') NOT NULL,
content text NOT NULL,
media_url varchar(255) DEFAULT NULL,
scheduled_datetime datetime DEFAULT NULL,
status enum('Scheduled','Posted','Failed') DEFAULT 'Scheduled',
created_at datetime DEFAULT current_timestamp(),
updated_at datetime DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE customers
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table drivers
ALTER TABLE drivers
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table orders
ALTER TABLE orders
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table order_items
ALTER TABLE order_items
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table products
ALTER TABLE products
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table users
ALTER TABLE users
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table workspace_notes
ALTER TABLE workspace_notes
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table workspace_plans
ALTER TABLE workspace_plans
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table workspace_posts
ALTER TABLE workspace_posts
MODIFY id int(11) NOT NULL AUTO_INCREMENT;
--
-- Constraints for dumped tables
--
-- Constraints for table orders
ALTER TABLE orders
ADD CONSTRAINT fk_orders_customer_id FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT orders_ibfk_1 FOREIGN KEY (customer_id) REFERENCES customers (id) ON DELETE CASCADE;
--
-- Constraints for table order_items
ALTER TABLE order_items
ADD CONSTRAINT fk_order_items_order_id FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT fk_order_items_product_id FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT order_items_ibfk_1 FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE,
ADD CONSTRAINT order_items_ibfk_2 FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE;
--
-- Constraints for table workspace_notes
ALTER TABLE workspace_notes
ADD CONSTRAINT fk_workspace_notes_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
--
-- Constraints for table workspace_plans
ALTER TABLE workspace_plans
ADD CONSTRAINT fk_workspace_plans_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
--
-- Constraints for table workspace_posts
ALTER TABLE workspace_posts
ADD CONSTRAINT fk_workspace_posts_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
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 */;) and this index.php (<?php
// /public/workspace/index.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Include authentication, database connection, and utility functions
require_once DIR . '/../../includes/auth.php';
require_once DIR . '/../../includes/db_connect.php';
require_once DIR . '/../../includes/functions.php'; // Contains sanitize_input()
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
// Fetch summary data: Total Number of Plans, Posts, Notes
try {
// Total Plans
planscountsql="SELECTCOUNT(∗)AStotalFROMworkspaceplans";stmt = conn−>prepare(plans_count_sql);
if (!stmt) {
throw new Exception("Prepare statement failed for plans count: " . conn->error);
}
stmt−>execute();result = stmt−>getresult();plans_count = result−>fetchassoc()[stmt->close();
code
// Total Posts
$posts_count_sql = "SELECT COUNT(*) AS total FROM workspace_posts";
$stmt = $conn->prepare($posts_count_sql);
if (!$stmt) {
throw new Exception("Prepare statement failed for posts count: " . $conn->error);
}
$stmt->execute();
$result = $stmt->get_result();
$posts_count = $result->fetch_assoc()['total'] ?? 0;
$stmt->close();
// Total Notes
$notes_count_sql = "SELECT COUNT(*) AS total FROM workspace_notes";
$stmt = $conn->prepare($notes_count_sql);
if (!$stmt) {
throw new Exception("Prepare statement failed for notes count: " . $conn->error);
}
$stmt->execute();
$result = $stmt->get_result();
$notes_count = $result->fetch_assoc()['total'] ?? 0;
$stmt->close();
} catch (Exception e) {
errors[] = e−>getMessage();plans_count = postscount=notes_count = 0; // Default values in case of error
}
// Fetch upcoming plans and posts for the calendar along with creator's username
try {
// Fetch Plans
calendarplanssql="SELECTwp.id,wstmt = conn−>prepare(calendar_plans_sql);
if (!stmt) {
throw new Exception("Prepare statement failed for calendar plans: " . conn->error);
}
stmt−>execute();result = $stmt->get_result();
code
while ($plan = $result->fetch_assoc()) {
$calendar_events[] = [
'id' => 'plan_' . $plan['id'], // Prefix to distinguish type
'title' => sanitize_input($plan['title']) . " (by " . sanitize_input($plan['username']) . ")",
'start' => $plan['due_date'],
'type' => 'plan', // Custom property to identify type
'color' => '#3B82F6' // Tailwind Blue-500
];
}
$stmt->close();
// Fetch Posts
$calendar_posts_sql = "SELECT wp.id, CONCAT(wp.platform, ': ', wp.content) AS content, wp.scheduled_datetime, u.username
FROM workspace_posts wp
JOIN users u ON wp.user_id = u.id
WHERE wp.scheduled_datetime >= NOW()
ORDER BY wp.scheduled_datetime ASC";
$stmt = $conn->prepare($calendar_posts_sql);
if (!$stmt) {
throw new Exception("Prepare statement failed for calendar posts: " . $conn->error);
}
$stmt->execute();
$result = $stmt->get_result();
while ($post = $result->fetch_assoc()) {
$calendar_events[] = [
'id' => 'post_' . $post['id'], // Prefix to distinguish type
'title' => sanitize_input($post['content']) . " (by " . sanitize_input($post['username']) . ")",
'start' => $post['scheduled_datetime'],
'type' => 'post', // Custom property to identify type
'color' => '#10B981' // Tailwind Green-500
];
}
$stmt->close();
// (Optional) Fetch recent activities: Plans, Posts, Notes
recentplans=[];recent_posts = [];
recentnotes=[];items_per_section = 5; // Number of items to display in each recent section
Certainly! Below are the fully updated PHP scripts that allow users with the admin role to delete or edit posts, plans, and notes regardless of ownership. Regular users can still only delete or edit their own items. These scripts include comprehensive role checks to ensure proper access control.
Assumptions:
Session Variables:
$_SESSION['user_id']: Stores the authenticated user's ID.
$_SESSION['role']: Stores the authenticated user's role ('admin' or 'staff').
Included Files:
auth.php: Handles user authentication and initializes session variables.
db_connect.php: Establishes a connection to the MySQL database.
functions.php: Contains utility functions like sanitize_input().
Database Schema:
Users are stored in the users table with roles determining their permissions.
1. /public/workspace/delete_note.php
This script allows an admin to delete any note or a regular user to delete their own notes.
php
<?php
// /public/workspace/delete_note.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start output buffering to prevent "headers already sent" errors
ob_start();
// Include authentication and database connection
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
// Get user details from session
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'
// Get note ID from GET parameter
$note_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($note_id > 0) {
// Verify that the note belongs to the user or the user is admin
if ($user_role === 'admin') {
// Admin can delete any note
$sql = "SELECT id FROM workspace_notes WHERE id = ?";
$stmt = $conn->prepare($sql);
if ($stmt) {
$stmt->bind_param("i", $note_id);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->close();
// Proceed to delete
$delete_sql = "DELETE FROM workspace_notes WHERE id = ?";
$delete_stmt = $conn->prepare($delete_sql);
if ($delete_stmt) {
$delete_stmt->bind_param("i", $note_id);
if ($delete_stmt->execute()) {
// Success, redirect to notes.php with success message
header("Location: notes.php?message=Note+deleted+successfully");
exit();
} else {
// Deletion failed
header("Location: notes.php?error=Failed+to+delete+note");
exit();
}
} else {
// Prepare failed
header("Location: notes.php?error=Database+error");
exit();
}
} else {
// Note not found
header("Location: notes.php?error=Note+not+found");
exit();
}
} else {
// Prepare failed
header("Location: notes.php?error=Database+error");
exit();
}
} else {
// Regular user: Verify ownership
$sql = "SELECT id FROM workspace_notes WHERE id = ? AND user_id = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ii", $note_id, $user_id);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// Proceed to delete
$stmt->close();
$delete_sql = "DELETE FROM workspace_notes WHERE id = ? AND user_id = ?";
if ($delete_stmt = $conn->prepare($delete_sql)) {
$delete_stmt->bind_param("ii", $note_id, $user_id);
if ($delete_stmt->execute()) {
// Success, redirect to notes.php with success message
header("Location: notes.php?message=Note+deleted+successfully");
exit();
} else {
// Deletion failed
header("Location: notes.php?error=Failed+to+delete+note");
exit();
}
} else {
// Prepare failed
header("Location: notes.php?error=Database+error");
exit();
}
} else {
// Note not found or doesn't belong to user
header("Location: notes.php?error=Note+not+found");
exit();
}
} else {
// Prepare failed
header("Location: notes.php?error=Database+error");
exit();
}
}
} else {
// Invalid note ID
header("Location: notes.php?error=Invalid+note+ID");
exit();
}
// Flush the output buffer
ob_end_flush();
?>
2. /public/workspace/delete_plan.php
This script allows an admin to delete any plan or a regular user to delete their own plans.
php
3. /public/workspace/delete_post.php
This script allows an admin to delete any post or a regular user to delete their own posts.
php
4. /public/workspace/edit_note.php
This script allows an admin to edit any note or a regular user to edit their own notes.
php
5. /public/workspace/edit_plan.php
This script allows an admin to edit any plan or a regular user to edit their own plans.
php
6. /public/workspace/edit_post.php
This script allows an admin to edit any post or a regular user to edit their own posts.
php
7. /public/workspace/index.php
The index.php serves as the main dashboard and doesn't directly handle delete/edit operations. However, admins can view and manage all plans, posts, and notes from this dashboard.
php
Additional Notes:
Role Management:
Ensure that the auth.php script initializes the $_SESSION['role'] variable correctly upon user login.
Example in auth.php after successful authentication:
php
$_SESSION['user_id'] = $user['id'];
$_SESSION['role'] = $user['role']; // 'admin' or 'staff'
Security Considerations:
Input Sanitization: All user inputs are sanitized using the sanitize_input() function to prevent XSS attacks.
Prepared Statements: All database queries use prepared statements to prevent SQL injection.
File Uploads: Media uploads are validated for allowed file types and unique filenames are generated to prevent overwriting.
Consistent Behavior:
Admin users can perform CRUD operations on any resource (posts, plans, notes) without restrictions.
Regular users (staff) can only perform CRUD operations on their own resources.
User Interface:
The index.php dashboard displays different counts and recent activities based on the user's role.
The calendar and recent activities sections dynamically adjust the displayed data based on whether the user is an admin or a regular user.
Database Constraints:
Foreign key constraints ensure referential integrity between tables.
Cascading deletes ensure that related records are appropriately handled when a parent record is deleted.
Error Handling:
All scripts provide user-friendly error messages in case of failures or unauthorized access attempts.
Errors are logged server-side for debugging but presented to users in a controlled manner to avoid information leakage.
Tailwind CSS & Bootstrap Icons:
The UI leverages Tailwind CSS for styling and Bootstrap Icons for visual elements, ensuring a responsive and modern design.
By implementing these updated scripts, your application will now allow admin users to manage all posts, plans, and notes, while regular users are restricted to managing only their own entries. Ensure that all included files (auth.php, db_connect.php, and functions.php) are correctly configured to support these functionalities.
<?php
// /public/workspace/delete_plan.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start output buffering to prevent "headers already sent" errors
ob_start();
// Include authentication and database connection
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
// Get user details from session
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'
// Get plan ID from GET parameter
$plan_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($plan_id > 0) {
// Verify that the plan belongs to the user or the user is admin
if ($user_role === 'admin') {
// Admin can delete any plan
$sql = "SELECT id FROM workspace_plans WHERE id = ?";
$stmt = $conn->prepare($sql);
if ($stmt) {
$stmt->bind_param("i", $plan_id);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->close();
// Proceed to delete
$delete_sql = "DELETE FROM workspace_plans WHERE id = ?";
$delete_stmt = $conn->prepare($delete_sql);
if ($delete_stmt) {
$delete_stmt->bind_param("i", $plan_id);
if ($delete_stmt->execute()) {
// Success, redirect to plans.php with success message
header("Location: plans.php?message=Plan+deleted+successfully");
exit();
} else {
// Deletion failed
header("Location: plans.php?error=Failed+to+delete+plan");
exit();
}
} else {
// Prepare failed
header("Location: plans.php?error=Database+error");
exit();
}
} else {
// Plan not found
header("Location: plans.php?error=Plan+not+found");
exit();
}
} else {
// Prepare failed
header("Location: plans.php?error=Database+error");
exit();
}
} else {
// Regular user: Verify ownership
$sql = "SELECT id FROM workspace_plans WHERE id = ? AND user_id = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ii", $plan_id, $user_id);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
// Proceed to delete
$stmt->close();
$delete_sql = "DELETE FROM workspace_plans WHERE id = ? AND user_id = ?";
$delete_stmt = $conn->prepare($delete_sql);
if ($delete_stmt) {
$delete_stmt->bind_param("ii", $plan_id, $user_id);
if ($delete_stmt->execute()) {
// Success, redirect to plans.php with success message
header("Location: plans.php?message=Plan+deleted+successfully");
exit();
} else {
// Deletion failed
header("Location: plans.php?error=Failed+to+delete+plan");
exit();
}
} else {
// Prepare failed
header("Location: plans.php?error=Database+error");
exit();
}
} else {
// Plan not found or doesn't belong to user
header("Location: plans.php?error=Plan+not+found");
exit();
}
} else {
// Prepare failed
header("Location: plans.php?error=Database+error");
exit();
}
}
} else {
// Invalid plan ID
header("Location: plans.php?error=Invalid+plan+ID");
exit();
}
// Flush the output buffer
ob_end_flush();
?>
<?php
// /public/workspace/delete_post.php
// Enable error reporting for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Start output buffering to prevent "headers already sent" errors
ob_start();
// Include authentication and database connection
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../includes/db_connect.php';
// Ensure the user is authenticated
if (!isset($_SESSION['user_id'])) {
header("Location: /public/login.php");
exit();
}
// Get user details from session
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'
// Get post ID from GET parameter
$post_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($post_id > 0) {
// Verify that the post belongs to the user or the user is admin
if ($user_role === 'admin') {
// Admin can delete any post
$sql = "SELECT id, media_url FROM workspace_posts WHERE id = ?";
$stmt = $conn->prepare($sql);
if ($stmt) {
$stmt->bind_param("i", $post_id);
$stmt->execute();
$stmt->bind_result($id, $media_url);
if ($stmt->fetch()) {
$stmt->close();
// Proceed to delete
$delete_sql = "DELETE FROM workspace_posts WHERE id = ?";
$delete_stmt = $conn->prepare($delete_sql);
if ($delete_stmt) {
$delete_stmt->bind_param("i", $post_id);
if ($delete_stmt->execute()) {
// If media exists, delete the file
if ($media_url) {
$file_path = __DIR__ . '/../../' . ltrim($media_url, '/');
if (file_exists($file_path)) {
unlink($file_path);
}
}
// Success, redirect to posts.php with success message
header("Location: posts.php?message=Post+deleted+successfully");
exit();
} else {
// Deletion failed
header("Location: posts.php?error=Failed+to+delete+post");
exit();
}
} else {
// Prepare failed
header("Location: posts.php?error=Database+error");
exit();
}
} else {
// Post not found
header("Location: posts.php?error=Post+not+found");
exit();
}
} else {
// Prepare failed
header("Location: posts.php?error=Database+error");
exit();
}
} else {
// Regular user: Verify ownership
$sql = "SELECT id, media_url FROM workspace_posts WHERE id = ? AND user_id = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ii", $post_id, $user_id);
$stmt->execute();
$stmt->bind_result($id, $media_url);
if ($stmt->fetch()) {
$stmt->close();
// Proceed to delete
$delete_sql = "DELETE FROM workspace_posts WHERE id = ? AND user_id = ?";
$delete_stmt = $conn->prepare($delete_sql);
if ($delete_stmt) {
$delete_stmt->bind_param("ii", $post_id, $user_id);
if ($delete_stmt->execute()) {
// If media exists, delete the file
if ($media_url) {
$file_path = __DIR__ . '/../../' . ltrim($media_url, '/');
if (file_exists($file_path)) {
unlink($file_path);
}
}
// Success, redirect to posts.php with success message
header("Location: posts.php?message=Post+deleted+successfully");
exit();
} else {
// Deletion failed
header("Location: posts.php?error=Failed+to+delete+post");
exit();
}
} else {
// Prepare failed
header("Location: posts.php?error=Database+error");
exit();
}
} else {
// Post not found or doesn't belong to user
header("Location: posts.php?error=Post+not+found");
exit();
}
} else {
// Prepare failed
header("Location: posts.php?error=Database+error");
exit();
}
}
} else {
// Invalid post ID
header("Location: posts.php?error=Invalid+post+ID");
exit();
}
// Flush the output buffer
ob_end_flush();
?>