Priority File Manager

📁 public_html
Base Directory:
/home/ecedu/public_html/new/api
NameTypeSizeActions
📁 .. Folder -
📄 about_controller.php File 1241
Edit Download
📄 ads_controller.php File 2645
Edit Download
📄 contact_controller.php File 1712
Edit Download
📄 data_controller.php File 3033
Edit Download
📄 header.php File 735
Edit Download
📄 image_controller.php File 2510
Edit Download
📄 news_controller.php File 16067
Edit Download
📄 social_controller.php File 1717
Edit Download
📄 upload_pdf_thumbnail.php File 1844
Edit Download
📄 validate.php File 510
Edit Download

View File: news_controller.php

<?php

header("Access-Control-Allow-Origin: http://sj.madarik.org"); 
 
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}


include('header.php');

require_once __DIR__ . '/../Models/DB.php';

class NewsAPI {
    private $db;
    protected int $maxTables = 48;
    private $tables = [];

    /**
     * Initialize the object with database connection
     */
    public function __construct() {
        for ($i = 1; $i <= $this->maxTables; $i++) {
            $this->tables[$i] = 'dbs_news' . $i;
        }

        $this->db = DB::instance()->getConnection();
    }

    /**
     * Return a standardized JSON response
     * @param bool $success Status of the operation
     * @param string $message Response message
     * @param mixed $data Additional data (optional)
     */
    private function jsonResponse(bool $success, string $message, $data = null) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode([
            'status' => $success,
            'message' => $message,
            'data' => $data
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * Get table name based on news type
     * @param int $type News type
     * @return string|false Table name or false if invalid
     */
    private function getTableName(int $type) {
        return $this->tables[$type] ?? false;
    }

    /**
     * Validate input data
     * @param array $input Input data
     * @param bool $isUpdate Whether it's an update operation
     */
    private function validateInput(array $input, bool $isUpdate = false) {
        $requiredFields = ['news_title', 'news_description']; // Only non-nullable fields
        foreach ($requiredFields as $field) {
            if (empty($input[$field]) && !$isUpdate) {
                $this->jsonResponse(false, "الحقل $field مطلوب");
            }
        }

        // Validate date format if provided
        if (!empty($input['news_date']) && !DateTime::createFromFormat('Y-m-d H:i:s', $input['news_date'])) {
            $this->jsonResponse(false, "تنسيق التاريخ غير صحيح، يجب أن يكون Y-m-d H:i:s");
        }
    }

    /**
 * Upload an image associated with the news
 * @param array $file Uploaded file data
 * @param int $id News ID
 * @param string $table Table name
 * @param string|null $oldImage Existing image filename (if any)
 * @return string|null Filename if successful, null otherwise
 */
    private function uploadImage(array $file, int $id, string $table, ?string $oldImage = null) {
    if (!isset($file['tmp_name']) || !is_uploaded_file($file['tmp_name'])) {
        return null;
    }

    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

    if (!in_array($ext, $allowed)) {
        $this->jsonResponse(false, "نوع الصورة غير مدعوم");
    }

    $uploadDir = __DIR__ . "/../service/images/news/$table/";
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
        $this->jsonResponse(false, "فشل في إنشاء مجلد الصور");
    }

    $filename = "img_{$id}.{$ext}";
    $filepath = $uploadDir . $filename;

    // Delete old image if it exists
    if ($oldImage && file_exists($uploadDir . $oldImage)) {
        unlink($uploadDir . $oldImage);
    }

    // Delete any other old images with different extensions
    foreach ($allowed as $e) {
        $oldFile = $uploadDir . "img_{$id}.{$e}";
        if (file_exists($oldFile) && $oldFile !== $filepath) {
            unlink($oldFile);
        }
    }

    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return $ext;
    }

    $this->jsonResponse(false, "فشل رفع الصورة");
    }


