Certainly! Below is the fully updated edit_plan.php script that incorporates the audio upload and recording functionalities, as well as the priority field, based on the create_plan.php script you provided. This enhanced version ensures that administrators can manage audio files associated with workspace plans, while maintaining the existing functionality for regular users.
Key Updates:
- Audio Handling: Administrators can upload audio files or record audio directly within the edit form.
- Priority Field: Added a priority selection (
Normal, Important, Critical) to the edit form.
- Audio Management: When updating a plan, existing audio files are handled appropriately (e.g., deleted if replaced).
- UI Enhancements: The form dynamically shows/hides audio options based on user selection, similar to the create form.
<?php
// /public/workspace/edit_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, 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();
}
$user_id = $_SESSION['user_id'];
$user_role = $_SESSION['role']; // 'admin' or 'staff'
$plan_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
$errors = [];
$title = '';
$description = '';
$due_date = '';
$status = 'Not Started';
$priority = 'Normal';
$audio_path = '';
// Handle GET request to fetch existing plan data
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if ($plan_id > 0) {
if ($user_role === 'admin') {
// Admin can edit any plan
$sql = "SELECT title, description, due_date, status, priority, audio_path FROM workspace_plans WHERE id = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("i", $plan_id);
$stmt->execute();
$stmt->bind_result($title, $description, $due_date, $status, $priority, $audio_path);
if (!$stmt->fetch()) {
$errors[] = "Plan not found.";
}
$stmt->close();
} else {
$errors[] = "Database error: Unable to prepare statement.";
}
} else {
// Regular user: Verify ownership
$sql = "SELECT title, description, due_date, status, priority, audio_path FROM workspace_plans WHERE id = ? AND user_id = ?";
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("ii", $plan_id, $user_id);
$stmt->execute();
$stmt->bind_result($title, $description, $due_date, $status, $priority, $audio_path);
if (!$stmt->fetch()) {
$errors[] = "Plan not found or you do not have permission to edit this plan.";
}
$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['description'] ?? '');
$due_date = sanitize_input($_POST['due_date'] ?? '');
$status = sanitize_input($_POST['status'] ?? 'Not Started');
$priority = sanitize_input($_POST['priority'] ?? 'Normal');
// Determine if audio was uploaded via file input or via recording
$use_audio_upload = isset($_FILES['audio_file']) && $_FILES['audio_file']['error'] !== UPLOAD_ERR_NO_FILE;
$use_audio_recording = isset($_POST['audio_data']) && !empty($_POST['audio_data']);
$new_audio_path = null;
// 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 priority
$valid_priorities = ['Normal', 'Important', 'Critical'];
if (!in_array($priority, $valid_priorities)) {
$errors[] = "Invalid priority selected.";
}
// Validate due_date format
if (!strtotime($due_date)) {
$errors[] = "Invalid due date format.";
}
// Handle audio upload if admin opted to upload a file
if ($user_role === 'admin' && $use_audio_upload) {
$allowed_types = ['audio/mpeg', 'audio/wav', 'audio/mp3', 'audio/webm'];
$max_size = 5 * 1024 * 1024; // 5 MB
if ($_FILES['audio_file']['error'] !== UPLOAD_ERR_OK) {
$errors[] = "Error uploading audio file.";
} elseif (!in_array($_FILES['audio_file']['type'], $allowed_types)) {
$errors[] = "Invalid audio file type. Only MP3, WAV, and WEBM are allowed.";
} elseif ($_FILES['audio_file']['size'] > $max_size) {
$errors[] = "Audio file size exceeds the 5MB limit.";
} else {
// Create uploads directory if not exists
$upload_dir = __DIR__ . '/../../uploads/audio_plans/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0755, true);
}
// Generate a unique file name
$file_ext = pathinfo($_FILES['audio_file']['name'], PATHINFO_EXTENSION);
$file_name = uniqid('plan_audio_', true) . '.' . $file_ext;
$destination = $upload_dir . $file_name;
// Move the uploaded file
if (move_uploaded_file($_FILES['audio_file']['tmp_name'], $destination)) {
$new_audio_path = 'uploads/audio_plans/' . $file_name;
// Delete old audio file if exists
if (!empty($audio_path) && file_exists(__DIR__ . '/../../' . $audio_path)) {
unlink(__DIR__ . '/../../' . $audio_path);
}
} else {
$errors[] = "Failed to save the uploaded audio file.";
}
}
}
// Handle audio recording if admin opted to record
if ($user_role === 'admin' && $use_audio_recording && !$use_audio_upload) {
// Decode the base64 audio data
$audio_base64 = $_POST['audio_data'];
$audio_binary = base64_decode(preg_replace('#^data:\w+/\w+;base64,#i', '', $audio_base64));
if ($audio_binary === false) {
$errors[] = "Invalid audio data.";
} else {
// Create uploads directory if not exists
$upload_dir = __DIR__ . '/../../uploads/audio_plans/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0755, true);
}
// Generate a unique file name
$file_ext = 'webm'; // Assuming webm format from MediaRecorder
$file_name = uniqid('plan_audio_', true) . '.' . $file_ext;
$file_path = $upload_dir . $file_name;
// Save the audio file
if (file_put_contents($file_path, $audio_binary)) {
$new_audio_path = 'uploads/audio_plans/' . $file_name;
// Delete old audio file if exists
if (!empty($audio_path) && file_exists(__DIR__ . '/../../' . $audio_path)) {
unlink(__DIR__ . '/../../' . $audio_path);
}
} else {
$errors[] = "Failed to save the recorded audio.";
}
}
}
// Optional: Validate that at least a description or audio is provided
if (empty($description) && empty($new_audio_path) && empty($audio_path)) {
$errors[] = "Either description or audio recording/upload is required.";
}
if ($plan_id > 0) {
if ($user_role === 'admin') {
// Admin can update any plan
// Verify that the plan exists
$sql_check = "SELECT audio_path FROM workspace_plans WHERE id = ?";
if ($stmt_check = $conn->prepare($sql_check)) {
$stmt_check->bind_param("i", $plan_id);
$stmt_check->execute();
$stmt_check->bind_result($current_audio_path);
if ($stmt_check->fetch()) {
$stmt_check->close();
if (empty($errors)) {
// Update the plan
$update_sql = "UPDATE workspace_plans SET title = ?, description = ?, due_date = ?, status = ?, priority = ?, ";
if ($new_audio_path !== null) {
$update_sql .= "audio_path = ?, ";
}
$update_sql .= "updated_at = CURRENT_TIMESTAMP() WHERE id = ?";
// Prepare dynamic query based on whether audio is being updated
if ($new_audio_path !== null) {
$stmt_update = $conn->prepare($update_sql);
$stmt_update->bind_param("ssssssi", $title, $description, $due_date, $status, $priority, $new_audio_path, $plan_id);
} else {
$stmt_update = $conn->prepare($update_sql);
$stmt_update->bind_param("sssssi", $title, $description, $due_date, $status, $priority, $plan_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[] = "Plan not found or you do not have permission to edit this plan.";
$stmt_check->close();
}
} else {
$errors[] = "Database error: Unable to prepare statement.";
}
} else {
// Regular user: Verify ownership
$sql_check = "SELECT audio_path 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->bind_result($current_audio_path);
if ($stmt_check->fetch()) {
$stmt_check->close();
if (empty($errors)) {
// Update the plan
$update_sql = "UPDATE workspace_plans SET title = ?, description = ?, due_date = ?, status = ?, priority = ?, ";
if ($new_audio_path !== null) {
$update_sql .= "audio_path = ?, ";
}
$update_sql .= "updated_at = CURRENT_TIMESTAMP() WHERE id = ? AND user_id = ?";
// Prepare dynamic query based on whether audio is being updated
if ($new_audio_path !== null) {
$stmt_update = $conn->prepare($update_sql);
$stmt_update->bind_param("ssssssii", $title, $description, $due_date, $status, $priority, $new_audio_path, $plan_id, $user_id);
} else {
$stmt_update = $conn->prepare($update_sql);
$stmt_update->bind_param("sssssi", $title, $description, $due_date, $status, $priority, $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[] = "Plan not found or you do not have permission to edit this plan.";
$stmt_check->close();
}
} else {
$errors[] = "Database error: Unable to prepare statement.";
}
}
} else {
$errors[] = "Invalid plan ID.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Plan - Workspace</title>
<!-- Tailwind CSS -->
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
<!-- Bootstrap Icons -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
<!-- Custom Styles -->
<style>
/* Custom styles for audio recorder */
#audio_recorder_section {
display: none;
}
.hidden {
display: none;
}
/* Priority Badge Styles */
.priority-normal {
background-color: #3B82F6; /* Blue */
}
.priority-important {
background-color: #F59E0B; /* Yellow */
}
.priority-critical {
background-color: #EF4444; /* Red */
}
/* Status Badge Styles */
.status-completed {
background-color: #10B981; /* Green */
}
.status-in-progress {
background-color: #FBBF24; /* Amber */
}
.status-pending {
background-color: #EF4444; /* Red */
}
</style>
</head>
<body class="bg-gray-100 min-h-screen flex flex-col">
<!-- Header -->
<?php include __DIR__ . '/../../includes/header.php'; ?>
<!-- Main Content -->
<main class="container mx-auto p-6 mt-24 flex-grow">
<h1 class="text-2xl font-bold mb-6">Edit Plan</h1>
<!-- Display Errors -->
<?php if(!empty($errors)): ?>
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
<ul>
<?php foreach($errors as $error): ?>
<li><?= htmlspecialchars($error) ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<!-- Plan Edit Form -->
<?php if(empty($errors) || $_SERVER['REQUEST_METHOD'] === 'POST'): ?>
<form action="edit_plan.php?id=<?= htmlspecialchars($plan_id) ?>" method="POST" enctype="multipart/form-data" class="bg-white p-6 rounded shadow-md">
<div class="mb-4">
<label class="block text-gray-700">Title<span class="text-red-500">*</span></label>
<input type="text" name="title" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300" required value="<?= htmlspecialchars($title) ?>">
</div>
<div class="mb-4">
<label class="block text-gray-700">Description</label>
<textarea name="description" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300" rows="4"><?= htmlspecialchars($description) ?></textarea>
</div>
<?php if ($user_role === 'admin'): ?>
<div class="mb-4">
<label class="block text-gray-700">Audio Option</label>
<div class="flex items-center space-x-4 mt-2">
<div class="flex items-center">
<input type="radio" id="audio_option_none" name="audio_option" value="none" <?= empty($audio_path) ? 'checked' : '' ?> class="form-radio h-4 w-4 text-blue-600" onchange="toggleAudioOptions('none')">
<label for="audio_option_none" class="ml-2 text-gray-700">None</label>
</div>
<div class="flex items-center">
<input type="radio" id="audio_option_upload" name="audio_option" value="upload" <?= !empty($audio_path) ? 'checked' : '' ?> class="form-radio h-4 w-4 text-blue-600" onchange="toggleAudioOptions('upload')">
<label for="audio_option_upload" class="ml-2 text-gray-700">Upload Audio File</label>
</div>
<div class="flex items-center">
<input type="radio" id="audio_option_record" name="audio_option" value="record" <?= !empty($audio_path) ? '' : '' ?> class="form-radio h-4 w-4 text-blue-600" onchange="toggleAudioOptions('record')">
<label for="audio_option_record" class="ml-2 text-gray-700">Record Audio</label>
</div>
</div>
</div>
<!-- Audio Upload Section -->
<div class="mb-4 hidden" id="audio_upload_section">
<label class="block text-gray-700">Upload Audio File</label>
<input type="file" name="audio_file" accept="audio/*" class="w-full mt-2 px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300">
<small class="text-gray-500">Accepted formats: MP3, WAV, WEBM. Max size: 5MB.</small>
<?php if (!empty($audio_path)): ?>
<div class="mt-2">
<p class="text-gray-700">Current Audio:</p>
<audio controls class="w-full mt-1">
<source src="/<?= htmlspecialchars($audio_path) ?>" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>
<?php endif; ?>
</div>
<!-- Audio Recorder Section -->
<div class="mb-4 hidden" id="audio_recorder_section">
<label class="block text-gray-700">Record Audio</label>
<div class="flex space-x-2 mt-2">
<button type="button" id="start_recording" class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 flex items-center">
<i class="bi bi-play-fill mr-2"></i> Start Recording
</button>
<button type="button" id="stop_recording" class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 flex items-center hidden">
<i class="bi bi-stop-fill mr-2"></i> Stop Recording
</button>
</div>
<div id="recording_indicator" class="text-red-500 mt-2 hidden">Recording...</div>
<audio id="recorded_audio" class="mt-4 w-full" controls></audio>
<input type="hidden" name="audio_data" id="audio_data" value="<?= htmlspecialchars($_POST['audio_data'] ?? '') ?>">
<?php if (!empty($audio_path)): ?>
<div class="mt-2">
<p class="text-gray-700">Current Audio:</p>
<audio controls class="w-full mt-1">
<source src="/<?= htmlspecialchars($audio_path) ?>" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>
<?php endif; ?>
</div>
<?php endif; ?>
<div class="mb-4">
<label class="block text-gray-700">Due Date<span class="text-red-500">*</span></label>
<input type="datetime-local" name="due_date" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300" required value="<?= htmlspecialchars($due_date) ?>">
</div>
<div class="mb-4">
<label class="block text-gray-700">Status</label>
<select name="status" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300">
<option value="Not Started" <?= ($status === 'Not Started') ? 'selected' : '' ?>>Not Started</option>
<option value="In Progress" <?= ($status === 'In Progress') ? 'selected' : '' ?>>In Progress</option>
<option value="Completed" <?= ($status === 'Completed') ? 'selected' : '' ?>>Completed</option>
</select>
</div>
<!-- Priority Field -->
<div class="mb-4">
<label class="block text-gray-700">Priority</label>
<select name="priority" class="w-full px-3 py-2 border rounded focus:outline-none focus:ring focus:border-blue-300">
<option value="Normal" <?= ($priority === 'Normal') ? 'selected' : '' ?>>Normal</option>
<option value="Important" <?= ($priority === 'Important') ? 'selected' : '' ?>>Important</option>
<option value="Critical" <?= ($priority === 'Critical') ? 'selected' : '' ?>>Critical</option>
</select>
</div>
<div class="flex justify-between">
<a href="view_plan.php?id=<?= htmlspecialchars($plan_id) ?>" class="px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600">Cancel</a>
<button type="submit" class="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600">Update Plan</button>
</div>
</form>
<?php endif; ?>
</main>
<!-- Footer -->
<footer class="bg-gray-800 text-white text-center p-4">
© 2024 Kaak Alia Bakery. All rights reserved.
</footer>
<!-- JavaScript for Audio Recording and Enhanced UI -->
<?php if ($user_role === 'admin'): ?>
<script>
/**
* Toggle visibility of audio options based on selected radio button.
* @param {string} option - The selected audio option ('none', 'upload', 'record').
*/
function toggleAudioOptions(option) {
document.getElementById('audio_upload_section').style.display = (option === 'upload') ? 'block' : 'none';
document.getElementById('audio_recorder_section').style.display = (option === 'record') ? 'block' : 'none';
// Clear audio data if switching options
if (option !== 'record') {
document.getElementById('audio_data').value = '';
document.getElementById('recorded_audio').src = '';
}
if (option !== 'upload') {
document.querySelector('input[name="audio_file"]').value = '';
}
}
// Initialize media recorder variables
let mediaRecorder;
let recordedChunks = [];
const startButton = document.getElementById('start_recording');
const stopButton = document.getElementById('stop_recording');
const recordingIndicator = document.getElementById('recording_indicator');
const recordedAudio = document.getElementById('recorded_audio');
const audioDataInput = document.getElementById('audio_data');
// Check for MediaRecorder API support
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
if (startButton && stopButton) {
startButton.addEventListener('click', startRecording);
stopButton.addEventListener('click', stopRecording);
}
} else {
alert('Your browser does not support audio recording.');
if (startButton) startButton.disabled = true;
if (stopButton) stopButton.disabled = true;
}
/**
* Start recording audio using MediaRecorder API.
*/
function startRecording() {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(stream => {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
recordingIndicator.classList.remove('hidden');
startButton.classList.add('hidden');
stopButton.classList.remove('hidden');
mediaRecorder.ondataavailable = function(e) {
recordedChunks.push(e.data);
};
mediaRecorder.onstop = function() {
const blob = new Blob(recordedChunks, { type: 'audio/webm' });
recordedChunks = [];
// Create a URL for the recorded audio and set it to the audio element
const audioURL = URL.createObjectURL(blob);
recordedAudio.src = audioURL;
// Convert the blob to base64 and set it to the hidden input
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function() {
const base64data = reader.result;
audioDataInput.value = base64data;
};
recordingIndicator.classList.add('hidden');
startButton.classList.remove('hidden');
stopButton.classList.add('hidden');
};
})
.catch(err => {
console.error('The following error occurred:', err);
alert('Could not access the microphone. Please check your permissions.');
});
}
/**
* Stop recording audio.
*/
function stopRecording() {
if (mediaRecorder && mediaRecorder.state !== 'inactive') {
mediaRecorder.stop();
mediaRecorder.stream.getTracks().forEach(track => track.stop());
}
}
// Maintain the audio options state on form submission errors
window.onload = function() {
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($user_role === 'admin') {
if ($use_audio_upload) {
echo "toggleAudioOptions('upload');";
} elseif ($use_audio_recording) {
echo "toggleAudioOptions('record');";
} else {
echo "toggleAudioOptions('none');";
}
}
} else {
// On initial load, set the audio option based on existing audio_path
if ($user_role === 'admin') {
if (!empty($audio_path)) {
echo "toggleAudioOptions('upload');";
} else {
echo "toggleAudioOptions('none');";
}
}
}
?>
}
</script>
<?php endif; ?>
</body>
</html>
<?php
// Flush the output buffer
ob_end_flush();
?>
Explanation of Key Sections:
-
Fetching Existing Plan Data:
- On a
GET request, the script retrieves the existing plan details, including audio_path and priority, to pre-fill the form fields.
-
Handling Form Submission (POST Request):
- Sanitization: All input fields are sanitized to prevent security vulnerabilities.
- Validation: Ensures that required fields are filled and that inputs like
status and priority are valid.
- Audio Processing:
- Upload: If an audio file is uploaded, it validates the file type and size, saves it to the server, and updates the
audio_path. If a new audio is uploaded, it deletes the old audio file to prevent orphaned files.
- Recording: If audio is recorded via the form, it decodes the base64 data, saves it as a
.webm file, and updates the audio_path. Similarly, it removes any existing audio file if replaced.
- Database Update: The script dynamically constructs the SQL
UPDATE statement based on whether the audio is being updated. It ensures that only administrators can update any plan, while regular users can only update their own plans.
-
Form Structure:
- Audio Options: Administrators can choose between
None, Upload Audio File, or Record Audio. Depending on the selection, the corresponding section is displayed.
- Priority Field: Added a dropdown to select the plan's priority level.
- Existing Audio Display: If a plan already has an associated audio file, it is displayed with an audio player, allowing users to listen to it.
-
JavaScript Functionality:
- Toggle Audio Options: Shows or hides the upload and recorder sections based on the selected audio option.
- Audio Recording: Utilizes the
MediaRecorder API to record audio, which is then converted to Base64 and stored in a hidden input for submission.
- State Preservation: Ensures that the selected audio option remains consistent even if form submission results in validation errors.
-
:
Additional Notes:
-
Audio File Management: It's crucial to manage uploaded audio files appropriately to prevent storage bloat. This script ensures that old audio files are deleted when they are replaced by new uploads or recordings.
-
Browser Compatibility: The audio recording feature relies on the MediaRecorder API. Ensure that users are informed if their browsers do not support this feature.
-
Error Handling: Comprehensive error messages guide users in case of invalid inputs or system issues.
-
Security: Always ensure that uploaded files are stored in directories that are not directly accessible via the web or implement proper measures to prevent unauthorized access.
By integrating these enhancements, the edit_plan.php script now offers a robust and user-friendly interface for managing workspace plans, complete with audio capabilities and priority settings.