Sindbad~EG File Manager

Current Path : /home/copmadinaarea/thecopmadinaarea.org/newsfeed/includes/
Upload File :
Current File : /home/copmadinaarea/thecopmadinaarea.org/newsfeed/includes/image_handler.php

<?php
/**
 * Image Upload Handler for COP News Portal
 */

class ImageHandler {
    private $upload_dir;
    private $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    private $max_file_size = 5242880; // 5MB
    private $max_width = 1920;
    private $max_height = 1080;

    public function __construct() {
        $this->upload_dir = __DIR__ . '/../images/news/';
        
        // Create directory if it doesn't exist
        if (!is_dir($this->upload_dir)) {
            mkdir($this->upload_dir, 0755, true);
        }
    }

    public function uploadImage($file, $news_id = null) {
        try {
            // Validate file
            $validation = $this->validateFile($file);
            if (!$validation['valid']) {
                return ['success' => false, 'error' => $validation['error']];
            }

            // Generate unique filename
            $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $filename = $this->generateFilename($file_extension, $news_id);
            $filepath = $this->upload_dir . $filename;

            // Move uploaded file
            if (!move_uploaded_file($file['tmp_name'], $filepath)) {
                return ['success' => false, 'error' => 'Failed to move uploaded file'];
            }

            // Resize image if needed
            $this->resizeImage($filepath, $file_extension);

            // Return relative path for database storage
            $relative_path = 'images/news/' . $filename;
            
            return [
                'success' => true,
                'filename' => $filename,
                'path' => $relative_path,
                'full_path' => $filepath
            ];

        } catch (Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    private function validateFile($file) {
        // Check if file was uploaded
        if (!isset($file['tmp_name']) || empty($file['tmp_name'])) {
            return ['valid' => false, 'error' => 'No file uploaded'];
        }

        // Check for upload errors
        if ($file['error'] !== UPLOAD_ERR_OK) {
            return ['valid' => false, 'error' => 'File upload error: ' . $this->getUploadError($file['error'])];
        }

        // Check file size
        if ($file['size'] > $this->max_file_size) {
            return ['valid' => false, 'error' => 'File size exceeds 5MB limit'];
        }

        // Check file type
        $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($file_extension, $this->allowed_types)) {
            return ['valid' => false, 'error' => 'Invalid file type. Allowed: ' . implode(', ', $this->allowed_types)];
        }

        // Verify it's actually an image
        $image_info = getimagesize($file['tmp_name']);
        if ($image_info === false) {
            return ['valid' => false, 'error' => 'File is not a valid image'];
        }

        return ['valid' => true];
    }

    private function generateFilename($extension, $news_id = null) {
        $timestamp = time();
        $random = mt_rand(1000, 9999);
        $prefix = $news_id ? "news_{$news_id}_" : "news_";
        return $prefix . $timestamp . '_' . $random . '.' . $extension;
    }

    private function resizeImage($filepath, $extension) {
        $image_info = getimagesize($filepath);
        $width = $image_info[0];
        $height = $image_info[1];

        // Only resize if image is larger than max dimensions
        if ($width <= $this->max_width && $height <= $this->max_height) {
            return;
        }

        // Calculate new dimensions
        $ratio = min($this->max_width / $width, $this->max_height / $height);
        $new_width = intval($width * $ratio);
        $new_height = intval($height * $ratio);

        // Create image resource based on type
        switch ($extension) {
            case 'jpg':
            case 'jpeg':
                $source = imagecreatefromjpeg($filepath);
                break;
            case 'png':
                $source = imagecreatefrompng($filepath);
                break;
            case 'gif':
                $source = imagecreatefromgif($filepath);
                break;
            case 'webp':
                $source = imagecreatefromwebp($filepath);
                break;
            default:
                return;
        }

        if (!$source) {
            return;
        }

        // Create new image
        $resized = imagecreatetruecolor($new_width, $new_height);
        
        // Preserve transparency for PNG and GIF
        if ($extension === 'png' || $extension === 'gif') {
            imagealphablending($resized, false);
            imagesavealpha($resized, true);
            $transparent = imagecolorallocatealpha($resized, 255, 255, 255, 127);
            imagefilledrectangle($resized, 0, 0, $new_width, $new_height, $transparent);
        }

        // Resize image
        imagecopyresampled($resized, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

        // Save resized image
        switch ($extension) {
            case 'jpg':
            case 'jpeg':
                imagejpeg($resized, $filepath, 90);
                break;
            case 'png':
                imagepng($resized, $filepath, 9);
                break;
            case 'gif':
                imagegif($resized, $filepath);
                break;
            case 'webp':
                imagewebp($resized, $filepath, 90);
                break;
        }

        // Clean up memory
        imagedestroy($source);
        imagedestroy($resized);
    }

    private function getUploadError($error_code) {
        switch ($error_code) {
            case UPLOAD_ERR_INI_SIZE:
                return 'File exceeds upload_max_filesize directive';
            case UPLOAD_ERR_FORM_SIZE:
                return 'File exceeds MAX_FILE_SIZE directive';
            case UPLOAD_ERR_PARTIAL:
                return 'File was only partially uploaded';
            case UPLOAD_ERR_NO_FILE:
                return 'No file was uploaded';
            case UPLOAD_ERR_NO_TMP_DIR:
                return 'Missing temporary folder';
            case UPLOAD_ERR_CANT_WRITE:
                return 'Failed to write file to disk';
            case UPLOAD_ERR_EXTENSION:
                return 'File upload stopped by extension';
            default:
                return 'Unknown upload error';
        }
    }

    public function deleteImage($image_path) {
        if (empty($image_path)) {
            return true;
        }

        $full_path = __DIR__ . '/../' . $image_path;
        if (file_exists($full_path)) {
            return unlink($full_path);
        }
        return true;
    }

    public function getImageUrl($image_path) {
        if (empty($image_path)) {
            return null;
        }
        
        // Return relative URL for web display
        return $image_path;
    }
}
?>

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists