Sh3ll
OdayForums


Server : Apache
System : Linux profile 3.10.0-1160.88.1.el7.x86_64 #1 SMP Tue Mar 7 15:41:52 UTC 2023 x86_64
User : apache ( 48)
PHP Version : 8.0.28
Disable Function : NONE
Directory :  /var/www/html/pragyabhardwaj/admin/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //var/www/html/pragyabhardwaj/admin/publication_form.php
<?php
ob_start();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

include 'db.php';

$upload_path = "static/upload/";
$msg = "";

// Cryptographically secure CSRF Token generation
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* ================= FILE UPLOAD ENGINE (SECURE) ================= */
function secureUpload($file_field, $allowed_exts, $allowed_mimes, $prefix, $id, $upload_path) {
    if (empty($_FILES[$file_field]['name'])) return null;

    $filename = $_FILES[$file_field]['name'];
    $tmp_name = $_FILES[$file_field]['tmp_name'];
    
    // 1. Strict extension check
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed_exts)) {
        return ['error' => "❌ Invalid extension! Allowed: " . implode(', ', $allowed_exts)];
    }

    // 2. Binary content analysis (MIME check)
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $tmp_name);
    finfo_close($finfo);

    if (!in_array($mime, $allowed_mimes)) {
        return ['error' => "❌ Security violation: File content doesn't match extension."];
    }

    // 3. Unpredictable renaming
    $new_name = $prefix . "_" . $id . "_" . bin2hex(random_bytes(4)) . "." . $ext;
    if (move_uploaded_file($tmp_name, $upload_path . $new_name)) {
        return ['success' => $new_name];
    }

    return ['error' => "❌ Upload failed: Writing error."];
}

