📁 File Manager
Editing:
/home/wvl7mof7402e/public_html/chem/admin/media.php
<?php /** * Pure Chemical Admin * media.php * * Existing table: * media * * No new tables are created. */ if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); } require_once __DIR__ . '/includes/db.php'; if (file_exists(__DIR__ . '/includes/auth.php')) { require_once __DIR__ . '/includes/auth.php'; } if (function_exists('requireAdmin')) { requireAdmin(); } /* ========================================================= HELPERS ========================================================= */ if (!function_exists('e')) { function e($value) { return htmlspecialchars( (string)$value, ENT_QUOTES, 'UTF-8' ); } } if (!function_exists('csrf_token')) { function csrf_token() { if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex( random_bytes(32) ); } return $_SESSION['csrf_token']; } } if (!function_exists('csrf_field')) { function csrf_field() { return '<input type="hidden" name="csrf_token" value="' . e(csrf_token()) . '">'; } } function verify_csrf() { $token = isset($_POST['csrf_token']) ? (string)$_POST['csrf_token'] : ''; if ( empty($_SESSION['csrf_token']) || $token === '' || !hash_equals( $_SESSION['csrf_token'], $token ) ) { return false; } return true; } function media_flash($type, $message) { $_SESSION['media_flash'] = [ 'type' => $type, 'message' => $message ]; } function get_media_flash() { if (empty($_SESSION['media_flash'])) { return null; } $flash = $_SESSION['media_flash']; unset($_SESSION['media_flash']); return $flash; } function format_file_size($bytes) { $bytes = (float)$bytes; if ($bytes <= 0) { return '0 B'; } $units = [ 'B', 'KB', 'MB', 'GB', 'TB' ]; $power = floor( log($bytes, 1024) ); $power = min( $power, count($units) - 1 ); return number_format( $bytes / pow(1024, $power), $power === 0 ? 0 : 2 ) . ' ' . $units[$power]; } function get_media_icon($fileType, $mimeType = '') { $fileType = strtolower( (string)$fileType ); $mimeType = strtolower( (string)$mimeType ); if ($fileType === 'image') { return 'fa-image'; } if ($fileType === 'video') { return 'fa-video'; } if ($fileType === 'audio') { return 'fa-music'; } if ($fileType === 'pdf') { return 'fa-file-pdf'; } if ( strpos($mimeType, 'word') !== false || strpos($mimeType, 'document') !== false ) { return 'fa-file-word'; } if ( strpos($mimeType, 'excel') !== false || strpos($mimeType, 'spreadsheet') !== false ) { return 'fa-file-excel'; } if ( strpos($mimeType, 'zip') !== false || strpos($mimeType, 'compressed') !== false ) { return 'fa-file-zipper'; } return 'fa-file'; } function get_media_color_class($fileType) { switch (strtolower((string)$fileType)) { case 'image': return 'media-image'; case 'video': return 'media-video'; case 'audio': return 'media-audio'; case 'pdf': return 'media-pdf'; case 'document': return 'media-document'; default: return 'media-other'; } } function detect_file_type($mime, $extension) { $mime = strtolower( (string)$mime ); $extension = strtolower( (string)$extension ); if (strpos($mime, 'image/') === 0) { return 'image'; } if (strpos($mime, 'video/') === 0) { return 'video'; } if (strpos($mime, 'audio/') === 0) { return 'audio'; } if ($mime === 'application/pdf') { return 'pdf'; } $documentMimes = [ 'application/msword', 'application/vnd.ms-word', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'text/plain', 'text/csv', 'application/rtf' ]; if (in_array($mime, $documentMimes, true)) { return 'document'; } $documentExtensions = [ 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv', 'rtf' ]; if ( in_array( $extension, $documentExtensions, true ) ) { return 'document'; } return 'other'; } function safe_filename($filename) { $filename = basename( (string)$filename ); $extension = pathinfo( $filename, PATHINFO_EXTENSION ); $name = pathinfo( $filename, PATHINFO_FILENAME ); $name = preg_replace( '/[^A-Za-z0-9_-]+/', '-', $name ); $name = trim( $name, '-_' ); if ($name === '') { $name = 'file'; } $extension = preg_replace( '/[^A-Za-z0-9]+/', '', $extension ); return $name . ($extension !== '' ? '.' . strtolower($extension) : ''); } function generate_unique_filename($originalName) { $safe = safe_filename( $originalName ); $extension = pathinfo( $safe, PATHINFO_EXTENSION ); $name = pathinfo( $safe, PATHINFO_FILENAME ); $random = bin2hex( random_bytes(6) ); return $name . '-' . date('YmdHis') . '-' . $random . ($extension !== '' ? '.' . $extension : ''); } function media_public_path($path) { $path = trim( (string)$path ); if ($path === '') { return ''; } /* * Stored file_path is expected to be * something like: * * uploads/media/file.jpg */ if ( preg_match( '#^(https?:)?//#i', $path ) ) { return $path; } return '../' . ltrim( $path, '/' ); } function media_filesystem_path($storedPath) { $storedPath = trim( (string)$storedPath ); if ($storedPath === '') { return ''; } $storedPath = str_replace( ['/', '\\'], DIRECTORY_SEPARATOR, $storedPath ); $projectRoot = realpath( __DIR__ . DIRECTORY_SEPARATOR . '..' ); if (!$projectRoot) { return ''; } $storedPath = ltrim( $storedPath, DIRECTORY_SEPARATOR ); return $projectRoot . DIRECTORY_SEPARATOR . $storedPath; } /** * Return a session user ID only when that ID really exists in users.id. * This prevents the media.uploaded_by foreign-key error when an old or * differently named session variable contains a non-existent user ID. * If no valid user is found, NULL is stored (the column allows NULL). */ function get_current_admin_user_id(PDO $pdo) { $possibleKeys = [ 'USER_ID', 'user_id', 'ADMIN_ID', 'admin_id', 'admin_user_id', 'logged_in_user_id' ]; foreach ($possibleKeys as $key) { if (!isset($_SESSION[$key]) || !is_scalar($_SESSION[$key])) { continue; } $rawId = trim((string)$_SESSION[$key]); if ($rawId === '' || !ctype_digit($rawId) || (int)$rawId < 1) { continue; } $userId = (int)$rawId; try { $check = $pdo->prepare('SELECT id FROM users WHERE id = :id LIMIT 1'); $check->execute([':id' => $userId]); $existingId = $check->fetchColumn(); if ($existingId !== false) { return (int)$existingId; } } catch (Throwable $e) { // If the lookup fails, use NULL rather than risking a foreign-key failure. return null; } } return null; } /* ========================================================= CONFIG ========================================================= */ $maxUploadSize = 50 * 1024 * 1024; /* * Keep extensions reasonably safe. */ $allowedExtensions = [ 'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'avif', 'mp4', 'webm', 'mov', 'avi', 'mp3', 'wav', 'ogg', 'm4a', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv', 'rtf', 'zip' ]; /* * Upload directory. * * Database stores: * uploads/media/filename.ext */ $uploadRelativeDir = 'uploads/media'; $projectRoot = realpath( __DIR__ . DIRECTORY_SEPARATOR . '..' ); $uploadAbsoluteDir = $projectRoot ? $projectRoot . DIRECTORY_SEPARATOR . str_replace( '/', DIRECTORY_SEPARATOR, $uploadRelativeDir ) : ''; /* ========================================================= POST ACTIONS ========================================================= */ if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (!verify_csrf()) { media_flash( 'error', 'Security token expired. Please try again.' ); header( 'Location: media.php' ); exit; } $action = isset($_POST['action']) ? trim((string)$_POST['action']) : ''; try { /* ================================================= UPLOAD ================================================= */ if ($action === 'upload') { if ( !isset($_FILES['media_files']) || !is_array($_FILES['media_files']['name']) ) { throw new Exception( 'Please select at least one file.' ); } if ( $uploadAbsoluteDir === '' ) { throw new Exception( 'Upload directory could not be resolved.' ); } if ( !is_dir($uploadAbsoluteDir) && !mkdir( $uploadAbsoluteDir, 0755, true ) ) { throw new Exception( 'Unable to create media upload directory.' ); } $folderId = null; if ( isset($_POST['folder_id']) && trim((string)$_POST['folder_id']) !== '' ) { $folderValue = (int)$_POST['folder_id']; if ($folderValue > 0) { $folderId = $folderValue; } } $altText = isset($_POST['alt_text']) ? trim((string)$_POST['alt_text']) : ''; $title = isset($_POST['title']) ? trim((string)$_POST['title']) : ''; $caption = isset($_POST['caption']) ? trim((string)$_POST['caption']) : ''; $uploadedBy = get_current_admin_user_id($pdo); $uploadedCount = 0; $errors = []; $fileCount = count( $_FILES['media_files']['name'] ); for ( $i = 0; $i < $fileCount; $i++ ) { $originalName = $_FILES['media_files']['name'][$i] ?? ''; $tmpName = $_FILES['media_files']['tmp_name'][$i] ?? ''; $errorCode = $_FILES['media_files']['error'][$i] ?? UPLOAD_ERR_NO_FILE; $fileSize = isset($_FILES['media_files']['size'][$i]) ? (int)$_FILES['media_files']['size'][$i] : 0; if ( $errorCode === UPLOAD_ERR_NO_FILE ) { continue; } if ( $errorCode !== UPLOAD_ERR_OK ) { $errors[] = $originalName . ': Upload failed.'; continue; } if ( !is_uploaded_file($tmpName) ) { $errors[] = $originalName . ': Invalid uploaded file.'; continue; } if ( $fileSize <= 0 ) { $errors[] = $originalName . ': Empty file is not allowed.'; continue; } if ( $fileSize > $maxUploadSize ) { $errors[] = $originalName . ': Maximum allowed size is 50 MB.'; continue; } $extension = strtolower( pathinfo( $originalName, PATHINFO_EXTENSION ) ); if ( $extension === '' || !in_array( $extension, $allowedExtensions, true ) ) { $errors[] = $originalName . ': File type is not allowed.'; continue; } $mimeType = 'application/octet-stream'; if ( function_exists('finfo_open') ) { $finfo = finfo_open( FILEINFO_MIME_TYPE ); if ($finfo) { $detectedMime = finfo_file( $finfo, $tmpName ); if ($detectedMime) { $mimeType = $detectedMime; } finfo_close( $finfo ); } } elseif ( function_exists('mime_content_type') ) { $detectedMime = mime_content_type( $tmpName ); if ($detectedMime) { $mimeType = $detectedMime; } } $fileType = detect_file_type( $mimeType, $extension ); $storedFileName = generate_unique_filename( $originalName ); $absoluteFile = $uploadAbsoluteDir . DIRECTORY_SEPARATOR . $storedFileName; if ( !move_uploaded_file( $tmpName, $absoluteFile ) ) { $errors[] = $originalName . ': Could not move uploaded file.'; continue; } $relativeFilePath = $uploadRelativeDir . '/' . $storedFileName; $width = null; $height = null; $duration = null; /* * Image dimensions */ if ( $fileType === 'image' ) { $imageInfo = @getimagesize( $absoluteFile ); if ( is_array($imageInfo) ) { $width = isset($imageInfo[0]) ? (int)$imageInfo[0] : null; $height = isset($imageInfo[1]) ? (int)$imageInfo[1] : null; } } /* * For uploaded media where FFmpeg * is not available, duration is kept NULL. */ $insertStmt = $pdo->prepare(" INSERT INTO media ( folder_id, original_name, file_name, file_path, mime_type, file_type, extension, file_size, width, height, duration, alt_text, title, caption, thumbnail_path, uploaded_by, status ) VALUES ( :folder_id, :original_name, :file_name, :file_path, :mime_type, :file_type, :extension, :file_size, :width, :height, :duration, :alt_text, :title, :caption, :thumbnail_path, :uploaded_by, 1 ) "); $insertStmt->execute([ ':folder_id' => $folderId, ':original_name' => $originalName, ':file_name' => $storedFileName, ':file_path' => $relativeFilePath, ':mime_type' => $mimeType, ':file_type' => $fileType, ':extension' => $extension, ':file_size' => $fileSize, ':width' => $width, ':height' => $height, ':duration' => $duration, ':alt_text' => $altText !== '' ? $altText : null, ':title' => $title !== '' ? $title : null, ':caption' => $caption !== '' ? $caption : null, ':thumbnail_path' => null, ':uploaded_by' => $uploadedBy ]); $uploadedCount++; } if ($uploadedCount > 0) { $message = $uploadedCount === 1 ? '1 media file uploaded successfully.' : $uploadedCount . ' media files uploaded successfully.'; if (!empty($errors)) { $message .= ' Some files were skipped.'; } media_flash( 'success', $message ); } else { media_flash( 'error', !empty($errors) ? implode( ' ', $errors ) : 'No file was uploaded.' ); } header( 'Location: media.php' ); exit; } /* ================================================= UPDATE META ================================================= */ if ($action === 'update') { $id = isset($_POST['id']) ? (int)$_POST['id'] : 0; if ($id <= 0) { throw new Exception( 'Invalid media ID.' ); } $folderId = null; if ( isset($_POST['folder_id']) && trim((string)$_POST['folder_id']) !== '' ) { $folderValue = (int)$_POST['folder_id']; if ($folderValue > 0) { $folderId = $folderValue; } } $altText = isset($_POST['alt_text']) ? trim((string)$_POST['alt_text']) : ''; $title = isset($_POST['title']) ? trim((string)$_POST['title']) : ''; $caption = isset($_POST['caption']) ? trim((string)$_POST['caption']) : ''; $stmt = $pdo->prepare(" UPDATE media SET folder_id = :folder_id, alt_text = :alt_text, title = :title, caption = :caption WHERE id = :id LIMIT 1 "); $stmt->execute([ ':folder_id' => $folderId, ':alt_text' => $altText !== '' ? $altText : null, ':title' => $title !== '' ? $title : null, ':caption' => $caption !== '' ? $caption : null, ':id' => $id ]); media_flash( 'success', 'Media details updated successfully.' ); header( 'Location: media.php' ); exit; } /* ================================================= TOGGLE STATUS ================================================= */ if ($action === 'toggle_status') { $id = isset($_POST['id']) ? (int)$_POST['id'] : 0; if ($id <= 0) { throw new Exception( 'Invalid media ID.' ); } $stmt = $pdo->prepare(" SELECT status FROM media WHERE id = :id LIMIT 1 "); $stmt->execute([ ':id' => $id ]); $currentStatus = $stmt->fetchColumn(); if ($currentStatus === false) { throw new Exception( 'Media record not found.' ); } $newStatus = ((int)$currentStatus === 1) ? 0 : 1; $updateStmt = $pdo->prepare(" UPDATE media SET status = :status WHERE id = :id LIMIT 1 "); $updateStmt->execute([ ':status' => $newStatus, ':id' => $id ]); media_flash( 'success', $newStatus === 1 ? 'Media activated.' : 'Media disabled.' ); header( 'Location: media.php' ); exit; } /* ================================================= DELETE ================================================= */ if ($action === 'delete') { $id = isset($_POST['id']) ? (int)$_POST['id'] : 0; if ($id <= 0) { throw new Exception( 'Invalid media ID.' ); } $stmt = $pdo->prepare(" SELECT file_path, thumbnail_path FROM media WHERE id = :id LIMIT 1 "); $stmt->execute([ ':id' => $id ]); $media = $stmt->fetch(); if (!$media) { throw new Exception( 'Media record not found.' ); } /* * Delete database record first. */ $deleteStmt = $pdo->prepare(" DELETE FROM media WHERE id = :id LIMIT 1 "); $deleteStmt->execute([ ':id' => $id ]); /* * Remove physical file if it belongs * to our local project path. */ if ( !empty($media['file_path']) && !preg_match( '#^(https?:)?//#i', $media['file_path'] ) ) { $physicalPath = media_filesystem_path( $media['file_path'] ); if ( $physicalPath !== '' && is_file($physicalPath) ) { @unlink( $physicalPath ); } } /* * Remove thumbnail if separate. */ if ( !empty($media['thumbnail_path']) && !preg_match( '#^(https?:)?//#i', $media['thumbnail_path'] ) ) { $thumbnailPhysicalPath = media_filesystem_path( $media['thumbnail_path'] ); if ( $thumbnailPhysicalPath !== '' && is_file( $thumbnailPhysicalPath ) ) { @unlink( $thumbnailPhysicalPath ); } } media_flash( 'success', 'Media deleted successfully.' ); header( 'Location: media.php' ); exit; } } catch (Throwable $e) { media_flash( 'error', $e->getMessage() ); header( 'Location: media.php' ); exit; } } /* ========================================================= FILTERS ========================================================= */ $search = isset($_GET['search']) ? trim((string)$_GET['search']) : ''; $typeFilter = isset($_GET['file_type']) ? trim((string)$_GET['file_type']) : ''; $statusFilter = isset($_GET['status']) ? trim((string)$_GET['status']) : ''; $where = []; $params = []; if ($search !== '') { $where[] = " ( m.original_name LIKE :search OR m.file_name LIKE :search OR m.alt_text LIKE :search OR m.title LIKE :search OR m.caption LIKE :search OR m.mime_type LIKE :search ) "; $params[':search'] = '%' . $search . '%'; } $allowedTypes = [ 'image', 'video', 'audio', 'pdf', 'document', 'other' ]; if ( $typeFilter !== '' && in_array( $typeFilter, $allowedTypes, true ) ) { $where[] = 'm.file_type = :file_type'; $params[':file_type'] = $typeFilter; } if ( $statusFilter !== '' && in_array( $statusFilter, ['0', '1'], true ) ) { $where[] = 'm.status = :status'; $params[':status'] = (int)$statusFilter; } $whereSql = ''; if (!empty($where)) { $whereSql = 'WHERE ' . implode( ' AND ', $where ); } /* ========================================================= STATS ========================================================= */ $statsStmt = $pdo->query(" SELECT COUNT(*) AS total, SUM( CASE WHEN status = 1 THEN 1 ELSE 0 END ) AS active, SUM( CASE WHEN status = 0 THEN 1 ELSE 0 END ) AS inactive, SUM( CASE WHEN file_type = 'image' THEN 1 ELSE 0 END ) AS images, SUM( CASE WHEN file_type IN ('video', 'audio') THEN 1 ELSE 0 END ) AS media_files, SUM(file_size) AS total_size FROM media "); $stats = $statsStmt->fetch(); $totalMedia = (int)($stats['total'] ?? 0); $activeMedia = (int)($stats['active'] ?? 0); $inactiveMedia = (int)($stats['inactive'] ?? 0); $totalImages = (int)($stats['images'] ?? 0); $totalVideoAudio = (int)($stats['media_files'] ?? 0); $totalStorage = (int)($stats['total_size'] ?? 0); /* ========================================================= RECENT ========================================================= */ $recentStmt = $pdo->query(" SELECT COUNT(*) FROM media WHERE created_at >= DATE_SUB( NOW(), INTERVAL 30 DAY ) "); $recentMedia = (int)$recentStmt->fetchColumn(); /* ========================================================= MEDIA LIST ========================================================= */ $listStmt = $pdo->prepare(" SELECT m.id, m.folder_id, m.original_name, m.file_name, m.file_path, m.mime_type, m.file_type, m.extension, m.file_size, m.width, m.height, m.duration, m.alt_text, m.title, m.caption, m.thumbnail_path, m.uploaded_by, m.status, m.created_at, m.updated_at FROM media m {$whereSql} ORDER BY m.id DESC "); $listStmt->execute( $params ); $mediaItems = $listStmt->fetchAll(); $flash = get_media_flash(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" > <title> Media Library | Pure Chemical Admin </title> <meta name="description" content="Pure Chemical media library" > <link rel="preconnect" href="https://fonts.googleapis.com" > <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin > <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet" > <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" > <style> :root { --primary: #0f766e; --primary-dark: #115e59; --primary-soft: #ecfdf5; --text: #0f172a; --muted: #64748b; --muted-light: #94a3b8; --border: #e2e8f0; --surface: #ffffff; --surface-soft: #f8fafc; --success: #15803d; --success-bg: #f0fdf4; --danger: #dc2626; --danger-bg: #fef2f2; --warning: #d97706; --warning-bg: #fffbeb; --blue: #2563eb; --blue-bg: #eff6ff; --purple: #7c3aed; --purple-bg: #f5f3ff; --pink: #db2777; --pink-bg: #fdf2f8; --shadow-sm: 0 1px 2px rgba(15, 23, 42, .04); --shadow-md: 0 10px 30px rgba(15, 23, 42, .07); --shadow-lg: 0 25px 60px rgba(15, 23, 42, .16); --radius: 18px; } * { box-sizing: border-box; } html { scroll-behavior: smooth; } body { margin: 0; background: linear-gradient( 180deg, #f8fafc 0%, #f1f5f9 100% ); color: var(--text); font-family: "Inter", sans-serif; font-size: 14px; line-height: 1.5; } button, input, select, textarea { font: inherit; } a { text-decoration: none; color: inherit; } /* ================================================= LAYOUT ================================================= */ .page-shell { margin-left: 280px; min-height: 100vh; } .page-container { width: min( 1500px, calc(100% - 44px) ); margin: 0 auto; padding: 28px 0 60px; } /* ================================================= TOPBAR ================================================= */ .topbar { position: sticky; top: 0; z-index: 50; height: 76px; display: flex; align-items: center; justify-content: space-between; padding: 0 30px; background: rgba( 255, 255, 255, .88 ); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px); border-bottom: 1px solid rgba( 226, 232, 240, .85 ); } .topbar-left { display: flex; align-items: center; gap: 14px; } .topbar-icon { width: 42px; height: 42px; display: flex; align-items: center; justify-content: center; border-radius: 13px; color: var(--primary); background: var(--primary-soft); } .topbar-title { margin: 0; font-size: 17px; font-weight: 800; letter-spacing: -.02em; } .topbar-subtitle { margin: 2px 0 0; color: var(--muted); font-size: 12px; } .topbar-pill { display: inline-flex; align-items: center; gap: 8px; padding: 9px 13px; border: 1px solid var(--border); border-radius: 999px; background: #fff; color: var(--muted); font-size: 12px; font-weight: 600; } .topbar-pill i { color: var(--primary); } /* ================================================= PAGE HEADER ================================================= */ .page-header { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; margin-bottom: 24px; } .page-heading h1 { margin: 0; font-size: clamp( 25px, 3vw, 34px ); line-height: 1.15; letter-spacing: -.035em; font-weight: 800; } .page-heading p { margin: 8px 0 0; color: var(--muted); max-width: 760px; } /* ================================================= BUTTONS ================================================= */ .btn-primary { display: inline-flex; align-items: center; justify-content: center; gap: 9px; min-height: 44px; padding: 0 17px; border: 0; border-radius: 12px; color: #fff; background: linear-gradient( 135deg, var(--primary), var(--primary-dark) ); box-shadow: 0 8px 18px rgba( 15, 118, 110, .20 ); font-size: 13px; font-weight: 700; cursor: pointer; transition: transform .2s ease, box-shadow .2s ease; } .btn-primary:hover { transform: translateY(-1px); box-shadow: 0 12px 24px rgba( 15, 118, 110, .26 ); } .btn-light { min-height: 44px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; padding: 0 14px; border: 1px solid var(--border); border-radius: 11px; background: #fff; color: #475569; font-size: 12px; font-weight: 700; cursor: pointer; } .btn-light:hover { background: var(--surface-soft); } .btn-secondary { min-height: 42px; padding: 0 15px; border: 1px solid var(--border); border-radius: 11px; background: #fff; color: #475569; font-size: 12px; font-weight: 700; cursor: pointer; } /* ================================================= STATS ================================================= */ .stats-grid { display: grid; grid-template-columns: repeat( 5, minmax(0, 1fr) ); gap: 15px; margin-bottom: 22px; } .stat-card { position: relative; overflow: hidden; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 19px; box-shadow: var(--shadow-sm); } .stat-card::after { content: ""; position: absolute; width: 90px; height: 90px; right: -35px; bottom: -40px; border-radius: 50%; background: var(--primary-soft); } .stat-icon { width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; border-radius: 12px; background: var(--primary-soft); color: var(--primary); } .stat-value { margin-top: 15px; font-size: 25px; line-height: 1; font-weight: 800; letter-spacing: -.03em; } .stat-label { margin-top: 7px; color: var(--muted); font-size: 12px; font-weight: 600; } /* ================================================= FLASH ================================================= */ .flash { display: flex; align-items: center; gap: 11px; margin-bottom: 18px; padding: 14px 16px; border-radius: 14px; font-weight: 600; font-size: 13px; } .flash.success { color: var(--success); background: var(--success-bg); border: 1px solid #bbf7d0; } .flash.error { color: var(--danger); background: var(--danger-bg); border: 1px solid #fecaca; } /* ================================================= MEDIA CARD ================================================= */ .content-card { background: var(--surface); border: 1px solid var(--border); border-radius: 22px; box-shadow: var(--shadow-md); overflow: hidden; } .card-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 18px 20px; border-bottom: 1px solid var(--border); } .toolbar-left { display: flex; align-items: center; gap: 10px; flex: 1; } .search-box { position: relative; width: min( 430px, 100% ); } .search-box i { position: absolute; left: 14px; top: 50%; transform: translateY(-50%); color: var(--muted-light); } .form-control, .form-select { width: 100%; min-height: 44px; padding: 0 13px; border: 1px solid var(--border); border-radius: 11px; background: #fff; color: var(--text); outline: none; transition: border-color .2s ease, box-shadow .2s ease; } .search-box .form-control { padding-left: 41px; } .form-control:focus, .form-select:focus, textarea.form-control:focus { border-color: rgba( 15, 118, 110, .55 ); box-shadow: 0 0 0 4px rgba( 15, 118, 110, .09 ); } textarea.form-control { min-height: 100px; padding: 12px 13px; resize: vertical; } .filter-select { min-width: 140px; } /* ================================================= MEDIA GRID ================================================= */ .media-grid { display: grid; grid-template-columns: repeat( 4, minmax(0, 1fr) ); gap: 18px; padding: 20px; } .media-card { overflow: hidden; background: #fff; border: 1px solid var(--border); border-radius: 17px; box-shadow: var(--shadow-sm); transition: transform .2s ease, box-shadow .2s ease, border-color .2s ease; } .media-card:hover { transform: translateY(-3px); box-shadow: var(--shadow-md); border-color: #cbd5e1; } .media-preview { position: relative; height: 190px; overflow: hidden; display: flex; align-items: center; justify-content: center; background: linear-gradient( 145deg, #f8fafc, #eef2f7 ); } .media-preview img { width: 100%; height: 100%; object-fit: cover; display: block; } .media-file-icon { width: 74px; height: 74px; display: flex; align-items: center; justify-content: center; border-radius: 22px; font-size: 29px; } .media-image { color: #047857; background: #d1fae5; } .media-video { color: #1d4ed8; background: #dbeafe; } .media-audio { color: #7e22ce; background: #f3e8ff; } .media-pdf { color: #b91c1c; background: #fee2e2; } .media-document { color: #1d4ed8; background: #dbeafe; } .media-other { color: #475569; background: #e2e8f0; } .media-type-pill { position: absolute; left: 11px; top: 11px; padding: 5px 8px; border-radius: 7px; color: #fff; background: rgba( 15, 23, 42, .72 ); backdrop-filter: blur(8px); font-size: 9px; font-weight: 800; text-transform: uppercase; letter-spacing: .05em; } .media-status-pill { position: absolute; right: 11px; top: 11px; padding: 5px 8px; border-radius: 999px; font-size: 9px; font-weight: 800; background: rgba( 255, 255, 255, .92 ); } .media-status-pill.active { color: var(--success); } .media-status-pill.inactive { color: var(--danger); } .media-info { padding: 15px; } .media-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; font-weight: 800; } .media-original { margin-top: 3px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--muted); font-size: 10px; } .media-meta { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; margin-top: 11px; } .meta-chip { display: inline-flex; align-items: center; gap: 5px; padding: 5px 7px; border-radius: 7px; background: var(--surface-soft); color: #64748b; font-size: 9px; font-weight: 700; } .media-card-footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 14px; padding-top: 12px; border-top: 1px solid #edf2f7; } .media-date { color: var(--muted-light); font-size: 9px; } .media-actions { display: flex; align-items: center; gap: 5px; } .icon-btn { width: 32px; height: 32px; display: inline-flex; align-items: center; justify-content: center; border: 1px solid var(--border); border-radius: 9px; background: #fff; color: #64748b; cursor: pointer; transition: background .18s ease, color .18s ease, border-color .18s ease; } .icon-btn:hover { background: var(--surface-soft); color: var(--text); } .icon-btn.success:hover { color: var(--success); border-color: #bbf7d0; background: var(--success-bg); } .icon-btn.warning:hover { color: var(--warning); border-color: #fde68a; background: var(--warning-bg); } .icon-btn.danger:hover { color: var(--danger); border-color: #fecaca; background: var(--danger-bg); } .empty-state { text-align: center; padding: 75px 20px; } .empty-icon { width: 66px; height: 66px; margin: 0 auto 15px; display: flex; align-items: center; justify-content: center; border-radius: 19px; background: var(--primary-soft); color: var(--primary); font-size: 25px; } .empty-state h3 { margin: 0; font-size: 17px; } .empty-state p { margin: 7px 0 20px; color: var(--muted); } /* ================================================= MODAL ================================================= */ .modal-backdrop { position: fixed; inset: 0; z-index: 100; display: none; align-items: center; justify-content: center; padding: 20px; background: rgba( 15, 23, 42, .58 ); backdrop-filter: blur(7px); -webkit-backdrop-filter: blur(7px); } .modal-backdrop.show { display: flex; } .modal { width: min( 720px, 100% ); max-height: calc( 100vh - 40px ); overflow-y: auto; background: #fff; border-radius: 22px; box-shadow: var(--shadow-lg); animation: modalIn .22s ease; } @keyframes modalIn { from { opacity: 0; transform: translateY(10px) scale(.98); } to { opacity: 1; transform: translateY(0) scale(1); } } .modal-header { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 20px 22px; border-bottom: 1px solid var(--border); } .modal-title { display: flex; align-items: center; gap: 11px; } .modal-title-icon { width: 39px; height: 39px; display: flex; align-items: center; justify-content: center; border-radius: 11px; background: var(--primary-soft); color: var(--primary); } .modal-title h3 { margin: 0; font-size: 17px; font-weight: 800; } .modal-title p { margin: 2px 0 0; color: var(--muted); font-size: 11px; } .close-btn { width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; border: 1px solid var(--border); border-radius: 10px; background: #fff; color: #64748b; cursor: pointer; } .close-btn:hover { color: var(--danger); background: var(--danger-bg); } .modal-body { padding: 22px; } .form-grid { display: grid; grid-template-columns: repeat( 2, minmax(0, 1fr) ); gap: 17px; } .form-group.full { grid-column: 1 / -1; } .form-label { display: block; margin-bottom: 7px; color: #334155; font-size: 12px; font-weight: 800; } .required { color: var(--danger); } .field-help { margin-top: 6px; color: var(--muted-light); font-size: 10px; line-height: 1.5; } .modal-footer { display: flex; align-items: center; justify-content: flex-end; gap: 9px; padding: 16px 22px; border-top: 1px solid var(--border); background: #fafafa; } /* ================================================= UPLOAD ZONE ================================================= */ .upload-zone { position: relative; min-height: 180px; display: flex; flex-direction: column; align-items: center; justify-content: center; text-align: center; padding: 25px; border: 1.5px dashed #cbd5e1; border-radius: 16px; background: #f8fafc; cursor: pointer; transition: border-color .2s ease, background .2s ease; } .upload-zone:hover, .upload-zone.dragging { border-color: var(--primary); background: var(--primary-soft); } .upload-icon { width: 55px; height: 55px; display: flex; align-items: center; justify-content: center; margin-bottom: 10px; border-radius: 16px; background: var(--primary-soft); color: var(--primary); font-size: 21px; } .upload-zone strong { font-size: 13px; } .upload-zone span { margin-top: 5px; color: var(--muted); font-size: 10px; } .upload-zone input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; } .selected-files { margin-top: 10px; color: var(--primary); font-size: 11px; font-weight: 700; } /* ================================================= RESPONSIVE ================================================= */ @media (max-width: 1300px) { .stats-grid { grid-template-columns: repeat( 3, minmax(0, 1fr) ); } .media-grid { grid-template-columns: repeat( 3, minmax(0, 1fr) ); } } @media (max-width: 1100px) { .page-shell { margin-left: 0; } .topbar { padding: 0 20px; } } @media (max-width: 850px) { .media-grid { grid-template-columns: repeat( 2, minmax(0, 1fr) ); } .card-toolbar { align-items: stretch; flex-direction: column; } .toolbar-left { flex-direction: column; align-items: stretch; } .search-box { width: 100%; } .filter-select { width: 100%; } } @media (max-width: 700px) { .page-container { width: calc(100% - 28px); padding-top: 20px; } .page-header { align-items: flex-start; flex-direction: column; } .stats-grid { grid-template-columns: repeat( 2, minmax(0, 1fr) ); } .form-grid { grid-template-columns: 1fr; } .form-group.full { grid-column: auto; } } @media (max-width: 540px) { .page-container { width: calc(100% - 20px); } .topbar { height: 66px; padding: 0 13px; } .topbar-icon { width: 37px; height: 37px; } .topbar-title { font-size: 14px; } .topbar-subtitle { display: none; } .topbar-pill span { display: none; } .stats-grid { grid-template-columns: 1fr; } .media-grid { grid-template-columns: 1fr; } .media-preview { height: 220px; } .modal-backdrop { padding: 10px; } .modal { border-radius: 17px; } .modal-body { padding: 17px; } .modal-footer { padding: 14px 17px; } } </style> </head> <body> <?php /* * Sidebar intentionally included separately. * * Do NOT include admin/header.php here. */ require_once __DIR__ . '/sidebar.php'; ?> <div class="page-shell"> <!-- ===================================================== TOPBAR ====================================================== --> <header class="topbar"> <div class="topbar-left"> <div class="topbar-icon"> <i class="fa-solid fa-photo-film"></i> </div> <div> <h2 class="topbar-title"> Media Library </h2> <p class="topbar-subtitle"> Images, documents, videos & files </p> </div> </div> <div> <div class="topbar-pill"> <i class="fa-solid fa-shield-halved"></i> <span> Admin Panel </span> </div> </div> </header> <!-- ===================================================== MAIN ====================================================== --> <main class="page-container"> <!-- PAGE HEADER --> <div class="page-header"> <div class="page-heading"> <h1> Media Library </h1> <p> Upload, organize and manage all website media assets from one place. </p> </div> <button type="button" class="btn-primary" onclick="openUploadModal()" > <i class="fa-solid fa-cloud-arrow-up"></i> Upload Media </button> </div> <!-- ================================================= FLASH ================================================== --> <?php if ($flash): ?> <div class="flash <?= e($flash['type']); ?>" > <?php if ( $flash['type'] === 'success' ): ?> <i class="fa-solid fa-circle-check"></i> <?php else: ?> <i class="fa-solid fa-circle-exclamation"></i> <?php endif; ?> <span> <?= e( $flash['message'] ); ?> </span> </div> <?php endif; ?> <!-- ================================================= STATS ================================================== --> <div class="stats-grid"> <div class="stat-card"> <div class="stat-icon"> <i class="fa-solid fa-photo-film"></i> </div> <div class="stat-value"> <?= number_format( $totalMedia ); ?> </div> <div class="stat-label"> Total Media </div> </div> <div class="stat-card"> <div class="stat-icon"> <i class="fa-solid fa-circle-check"></i> </div> <div class="stat-value"> <?= number_format( $activeMedia ); ?> </div> <div class="stat-label"> Active Files </div> </div> <div class="stat-card"> <div class="stat-icon"> <i class="fa-solid fa-images"></i> </div> <div class="stat-value"> <?= number_format( $totalImages ); ?> </div> <div class="stat-label"> Images </div> </div> <div class="stat-card"> <div class="stat-icon"> <i class="fa-solid fa-film"></i> </div> <div class="stat-value"> <?= number_format( $totalVideoAudio ); ?> </div> <div class="stat-label"> Video / Audio </div> </div> <div class="stat-card"> <div class="stat-icon"> <i class="fa-solid fa-hard-drive"></i> </div> <div class="stat-value"> <?= e( format_file_size( $totalStorage ) ); ?> </div> <div class="stat-label"> Storage Used </div> </div> </div> <!-- ================================================= MEDIA CARD ================================================== --> <section class="content-card"> <div class="card-toolbar"> <form method="get" action="media.php" class="toolbar-left" > <div class="search-box"> <i class="fa-solid fa-magnifying-glass"></i> <input type="text" name="search" class="form-control" value="<?= e( $search ); ?>" placeholder="Search files, titles, alt text..." > </div> <select name="file_type" class="form-select filter-select" onchange="this.form.submit()" > <option value=""> All Types </option> <?php foreach ( $allowedTypes as $type ): ?> <option value="<?= e( $type ); ?>" <?= $typeFilter === $type ? 'selected' : ''; ?> > <?= e( ucfirst( $type ) ); ?> </option> <?php endforeach; ?> </select> <select name="status" class="form-select filter-select" onchange="this.form.submit()" > <option value=""> All Status </option> <option value="1" <?= $statusFilter === '1' ? 'selected' : ''; ?> > Active </option> <option value="0" <?= $statusFilter === '0' ? 'selected' : ''; ?> > Disabled </option> </select> <button type="submit" class="btn-light" > <i class="fa-solid fa-filter"></i> Filter </button> <?php if ( $search !== '' || $typeFilter !== '' || $statusFilter !== '' ): ?> <a href="media.php" class="btn-light" > <i class="fa-solid fa-xmark"></i> Clear </a> <?php endif; ?> </form> </div> <?php if (!empty($mediaItems)): ?> <div class="media-grid"> <?php foreach ( $mediaItems as $item ): ?> <?php $isImage = strtolower( (string)$item['file_type'] ) === 'image'; $publicPath = media_public_path( $item['file_path'] ); $thumbnailPath = !empty( $item['thumbnail_path'] ) ? media_public_path( $item['thumbnail_path'] ) : ''; $previewPath = $thumbnailPath !== '' ? $thumbnailPath : $publicPath; $icon = get_media_icon( $item['file_type'], $item['mime_type'] ); $colorClass = get_media_color_class( $item['file_type'] ); $dimensions = ''; if ( !empty($item['width']) && !empty($item['height']) ) { $dimensions = (int)$item['width'] . ' × ' . (int)$item['height']; } ?> <article class="media-card"> <!-- PREVIEW --> <div class="media-preview"> <?php if ( $isImage && $previewPath !== '' ): ?> <img src="<?= e( $previewPath ); ?>" alt="<?= e( $item['alt_text'] ?: $item['original_name'] ); ?>" loading="lazy" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';" > <div class="media-file-icon <?= e( $colorClass ); ?>" style="display:none;" > <i class="fa-solid <?= e( $icon ); ?>" ></i> </div> <?php else: ?> <div class="media-file-icon <?= e( $colorClass ); ?>" > <i class="fa-solid <?= e( $icon ); ?>" ></i> </div> <?php endif; ?> <div class="media-type-pill"> <?= e( strtoupper( $item['file_type'] ) ); ?> </div> <div class="media-status-pill <?= (int)$item['status'] === 1 ? 'active' : 'inactive'; ?>" > <i class="fa-solid fa-circle" style="font-size:6px;" ></i> <?= (int)$item['status'] === 1 ? 'Active' : 'Disabled'; ?> </div> </div> <!-- INFO --> <div class="media-info"> <div class="media-name" title="<?= e( $item['title'] ?: $item['original_name'] ); ?>" > <?= e( $item['title'] ?: $item['original_name'] ); ?> </div> <div class="media-original" title="<?= e( $item['original_name'] ); ?>" > <?= e( $item['original_name'] ); ?> </div> <div class="media-meta"> <span class="meta-chip"> <i class="fa-solid fa-weight-hanging"></i> <?= e( format_file_size( $item['file_size'] ) ); ?> </span> <?php if ( $dimensions !== '' ): ?> <span class="meta-chip"> <i class="fa-solid fa-expand"></i> <?= e( $dimensions ); ?> </span> <?php endif; ?> <?php if ( !empty( $item['extension'] ) ): ?> <span class="meta-chip"> .<?= e( strtolower( $item['extension'] ) ); ?> </span> <?php endif; ?> </div> <div class="media-card-footer"> <div class="media-date"> <?= !empty( $item['created_at'] ) ? e( date( 'd M Y', strtotime( $item['created_at'] ) ) ) : '—'; ?> </div> <div class="media-actions"> <!-- Preview --> <?php if ( $publicPath !== '' ): ?> <a href="<?= e( $publicPath ); ?>" target="_blank" rel="noopener noreferrer" class="icon-btn" title="Open File" > <i class="fa-solid fa-arrow-up-right-from-square"></i> </a> <?php endif; ?> <!-- Edit --> <button type="button" class="icon-btn" title="Edit Details" onclick='openEditModal( <?= json_encode( [ 'id' => (int)$item['id'], 'folder_id' => $item['folder_id'], 'alt_text' => $item['alt_text'], 'title' => $item['title'], 'caption' => $item['caption'] ], JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT ); ?> )' > <i class="fa-solid fa-pen"></i> </button> <!-- Status --> <form method="post" style="display:inline;" onsubmit="return confirmToggle(<?= (int)$item['status']; ?>);" > <?= csrf_field(); ?> <input type="hidden" name="action" value="toggle_status" > <input type="hidden" name="id" value="<?= (int)$item['id']; ?>" > <button type="submit" class="icon-btn <?= (int)$item['status'] === 1 ? 'warning' : 'success'; ?>" title="<?= (int)$item['status'] === 1 ? 'Disable' : 'Activate'; ?>" > <?php if ( (int)$item['status'] === 1 ): ?> <i class="fa-solid fa-pause"></i> <?php else: ?> <i class="fa-solid fa-play"></i> <?php endif; ?> </button> </form> <!-- Delete --> <form method="post" style="display:inline;" onsubmit="return confirmDelete();" > <?= csrf_field(); ?> <input type="hidden" name="action" value="delete" > <input type="hidden" name="id" value="<?= (int)$item['id']; ?>" > <button type="submit" class="icon-btn danger" title="Delete" > <i class="fa-solid fa-trash"></i> </button> </form> </div> </div> </div> </article> <?php endforeach; ?> </div> <?php else: ?> <div class="empty-state"> <div class="empty-icon"> <i class="fa-solid fa-photo-film"></i> </div> <h3> No media found </h3> <p> <?php if ( $search !== '' || $typeFilter !== '' || $statusFilter !== '' ): ?> No media matched your current filters. <?php else: ?> Your media library is empty. Upload your first file to get started. <?php endif; ?> </p> <?php if ( $search !== '' || $typeFilter !== '' || $statusFilter !== '' ): ?> <a href="media.php" class="btn-light" > <i class="fa-solid fa-rotate-left"></i> Reset Filters </a> <?php else: ?> <button type="button" class="btn-primary" onclick="openUploadModal()" > <i class="fa-solid fa-cloud-arrow-up"></i> Upload Media </button> <?php endif; ?> </div> <?php endif; ?> </section> </main> </div> <!-- ========================================================= UPLOAD MODAL ========================================================= --> <div class="modal-backdrop" id="uploadModal" onclick="closeUploadBackdrop(event)" > <div class="modal"> <div class="modal-header"> <div class="modal-title"> <div class="modal-title-icon"> <i class="fa-solid fa-cloud-arrow-up"></i> </div> <div> <h3> Upload Media </h3> <p> Add one or multiple files to your library. </p> </div> </div> <button type="button" class="close-btn" onclick="closeUploadModal()" > <i class="fa-solid fa-xmark"></i> </button> </div> <form method="post" action="media.php" enctype="multipart/form-data" id="uploadForm" > <?= csrf_field(); ?> <input type="hidden" name="action" value="upload" > <div class="modal-body"> <div class="form-grid"> <!-- FILES --> <div class="form-group full"> <label class="form-label"> Select Files <span class="required">*</span> </label> <label class="upload-zone" id="uploadZone" > <div class="upload-icon"> <i class="fa-solid fa-cloud-arrow-up"></i> </div> <strong> Click to browse or drag & drop </strong> <span> Images, videos, audio, PDF and documents up to 50 MB per file </span> <div class="selected-files" id="selectedFiles" ></div> <input type="file" name="media_files[]" id="mediaFiles" multiple required > </label> </div> <!-- FOLDER ID --> <div class="form-group"> <label class="form-label"> Folder ID </label> <input type="number" name="folder_id" class="form-control" min="1" placeholder="Optional" > <div class="field-help"> Leave blank for media without a folder. </div> </div> <!-- ALT --> <div class="form-group"> <label class="form-label"> Alt Text </label> <input type="text" name="alt_text" class="form-control" maxlength="255" placeholder="Describe the image/file" > <div class="field-help"> Useful for accessibility and image SEO. </div> </div> <!-- TITLE --> <div class="form-group full"> <label class="form-label"> Title </label> <input type="text" name="title" class="form-control" maxlength="255" placeholder="Media title" > </div> <!-- CAPTION --> <div class="form-group full"> <label class="form-label"> Caption </label> <textarea name="caption" class="form-control" placeholder="Optional media caption..." ></textarea> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn-secondary" onclick="closeUploadModal()" > Cancel </button> <button type="submit" class="btn-primary" id="uploadButton" > <i class="fa-solid fa-cloud-arrow-up"></i> Upload Files </button> </div> </form> </div> </div> <!-- ========================================================= EDIT MODAL ========================================================= --> <div class="modal-backdrop" id="editModal" onclick="closeEditBackdrop(event)" > <div class="modal"> <div class="modal-header"> <div class="modal-title"> <div class="modal-title-icon"> <i class="fa-solid fa-pen"></i> </div> <div> <h3> Edit Media </h3> <p> Update media metadata. </p> </div> </div> <button type="button" class="close-btn" onclick="closeEditModal()" > <i class="fa-solid fa-xmark"></i> </button> </div> <form method="post" action="media.php" id="editForm" > <?= csrf_field(); ?> <input type="hidden" name="action" value="update" > <input type="hidden" name="id" id="editId" value="0" > <div class="modal-body"> <div class="form-grid"> <div class="form-group"> <label class="form-label"> Folder ID </label> <input type="number" name="folder_id" id="editFolderId" class="form-control" min="1" placeholder="Optional" > </div> <div class="form-group"> <label class="form-label"> Alt Text </label> <input type="text" name="alt_text" id="editAltText" class="form-control" maxlength="255" > </div> <div class="form-group full"> <label class="form-label"> Title </label> <input type="text" name="title" id="editTitle" class="form-control" maxlength="255" > </div> <div class="form-group full"> <label class="form-label"> Caption </label> <textarea name="caption" id="editCaption" class="form-control" placeholder="Optional caption..." ></textarea> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn-secondary" onclick="closeEditModal()" > Cancel </button> <button type="submit" class="btn-primary" id="editButton" > <i class="fa-solid fa-floppy-disk"></i> Save Changes </button> </div> </form> </div> </div> <script> /* ===================================================== UPLOAD MODAL ====================================================== */ const uploadModal = document.getElementById( 'uploadModal' ); const uploadForm = document.getElementById( 'uploadForm' ); const mediaFiles = document.getElementById( 'mediaFiles' ); const selectedFiles = document.getElementById( 'selectedFiles' ); const uploadZone = document.getElementById( 'uploadZone' ); function openUploadModal() { uploadForm.reset(); selectedFiles.textContent = ''; uploadModal.classList.add( 'show' ); document.body.style.overflow = 'hidden'; } function closeUploadModal() { uploadModal.classList.remove( 'show' ); document.body.style.overflow = ''; } function closeUploadBackdrop(event) { if ( event.target === uploadModal ) { closeUploadModal(); } } /* ===================================================== FILE SELECTION ====================================================== */ mediaFiles.addEventListener( 'change', function () { const files = Array.from( this.files || [] ); if (!files.length) { selectedFiles.textContent = ''; return; } const totalSize = files.reduce( function ( total, file ) { return total + file.size; }, 0 ); selectedFiles.textContent = files.length + ( files.length === 1 ? ' file selected' : ' files selected' ) + ' • ' + formatBytes( totalSize ); } ); function formatBytes(bytes) { if (!bytes) { return '0 B'; } const units = [ 'B', 'KB', 'MB', 'GB' ]; const i = Math.floor( Math.log(bytes) / Math.log(1024) ); return ( bytes / Math.pow( 1024, Math.min( i, units.length - 1 ) ) ).toFixed( i === 0 ? 0 : 2 ) + ' ' + units[ Math.min( i, units.length - 1 ) ]; } /* ===================================================== DRAG & DROP ====================================================== */ [ 'dragenter', 'dragover' ].forEach( function (eventName) { uploadZone.addEventListener( eventName, function (event) { event.preventDefault(); uploadZone.classList.add( 'dragging' ); } ); } ); [ 'dragleave', 'drop' ].forEach( function (eventName) { uploadZone.addEventListener( eventName, function (event) { event.preventDefault(); uploadZone.classList.remove( 'dragging' ); } ); } ); uploadZone.addEventListener( 'drop', function (event) { const files = event.dataTransfer.files; if (!files.length) { return; } try { const dataTransfer = new DataTransfer(); Array.from(files) .forEach( function (file) { dataTransfer.items.add( file ); } ); mediaFiles.files = dataTransfer.files; mediaFiles.dispatchEvent( new Event( 'change' ) ); } catch (error) { selectedFiles.textContent = files.length + ' file(s) selected'; } } ); /* ===================================================== EDIT MODAL ====================================================== */ const editModal = document.getElementById( 'editModal' ); function openEditModal(data) { document.getElementById( 'editId' ).value = data.id || 0; document.getElementById( 'editFolderId' ).value = data.folder_id || ''; document.getElementById( 'editAltText' ).value = data.alt_text || ''; document.getElementById( 'editTitle' ).value = data.title || ''; document.getElementById( 'editCaption' ).value = data.caption || ''; editModal.classList.add( 'show' ); document.body.style.overflow = 'hidden'; } function closeEditModal() { editModal.classList.remove( 'show' ); document.body.style.overflow = ''; } function closeEditBackdrop(event) { if ( event.target === editModal ) { closeEditModal(); } } /* ===================================================== CONFIRMATIONS ====================================================== */ function confirmDelete() { return confirm( 'Are you sure you want to delete this media file? The database record and local uploaded file will be removed.' ); } function confirmToggle(status) { if ( Number(status) === 1 ) { return confirm( 'Disable this media file?' ); } return confirm( 'Activate this media file?' ); } /* ===================================================== SUBMIT BUTTON STATES ====================================================== */ uploadForm.addEventListener( 'submit', function () { const button = document.getElementById( 'uploadButton' ); button.disabled = true; button.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Uploading...'; } ); document.getElementById( 'editForm' ).addEventListener( 'submit', function () { const button = document.getElementById( 'editButton' ); button.disabled = true; button.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Saving...'; } ); /* ===================================================== ESC KEY ====================================================== */ document.addEventListener( 'keydown', function (event) { if ( event.key !== 'Escape' ) { return; } closeUploadModal(); closeEditModal(); } ); </script> </body> </html>
Save
Cancel