    /**
     * Add a new news item
     * @param array $post News data
     * @param array $file Image data (optional)
     * @param int $type News type
     */
    public function addNews(array $post, array $file, int $type) {
        try {
            $this->validateInput($post);

            $table = $this->getTableName($type);
            if (!$table) $this->jsonResponse(false, "نوع الأخبار غير صحيح");

            $stmt = $this->db->prepare("
                INSERT INTO $table 
                (news_title, news_title1, news_title2, news_description, news_description1, news_description2, news_link, news_date, news_status, news_priority, user_id)
                VALUES (:news_title, :news_title1, :news_title2, :news_description, :news_description1, :news_description2, :news_link, :news_date,  :news_status, :news_priority, :user_id)
            ");

            $stmt->execute([
                ':news_title' => $post['news_title'] ?? '',
                ':news_title1' => $post['news_title1'] ?? null,
                ':news_title2' => $post['news_title2'] ?? null,
                ':news_description' => $post['news_description'] ?? '',
                ':news_description1' => $post['news_description1'] ?? null,
                ':news_description2' => $post['news_description2'] ?? null,
                ':news_link' => $post['news_link'] ?? null,
                ':news_date' => $post['news_date'] ?? date('Y-m-d H:i:s'),
                ':news_status' => 1,
                ':news_priority' => $post['news_priority'] ?? 1,
                ':user_id' => $post['user_id'] ?? 1,
            ]);

            $id = $this->db->lastInsertId();

            if (!empty($file)) {
                $imageExt = $this->uploadImage($file, $id, $table);
                if ($imageExt) {
                    $upd = $this->db->prepare("UPDATE $table SET img_ext = :ext WHERE news_id = :id");
                    $upd->execute([':ext' => $imageExt, ':id' => $id]);
                } elseif (isset($file['tmp_name']) && is_uploaded_file($file['tmp_name'])) {
                    $this->jsonResponse(false, "فشل رفع الصورة");
                }
            }

            $this->jsonResponse(true, "تم إضافة الخبر بنجاح", ['id' => $id]);
        } catch (PDOException $e) {
            $this->jsonResponse(false, "خطأ في قاعدة البيانات: " . $e->getMessage());
        }
    }

   
/**
 * Update an existing news item
 * @param int $id News ID
 * @param array $post Updated news data
 * @param array $file New image data (optional)
 * @param int $type News type
 */
      public function updateNews(int $id, array $post, array $file, int $type) {
       try {
        $this->validateInput($post, true);

        $table = $this->getTableName($type);
        if (!$table) $this->jsonResponse(false, "نوع الأخبار غير صحيح");

        $stmtCheck = $this->db->prepare("SELECT * FROM $table WHERE news_id = :id");
        $stmtCheck->execute([':id' => $id]);
        $news = $stmtCheck->fetch(PDO::FETCH_ASSOC);
        if (!$news) $this->jsonResponse(false, "الخبر غير موجود");

        // Update news data
        $stmt = $this->db->prepare("
            UPDATE $table SET 
                news_title = :news_title,
                news_title1 = :news_title1,
                news_title2 = :news_title2,
                news_description = :news_description,
                news_description1 = :news_description1,
                news_description2 = :news_description2,
                news_link = :news_link,
                news_date = :news_date,
                news_priority = :news_priority,
                user_id = :user_id
            WHERE news_id = :id
        ");

        $stmt->execute([
            ':news_title' => $post['news_title'] ?? $news['news_title'],
            ':news_title1' => $post['news_title1'] ?? $news['news_title1'],
            ':news_title2' => $post['news_title2'] ?? $news['news_title2'],
            ':news_description' => $post['news_description'] ?? $news['news_description'],
            ':news_description1' => $post['news_description1'] ?? $news['news_description1'],
            ':news_description2' => $post['news_description2'] ?? $news['news_description2'],
            ':news_link' => $post['news_link'] ?? $news['news_link'],
            ':news_date' => $post['news_date'] ?? $news['news_date'],
            ':news_priority' => $post['news_priority'] ?? $news['news_priority'],
            ':user_id' => $post['user_id'] ?? $news['user_id'],
            ':id' => $id,
        ]);

        // Handle image upload
        if (!empty($file) && isset($file['tmp_name']) && is_uploaded_file($file['tmp_name'])) {
            $imageExt = $this->uploadImage($file, $id, $table, $news['img_ext']);
            if ($imageExt) {
                $upd = $this->db->prepare("UPDATE $table SET img_ext = :ext WHERE news_id = :id");
                $upd->execute([':ext' => $imageExt, ':id' => $id]);
            }
        }

        $this->jsonResponse(true, "تم تعديل الخبر بنجاح");
     } catch (PDOException $e) {
        $this->jsonResponse(false, "خطأ في قاعدة البيانات: " . $e->getMessage());
     }
    }

    /**
     * Delete a news item
     * @param int $id News ID
     * @param int $type News type
     */
    public function deleteNews(int $id, int $type) {
        try {
            $table = $this->getTableName($type);
            if (!$table) $this->jsonResponse(false, "نوع الأخبار غير صحيح");

            $stmt = $this->db->prepare("SELECT img_ext FROM $table WHERE news_id = :id");
            $stmt->execute([':id' => $id]);
            $news = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($news && !empty($news['img_ext'])) {
                $oldFile = __DIR__ . "/../service/images/news/$table/img_{$id}.{$news['img_ext']}";
                if (file_exists($oldFile)) {
                    unlink($oldFile);
                }
            }

            $del = $this->db->prepare("DELETE FROM $table WHERE news_id = :id");
            $del->execute([':id' => $id]);

            $this->jsonResponse(true, "تم حذف الخبر بنجاح");
        } catch (PDOException $e) {
            $this->jsonResponse(false, "خطأ في قاعدة البيانات: " . $e->getMessage());
        }
    }

    /**
     * Toggle news status (active/inactive)
     * @param int $id News ID
     * @param int $type News type
     */
    public function toggleStatus(int $id, int $type) {
        try {
            $table = $this->getTableName($type);
            if (!$table) $this->jsonResponse(false, "نوع الأخبار غير صحيح");

            $stmt = $this->db->prepare("SELECT news_status FROM $table WHERE news_id = :id");
            $stmt->execute([':id' => $id]);
            $news = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$news) $this->jsonResponse(false, "الخبر غير موجود");

            $newStatus = $news['news_status'] == 1 ? 0 : 1;

            $upd = $this->db->prepare("UPDATE $table SET news_status = :status WHERE news_id = :id");
            $upd->execute([':status' => $newStatus, ':id' => $id]);

            $this->jsonResponse(true, "تم تغيير حالة الخبر بنجاح", ['status' => $newStatus]);
        } catch (PDOException $e) {
            $this->jsonResponse(false, "خطأ في قاعدة البيانات: " . $e->getMessage());
        }
    }

    /**
     * Retrieve news list with pagination
     * @param int $type News type
     * @param int $page Page number
     * @param int $perPage Items per page
     */
    public function getNews(int $type, int $page = 1, int $perPage = 10) {
        try {
            $table = $this->getTableName($type);
            if (!$table) $this->jsonResponse(false, "نوع الأخبار غير صحيح");

            $offset = ($page - 1) * $perPage;

            $stmt = $this->db->prepare("SELECT * FROM $table ORDER BY news_date DESC LIMIT :perPage OFFSET :offset");
            $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
            $stmt->bindValue(':perPage', $perPage, PDO::PARAM_INT);
            $stmt->execute();

            $newsList = $stmt->fetchAll(PDO::FETCH_ASSOC);

            $this->jsonResponse(true, "تم جلب الأخبار بنجاح", $newsList);
        } catch (PDOException $e) {
            $this->jsonResponse(false, "خطأ في قاعدة البيانات: " . $e->getMessage());
        }
    }
    
    /**
     * Retrieve news details
     * @param int $id News ID
     * @param int $type News type 
     */
    public function readNews( int $id , int $type) {
        try {
            $table = $this->getTableName($type);
            if (!$table) $this->jsonResponse(false, "نوع الأخبار غير صحيح");
             
            $sql = "SELECT * FROM $table WHERE news_id = :id LIMIT 1";
            $stmt = $this->db->prepare($sql);
            $stmt->bindValue(':id', $id, \PDO::PARAM_INT);
            $stmt->execute();
            $row = $stmt->fetch(\PDO::FETCH_ASSOC);
            $this->jsonResponse(true, "تم جلب تفاصيل خبر بنجاح", $row);
        
        } catch (PDOException $e) {
            $this->jsonResponse(false, "خطأ في قاعدة البيانات: " . $e->getMessage());
        }
    }

    /**
     * Handle incoming requests
     */
    public function handle() {
        try {
            $action = $_POST['action'] ?? '';
            $type = (int)($_POST['type'] ?? 0);

            if (!$type || !$this->getTableName($type)) {
                $this->jsonResponse(false, "نوع الأخبار غير صحيح");
            }

            switch ($action) {
                case 'add':
                    $this->addNews($_POST, $_FILES['image'] ?? [], $type);
                    break;
                case 'update':
                    $id = (int)($_POST['id'] ?? 0);
                    if (!$id) $this->jsonResponse(false, "معرف الخبر مطلوب للتعديل");
                    $this->updateNews($id, $_POST, $_FILES['image'] ?? [], $type);
                    break;
                case 'delete':
                    $id = (int)($_POST['id'] ?? 0);
                    if (!$id) $this->jsonResponse(false, "معرف الخبر مطلوب للحذف");
                    $this->deleteNews($id, $type);
                    break;
                case 'toggleStatus':
                    $id = (int)($_POST['id'] ?? 0);
                    if (!$id) $this->jsonResponse(false, "معرف الخبر مطلوب لتغيير الحالة");
                    $this->toggleStatus($id, $type);
                    break;
                case 'get':
                    $page = (int)($_POST['page'] ?? 1);
                    $perPage = (int)($_POST['perPage'] ?? 10);
                    $this->getNews($type, $page, $perPage);
                    break;
                case 'read':
                    $id = (int)($_POST['id'] ?? 0);
                    if (!$id) $this->jsonResponse(false, "معرف الخبر مطلوب للقراءة");
                    $this->readNews($id,$type );
                    break;
                default:
                    $this->jsonResponse(false, "عملية غير معروفة");
            }
        } catch (Exception $e) {
            $this->jsonResponse(false, "خطأ عام: " . $e->getMessage());
        }
    }
}

try {
    $newsApi = new NewsAPI();
    $newsApi->handle();
} catch (Exception $e) {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['success' => false, 'message' => "خطأ عام: " . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}