/* ================= POST ACTION: DELETE RECORD ================= */
if (isset($_POST['action_delete'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("❌ Security Error: CSRF Token Validation Failed!");
    }

    $id = intval($_POST['id']);

    $stmt = $conn->prepare("SELECT image, pdf FROM publications WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $data = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($data) {
        if (!empty($data['image']) && file_exists($upload_path . $data['image'])) {
            unlink($upload_path . $data['image']);
        }
        if (!empty($data['pdf']) && file_exists($upload_path . $data['pdf'])) {
            unlink($upload_path . $data['pdf']);
        }
    }

    $stmt = $conn->prepare("DELETE FROM publications WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $stmt->close();

    header("Location: index.php?page=publication_form");
    exit;
}

/* ================= POST ACTION: REMOVE IMAGE ================= */
if (isset($_POST['action_remove_image'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("❌ Security Error: CSRF Token Validation Failed!");
    }

    $id = intval($_POST['id']);

    $stmt = $conn->prepare("SELECT image FROM publications WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $data = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($data && !empty($data['image'])) {
        $file = $upload_path . $data['image'];
        if (file_exists($file)) unlink($file);

        $stmt = $conn->prepare("UPDATE publications SET image='' WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();
    }

    header("Location: index.php?page=publication_form");
    exit;
}

/* ================= POST ACTION: REMOVE PDF ================= */
if (isset($_POST['action_remove_pdf'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("❌ Security Error: CSRF Token Validation Failed!");
    }

    $id = intval($_POST['id']);

    $stmt = $conn->prepare("SELECT pdf FROM publications WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $data = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($data && !empty($data['pdf'])) {
        $file = $upload_path . $data['pdf'];
        if (file_exists($file)) unlink($file);

        $stmt = $conn->prepare("UPDATE publications SET pdf='' WHERE id = ?");
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $stmt->close();
    }

    header("Location: index.php?page=publication_form");
    exit;
}

/* ================= POST ACTION: UPDATE ================= */
if (isset($_POST['update'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("❌ Security Error: CSRF Token Validation Failed!");
    }

    $id = intval($_POST['id']);
    $title = trim($_POST['title']);
    $year = trim($_POST['year']);
    $details = trim($_POST['details']);
    $link = trim($_POST['link']);

    $image = $_POST['old_image'];
    $pdf = $_POST['old_pdf'];

    $img_exts = ['jpg', 'jpeg', 'png', 'gif'];
    $img_mimes = ['image/jpeg', 'image/png', 'image/gif'];

    $pdf_exts = ['pdf'];
    $pdf_mimes = ['application/pdf'];

    // Secure Image Update
    if (!empty($_FILES['new_image']['name'])) {
        $upload_res = secureUpload('new_image', $img_exts, $img_mimes, 'pub_img', $id, $upload_path);
        if (isset($upload_res['error'])) {
            die($upload_res['error']);
        } else {
            if (!empty($image) && file_exists($upload_path . $image)) unlink($upload_path . $image);
            $image = $upload_res['success'];
        }
    }

    // Secure PDF Update
    if (!empty($_FILES['new_pdf']['name'])) {
        $upload_res = secureUpload('new_pdf', $pdf_exts, $pdf_mimes, 'pub_doc', $id, $upload_path);
        if (isset($upload_res['error'])) {
            die($upload_res['error']);
        } else {
            if (!empty($pdf) && file_exists($upload_path . $pdf)) unlink($upload_path . $pdf);
            $pdf = $upload_res['success'];
        }
    }

    $stmt = $conn->prepare("UPDATE publications SET title=?, year=?, details=?, link=?, image=?, pdf=? WHERE id=?");
    $stmt->bind_param("ssssssi", $title, $year, $details, $link, $image, $pdf, $id);
    $stmt->execute();
    $stmt->close();

    header("Location: index.php?page=publication_form");
    exit;
}

/* ================= POST ACTION: INSERT ================= */
if (isset($_POST['save'])) {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die("❌ Security Error: CSRF Token Validation Failed!");
    }

    $title = trim($_POST['title']);
    $year = trim($_POST['year']);
    $details = trim($_POST['details']);
    $link = trim($_POST['link']);

    $stmt = $conn->prepare("INSERT INTO publications(title, year, details, link, image, pdf, sort_order) VALUES(?, ?, ?, ?, '', '', 0)");
    $stmt->bind_param("ssss", $title, $year, $details, $link);
    $stmt->execute();
    $last_id = $stmt->insert_id;
    $stmt->close();

    $img_exts = ['jpg', 'jpeg', 'png', 'gif'];
    $img_mimes = ['image/jpeg', 'image/png', 'image/gif'];

    $pdf_exts = ['pdf'];
    $pdf_mimes = ['application/pdf'];

    $final_image = '';
    $final_pdf = '';

    // Handle Image upload
    if (!empty($_FILES['image']['name'])) {
        $upload_res = secureUpload('image', $img_exts, $img_mimes, 'pub_img', $last_id, $upload_path);
        if (isset($upload_res['error'])) {
            $msg = $upload_res['error'];
        } else {
            $final_image = $upload_res['success'];
        }
    }

    // Handle PDF upload
    if (!empty($_FILES['pdf']['name']) && empty($msg)) {
        $upload_res = secureUpload('pdf', $pdf_exts, $pdf_mimes, 'pub_doc', $last_id, $upload_path);
        if (isset($upload_res['error'])) {
            $msg = $upload_res['error'];
        } else {
            $final_pdf = $upload_res['success'];
        }
    }

    // DB entry completion
    if (empty($msg) && (!empty($final_image) || !empty($final_pdf))) {
        $stmt = $conn->prepare("UPDATE publications SET image=?, pdf=? WHERE id=?");
        $stmt->bind_param("ssi", $final_image, $final_pdf, $last_id);
        $stmt->execute();
        $stmt->close();
    }

    if (empty($msg)) {
        header("Location: index.php?page=publication_form");
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Publications</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="static/css/admin.css">
</head>
<body>

<?php include 'admin/topbar.php'; ?>

<div class="container mt-4">
    <div class="box p-4 bg-light border rounded">
        <h2>📚 Add Publication</h2>

        <?php if(!empty($msg)) echo "<div class='alert alert-danger'>".htmlspecialchars($msg, ENT_QUOTES, 'UTF-8')."</div>"; ?>

        <!-- INSERT FORM -->
        <form method="POST" action="index.php?page=publication_form" enctype="multipart/form-data">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">
            
            <div class="row">
                <div class="col-md-2 mb-3">
                    <label class="form-label">Image Cover</label>
                    <input type="file" name="image" class="form-control">
                </div>

                <div class="col-md-2 mb-3">
                    <label class="form-label">Year</label>
                    <input type="text" name="year" class="form-control" placeholder="Year">
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Title</label>
                    <input type="text" name="title" class="form-control" placeholder="Title">
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">External Link</label>
                    <input type="text" name="link" class="form-control" placeholder="External Link">
                </div>

                <div class="col-md-4 mb-3">
                    <label class="form-label">Publication PDF</label>
                    <input type="file" name="pdf" class="form-control">
                </div>

                <div class="col-md-2 mb-3 align-self-end">
                    <button name="save" class="btn btn-primary w-100">Save</button>
                </div>

                <div class="col-12 mb-3">
                    <label class="form-label">Details</label>
                    <textarea name="details" class="form-control" placeholder="Details" rows="3"></textarea>
                </div>
            </div>
        </form>

        <hr>

        <h4>All Records (Inline Edit)</h4>

        <div class="table-responsive">
            <table class="table table-bordered table-hover align-middle">
                <thead class="table-dark">
                    <tr>
                        <th>ID</th>
                        <th>Image</th>
                        <th>Year</th>
                        <th>Title</th>
                        <th>Link</th>
                        <th>PDF</th>
                        <th>Details</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php
                $res = mysqli_query($conn, "SELECT * FROM publications ORDER BY sort_order ASC, id DESC");
                while($row = mysqli_fetch_assoc($res)){
                ?>
                <tr>
                    <form method="POST" action="index.php?page=publication_form" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="hidden" name="id" value="<?= $row['id'] ?>">

                        <td><?= $row['id'] ?></td>

                        <td>
                            <?php if(!empty($row['image'])) { ?>
                                <img src="<?= htmlspecialchars($upload_path . $row['image'], ENT_QUOTES, 'UTF-8') ?>" width="60" class="img-thumbnail mb-1"><br>
                            <?php } ?>
                            <input type="file" name="new_image" class="form-control form-control-sm mb-1">
                            <input type="hidden" name="old_image" value="<?= htmlspecialchars($row['image'], ENT_QUOTES, 'UTF-8') ?>">
                            <?php if(!empty($row['image'])) { ?>
                                <button type="submit" name="action_remove_image" class="btn btn-warning btn-sm w-100 mt-1">Remove</button>
                            <?php } ?>
                        </td>

                        <td><input type="text" name="year" class="form-control" value="<?= htmlspecialchars($row['year'], ENT_QUOTES, 'UTF-8') ?>"></td>
                        <td><input type="text" name="title" class="form-control" value="<?= htmlspecialchars($row['title'], ENT_QUOTES, 'UTF-8') ?>"></td>
                        <td><input type="text" name="link" class="form-control" value="<?= htmlspecialchars($row['link'], ENT_QUOTES, 'UTF-8') ?>"></td>

                        <td>
                            <?php if(!empty($row['pdf'])) { ?>
                                <a href="<?= htmlspecialchars($upload_path . $row['pdf'], ENT_QUOTES, 'UTF-8') ?>" target="_blank" class="btn btn-info btn-sm w-100 mb-1">View PDF</a><br>
                            <?php } ?>
                            <input type="file" name="new_pdf" class="form-control form-control-sm mb-1">
                            <input type="hidden" name="old_pdf" value="<?= htmlspecialchars($row['pdf'], ENT_QUOTES, 'UTF-8') ?>">
                            <?php if(!empty($row['pdf'])) { ?>
                                <button type="submit" name="action_remove_pdf" class="btn btn-warning btn-sm w-100 mt-1">Remove</button>
                            <?php } ?>
                        </td>

                        <td><textarea name="details" class="form-control" rows="2"><?= htmlspecialchars($row['details'], ENT_QUOTES, 'UTF-8') ?></textarea></td>

                        <td>
                            <button type="submit" name="update" class="btn btn-success btn-sm w-100 mb-1">Update</button>
                            <button type="submit" name="action_delete" class="btn btn-danger btn-sm w-100" onclick="return confirm('Confirm deletion?');">Delete</button>
                        </td>
                    </form>
                </tr>
                <?php } ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>

ZeroDay Forums Mini