false,'error'=>'Not installed']); exit; } require_once ROOT_PATH . '/includes/db.php'; require_once ROOT_PATH . '/includes/functions.php'; require_once ROOT_PATH . '/includes/auth.php'; require_login(); header('Content-Type: application/json; charset=UTF-8'); // Verify CSRF $token = $_POST['csrf_token'] ?? ''; if (!hash_equals($_SESSION['csrf_token'] ?? '', $token)) { echo json_encode(['success'=>false,'error'=>'Invalid CSRF token']); exit; } if (empty($_FILES['file']['tmp_name'])) { echo json_encode(['success'=>false,'error'=>'No file received']); exit; } $f = $_FILES['file']; $mime = mime_content_type($f['tmp_name']); $origName = basename($f['name']); $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION)); // Determine type $isImage = in_array($mime, ALLOWED_IMAGE_TYPES) || in_array('image/' . $ext, ALLOWED_IMAGE_TYPES); $isAudio = in_array($mime, ALLOWED_AUDIO_TYPES) || in_array('audio/' . $ext, ALLOWED_AUDIO_TYPES) || in_array($ext, ['mp3','ogg','wav','m4a']); $isPdf = ($ext === 'pdf') || in_array($mime, ALLOWED_PDF_TYPES); if (!$isImage && !$isAudio && !$isPdf) { echo json_encode(['success'=>false,'error'=>'File type not allowed: ' . $mime]); exit; } $maxSize = $isPdf ? MAX_PDF_SIZE : ($isImage ? MAX_IMAGE_SIZE : MAX_AUDIO_SIZE); if ($f['size'] > $maxSize) { echo json_encode(['success'=>false,'error'=>'File too large (max ' . ($maxSize/1024/1024) . 'MB)']); exit; } $fileType = $isPdf ? 'pdf' : ($isImage ? 'image' : 'audio'); $subDir = $isPdf ? 'pdf' : ($isImage ? 'images' : 'audio'); $safeName = preg_replace('/[^a-zA-Z0-9._-]/', '_', $origName); $filename = date('YmdHis') . '_' . bin2hex(random_bytes(4)) . '.' . $ext; $destPath = UPLOADS_PATH . '/' . $subDir . '/' . $filename; if (!move_uploaded_file($f['tmp_name'], $destPath)) { echo json_encode(['success'=>false,'error'=>'Failed to save file']); exit; } // Record in DB db()->prepare( "INSERT INTO media (filename, original_name, mime_type, file_size, file_type, uploaded_by) VALUES (?,?,?,?,?,?)" )->execute([$filename, $origName, $mime, $f['size'], $fileType, $_SESSION['user_id']]); $url = base_url('uploads/' . $subDir . '/' . $filename); echo json_encode([ 'success' => true, 'url' => $url, 'filename' => $filename, 'original_name' => $origName, 'file_type' => $fileType, 'mime_type' => $mime, ]);