Index of /home/htscrtms/newcrm.htshah.com/hslider
<?php
include('lib/db_connect.php');
function connectToGmailImap($email, $password) {
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$inbox = imap_open($hostname, $email, $password) or die('Cannot connect to Gmail: ' . imap_last_error());
return $inbox;
}
function fetchEmailsViaImap($email, $password, $fromDate, $toDate) {
$inbox = connectToGmailImap($email, $password);
// Format dates as DD-MMM-YYYY (e.g., 09-Apr-2025)
$from = date('d-M-Y', strtotime($fromDate));
$to = date('d-M-Y', strtotime($toDate));
$search = "SINCE \"$from\" BEFORE \"" . date('d-M-Y', strtotime($toDate . ' +1 day')) . "\"";
$emails = imap_search($inbox, $search);
if (!$emails) {
echo "No emails found.<br>";
return;
}
rsort($emails); // reverse sort to match your original code
foreach ($emails as $email_number) {
$overview = imap_fetch_overview($inbox, $email_number, 0)[0];
$message = imap_fetchbody($inbox, $email_number, 1.1);
if (empty($message)) {
$message = imap_fetchbody($inbox, $email_number, 1);
}
$subject = isset($overview->subject) ? imap_utf8($overview->subject) : "(No Subject)";
$date = date("Y-m-d H:i:s", strtotime($overview->date));
echo "Subject: $subject<br>";
echo "Date: $date<br>";
$jobNumber = null;
if (stripos($subject, 'Job number') !== false && stripos($subject, '_Success') !== false) {
if (preg_match('/Job number (\d+)_/', $subject, $matches)) {
$jobNumber = $matches[1];
echo "Matched Job Number: $jobNumber<br>";
}
$attachments = downloadAttachmentsImap($inbox, $email_number, $jobNumber);
foreach ($attachments as $filePath) {
$content = file_get_contents($filePath);
$boeNumber = extractBoeNumber($content);
echo "Extracted BOE Number: $boeNumber<br>";
updateDatabase($jobNumber, $boeNumber);
}
} else if (preg_match('/Bill of Entry No(\d{6,})Dt\d+/i', $subject, $matches)) {
$boeNumber = $matches[1];
echo "Matched BOE Number: $boeNumber<br>";
$attachments = downloadAttachmentsImap($inbox, $email_number, $boeNumber, true);
} else {
echo "Subject does not match known patterns.<br>";
}
echo "<hr>";
}
imap_close($inbox);
}
function downloadAttachmentsImap($inbox, $email_number, $jobNumber, $isUpload = false) {
$structure = imap_fetchstructure($inbox, $email_number);
$attachments = [];
$existingFiles = getExistingFileNames($jobNumber);
if (isset($structure->parts) && count($structure->parts)) {
for ($i = 0; $i < count($structure->parts); $i++) {
$part = $structure->parts[$i];
if ($part->ifdparameters) {
foreach ($part->dparameters as $object) {
if (strtolower($object->attribute) == 'filename') {
$filename = $object->value;
if (fileExistsInArray($filename, $existingFiles)) {
echo "Skipping duplicate file: $filename<br>";
continue;
}
$attachment = imap_fetchbody($inbox, $email_number, $i+1);
if ($part->encoding == 3) {
$attachment = base64_decode($attachment);
} elseif ($part->encoding == 4) {
$attachment = quoted_printable_decode($attachment);
}
$uniqueSuffix = time() . '_' . uniqid();
$filePath = "files/job_{$jobNumber}_{$uniqueSuffix}_" . $filename;
file_put_contents($filePath, $attachment);
$attachments[] = $filePath;
}
}
}
}
}
if ($isUpload) {
$allPaths = array_merge($existingFiles, $attachments);
updateDatabase($jobNumber, $allPaths, true);
}
return $attachments;
}
function fileExistsInArray($filename, $existingFiles) {
foreach ($existingFiles as $path) {
if (str_ends_with($path, $filename)) {
return true;
}
}
return false;
}
function updateDatabase($jobNumber, $allPaths, $isUpload = false) {
global $con;
if ($isUpload) {
$jsonPaths = $con->real_escape_string(json_encode($allPaths));
$query = "UPDATE tabl_importbooking SET file_paths = '$jsonPaths' WHERE thoka_no = $jobNumber";
} else {
$query = "UPDATE tabl_importbooking SET thoka_no=$allPaths WHERE htshah_no = $jobNumber";
}
echo $query;
if (mysqli_query($con, $query)) {
echo "Files updated for Job #$jobNumber<br>";
} else {
echo "Error updating record: " . mysqli_error($con);
}
}
function getExistingFileNames($jobNumber) {
global $con;
$result = mysqli_query($con, "SELECT file_paths FROM tabl_importbooking WHERE thoka_no = $jobNumber");
$existingNames = [];
if ($result && mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
if (!empty($row['file_paths'])) {
$paths = json_decode($row['file_paths'], true);
if (is_array($paths)) {
foreach ($paths as $path) {
$existingNames[] = $path; // just the filename
}
}
}
}
return $existingNames;
}
function extractBoeNumber($content) {
$lines = explode("\n", $content);
$boeNumber = null;
if (isset($lines[1])) {
$fields = explode(chr(29), $lines[1]); // Split by ASCII 29 (Group Separator)
for ($i = 0; $i < count($fields) - 1; $i++) {
// Match DDMMYYYY format
if (preg_match('/^\d{2}\d{2}\d{4}$/', $fields[$i])) {
$boeNumber = $fields[$i + 1];
break;
}
}
}
return $boeNumber;
}
$email = 'cse1@htshah.com';
$password = 'awzj inmk msgu npqw'; // Use App Password if 2FA is enabled
date_default_timezone_set('Asia/Kolkata');
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST["submit"])) {
$from = $_POST['from']; // Format: 2025-04-09
$to = $_POST['to'];
fetchEmailsViaImap($email, $password, $from, $to);
} else {
// Automatic mode for cron
$from = date('Y-m-d', strtotime('-3 days'));
$to = date('Y-m-d');
fetchEmailsViaImap($email, $password, $from, $to);
}
?>