FEATURE: Auto Populate Create Ticket when selecting a template, remove old ticket mail parser code

This commit is contained in:
johnnyq 2024-10-20 14:34:09 -04:00
parent 061e912123
commit c214c12d00
7 changed files with 64 additions and 1452 deletions

View File

@ -76,18 +76,14 @@ $total_tickets_closed = intval($row['total_tickets_closed']);
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addTicketModal">
<i class="fas fa-plus mr-2"></i>New Ticket
</button>
<?php if ($num_rows[0] > 0) { ?>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button>
<div class="dropdown-menu">
<a class="dropdown-item text-dark" href="#" data-toggle="modal" data-target="#addTicketFromTemplateModal">
<i class="fa fa-fw fa-plus mr-2"></i>From Template
<a class="dropdown-item text-dark" href="#" data-toggle="modal" data-target="#exportTicketModal">
<i class="fa fa-fw fa-download mr-2"></i>Export
</a>
<?php if ($num_rows[0] > 0) { ?>
<div class="dropdown-divider"></div>
<a class="dropdown-item text-dark" href="#" data-toggle="modal" data-target="#exportTicketModal">
<i class="fa fa-fw fa-download mr-2"></i>Export
</a>
<?php } ?>
</div>
<?php } ?>
</div>
</div>
</div>
@ -345,7 +341,6 @@ $total_tickets_closed = intval($row['total_tickets_closed']);
<?php
require_once "ticket_add_modal.php";
require_once "ticket_add_from_template_modal.php";
require_once "client_ticket_export_modal.php";

View File

@ -1,512 +0,0 @@
<?php
/*
* CRON - Email Parser
* Process emails and create/update tickets
*/
// Set working directory to the directory this cron script lives at.
chdir(dirname(__FILE__));
// Autoload Composer dependencies
require_once __DIR__ . '/plugins/php-imap/vendor/autoload.php';
// Get ITFlow config & helper functions
require_once "config.php";
// Set Timezone
require_once "inc_set_timezone.php";
require_once "functions.php";
// Get settings for the "default" company
require_once "get_settings.php";
$config_ticket_prefix = sanitizeInput($config_ticket_prefix);
$config_ticket_from_name = sanitizeInput($config_ticket_from_name);
$config_ticket_email_parse_unknown_senders = intval($row['config_ticket_email_parse_unknown_senders']);
// Get company name & phone & timezone
$sql = mysqli_query($mysqli, "SELECT * FROM companies, settings WHERE companies.company_id = settings.company_id AND companies.company_id = 1");
$row = mysqli_fetch_array($sql);
$company_name = sanitizeInput($row['company_name']);
$company_phone = sanitizeInput(formatPhoneNumber($row['company_phone']));
// Check setting enabled
if ($config_ticket_email_parse == 0) {
exit("Email Parser: Feature is not enabled - check Settings > Ticketing > Email-to-ticket parsing. See https://docs.itflow.org/ticket_email_parse -- Quitting..");
}
$argv = $_SERVER['argv'];
// Check Cron Key
if ($argv[1] !== $config_cron_key) {
exit("Cron Key invalid -- Quitting..");
}
// Get system temp directory
$temp_dir = sys_get_temp_dir();
// Create the path for the lock file using the temp directory
$lock_file_path = "{$temp_dir}/itflow_email_parser_{$installation_id}.lock";
// Check for lock file to prevent concurrent script runs
if (file_exists($lock_file_path)) {
$file_age = time() - filemtime($lock_file_path);
// If file is older than 3 minutes (180 seconds), delete and continue
if ($file_age > 300) {
unlink($lock_file_path);
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Cron-Email-Parser', log_action = 'Delete', log_description = 'Cron Email Parser detected a lock file was present but was over 10 minutes old so it removed it'");
} else {
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Cron-Email-Parser', log_action = 'Locked', log_description = 'Cron Email Parser attempted to execute but was already executing, so instead it terminated.'");
exit("Script is already running. Exiting.");
}
}
// Create a lock file
file_put_contents($lock_file_path, "Locked");
// Webklex PHP-IMAP
use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Message\Attachment;
// Allowed attachment extensions
$allowed_extensions = array('jpg', 'jpeg', 'gif', 'png', 'webp', 'pdf', 'txt', 'md', 'doc', 'docx', 'csv', 'xls', 'xlsx', 'xlsm', 'zip', 'tar', 'gz');
// Function to raise a new ticket for a given contact and email them confirmation (if configured)
function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file) {
global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_ticket_client_general_notifications, $config_ticket_new_ticket_notification_email, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $config_smtp_host, $config_smtp_port, $config_smtp_encryption, $config_smtp_username, $config_smtp_password, $allowed_extensions;
$ticket_number_sql = mysqli_fetch_array(mysqli_query($mysqli, "SELECT config_ticket_next_number FROM settings WHERE company_id = 1"));
$ticket_number = intval($ticket_number_sql['config_ticket_next_number']);
$new_config_ticket_next_number = $ticket_number + 1;
mysqli_query($mysqli, "UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = 1");
// Clean up the message
$message = trim($message); // Remove leading/trailing whitespace
$message = preg_replace('/\s+/', ' ', $message); // Replace multiple spaces with a single space
$message = nl2br($message); // Convert newlines to <br>
// Wrap the message in a div with controlled line height
$message = "<i>Email from: <b>$contact_name</b> &lt;$contact_email&gt; at $date:-</i> <br><br><div style='line-height:1.5;'>$message</div>";
$ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix);
$subject_esc = mysqli_real_escape_string($mysqli, $subject);
$message_esc = mysqli_real_escape_string($mysqli, $message);
$contact_email_esc = mysqli_real_escape_string($mysqli, $contact_email);
$client_id_esc = intval($client_id);
//Generate a unique URL key for clients to access
$url_key = randomString(156);
mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$ticket_prefix_esc', ticket_number = $ticket_number, ticket_subject = '$subject_esc', ticket_details = '$message_esc', ticket_priority = 'Low', ticket_status = 1, ticket_created_by = 0, ticket_contact_id = $contact_id, ticket_url_key = '$url_key', ticket_client_id = $client_id_esc");
$id = mysqli_insert_id($mysqli);
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Ticket', log_action = 'Create', log_description = 'Email parser: Client contact $contact_email_esc created ticket $ticket_prefix_esc$ticket_number ($subject_esc) ($id)', log_client_id = $client_id_esc");
mkdirMissing('uploads/tickets/');
$att_dir = "uploads/tickets/" . $id . "/";
mkdirMissing($att_dir);
rename("uploads/tmp/{$original_message_file}", "{$att_dir}/{$original_message_file}");
$original_message_file_esc = mysqli_real_escape_string($mysqli, $original_message_file);
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = 'Original-parsed-email.eml', ticket_attachment_reference_name = '$original_message_file_esc', ticket_attachment_ticket_id = $id");
foreach ($attachments as $attachment) {
$att_name = $attachment->getName();
$att_extarr = explode('.', $att_name);
$att_extension = strtolower(end($att_extarr));
if (in_array($att_extension, $allowed_extensions)) {
$att_saved_filename = md5(uniqid(rand(), true)) . '.' . $att_extension;
$att_saved_path = $att_dir . $att_saved_filename;
$attachment->save($att_dir); // Save the attachment to the directory
rename($att_dir . $attachment->getName(), $att_saved_path); // Rename the saved file to the hashed name
$ticket_attachment_name = sanitizeInput($att_name);
$ticket_attachment_reference_name = sanitizeInput($att_saved_filename);
$ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_name);
$ticket_attachment_reference_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_reference_name);
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_ticket_id = $id");
} else {
$ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name);
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Ticket', log_action = 'Update', log_description = 'Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $contact_email_esc for ticket $ticket_prefix_esc$ticket_number', log_client_id = $client_id_esc");
}
}
$data = [];
if ($config_ticket_client_general_notifications == 1) {
$subject_email = "Ticket created - [$config_ticket_prefix$ticket_number] - $subject";
$body = "<i style='color: #808080'>##- Please type your reply above this line -##</i><br><br>Hello $contact_name,<br><br>Thank you for your email. A ticket regarding \"$subject\" has been automatically created for you.<br><br>Ticket: $config_ticket_prefix$ticket_number<br>Subject: $subject<br>Status: New<br>https://$config_base_url/portal/ticket.php?id=$id<br><br>--<br>$company_name - Support<br>$config_ticket_from_email<br>$company_phone";
$data[] = [
'from' => $config_ticket_from_email,
'from_name' => $config_ticket_from_name,
'recipient' => $contact_email,
'recipient_name' => $contact_name,
'subject' => mysqli_real_escape_string($mysqli, $subject_email),
'body' => mysqli_real_escape_string($mysqli, $body)
];
}
if ($config_ticket_new_ticket_notification_email) {
if ($client_id == 0){
$client_name = "Guest";
} else {
$client_sql = mysqli_query($mysqli, "SELECT client_name FROM clients WHERE client_id = $client_id");
$client_row = mysqli_fetch_array($client_sql);
$client_name = sanitizeInput($client_row['client_name']);
}
$email_subject = "$config_app_name - New Ticket - $client_name: $subject";
$email_body = "Hello, <br><br>This is a notification that a new ticket has been raised in ITFlow. <br>Client: $client_name<br>Priority: Low (email parsed)<br>Link: https://$config_base_url/ticket.php?ticket_id=$id <br><br>--------------------------------<br><br><b>$subject</b><br>$message";
$data[] = [
'from' => $config_ticket_from_email,
'from_name' => $config_ticket_from_name,
'recipient' => $config_ticket_new_ticket_notification_email,
'recipient_name' => $config_ticket_from_name,
'subject' => mysqli_real_escape_string($mysqli, $email_subject),
'body' => mysqli_real_escape_string($mysqli, $email_body)
];
}
addToMailQueue($mysqli, $data);
// Custom action/notif handler
customAction('ticket_create', $id);
return true;
}
// Add Reply Function
function addReply($from_email, $date, $subject, $ticket_number, $message, $attachments) {
global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $config_smtp_host, $config_smtp_port, $config_smtp_encryption, $config_smtp_username, $config_smtp_password, $allowed_extensions;
$ticket_reply_type = 'Client';
// Clean up the message
$message_parts = explode("##- Please type your reply above this line -##", $message);
$message_body = $message_parts[0];
$message_body = trim($message_body); // Remove leading/trailing whitespace
$message_body = preg_replace('/\r\n|\r|\n/', ' ', $message_body); // Replace newlines with a space
$message_body = nl2br($message_body); // Convert remaining newlines to <br>
// Wrap the message in a div with controlled line height
$message = "<i>Email from: $from_email at $date:-</i> <br><br><div style='line-height:1.5;'>$message_body</div>";
$ticket_number_esc = intval($ticket_number);
$message_esc = mysqli_real_escape_string($mysqli, $message);
$from_email_esc = mysqli_real_escape_string($mysqli, $from_email);
$row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT ticket_id, ticket_subject, ticket_status, ticket_contact_id, ticket_client_id, contact_email, client_name
FROM tickets
LEFT JOIN contacts on tickets.ticket_contact_id = contacts.contact_id
LEFT JOIN clients on tickets.ticket_client_id = clients.client_id
WHERE ticket_number = $ticket_number_esc LIMIT 1"));
if ($row) {
$ticket_id = intval($row['ticket_id']);
$ticket_subject = sanitizeInput($row['ticket_subject']);
$ticket_status = sanitizeInput($row['ticket_status']);
$ticket_reply_contact = intval($row['ticket_contact_id']);
$ticket_contact_email = sanitizeInput($row['contact_email']);
$client_id = intval($row['ticket_client_id']);
$client_name = sanitizeInput($row['client_name']);
if ($ticket_status == 5) {
$config_ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix);
$ticket_number_esc = mysqli_real_escape_string($mysqli, $ticket_number);
$ticket_id_esc = intval($ticket_id);
$client_id_esc = intval($client_id);
mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = 'Email parser: $from_email attempted to re-open ticket $config_ticket_prefix_esc$ticket_number_esc (ID $ticket_id_esc) - check inbox manually to see email', notification_action = 'ticket.php?ticket_id=$ticket_id_esc', notification_client_id = $client_id_esc");
$email_subject = "Action required: This ticket is already closed";
$email_body = "Hi there, <br><br>You've tried to reply to a ticket that is closed - we won't see your response. <br><br>Please raise a new ticket by sending a new e-mail to our support address below. <br><br>--<br>$company_name - Support<br>$config_ticket_from_email<br>$company_phone";
$data = [
[
'from' => $config_ticket_from_email,
'from_name' => $config_ticket_from_name,
'recipient' => $from_email,
'recipient_name' => $from_email,
'subject' => mysqli_real_escape_string($mysqli, $email_subject),
'body' => mysqli_real_escape_string($mysqli, $email_body)
]
];
addToMailQueue($mysqli, $data);
return true;
}
if (empty($ticket_contact_email) || $ticket_contact_email !== $from_email) {
$from_email_esc = mysqli_real_escape_string($mysqli, $from_email);
$row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE contact_email = '$from_email_esc' AND contact_client_id = $client_id LIMIT 1"));
if ($row) {
$ticket_reply_contact = intval($row['contact_id']);
} else {
$ticket_reply_type = 'Internal';
$ticket_reply_contact = '0';
$message = "<b>WARNING: Contact email mismatch</b><br>$message";
$message_esc = mysqli_real_escape_string($mysqli, $message);
}
}
mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$message_esc', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $ticket_reply_contact, ticket_reply_ticket_id = $ticket_id");
$reply_id = mysqli_insert_id($mysqli);
mkdirMissing('uploads/tickets/');
foreach ($attachments as $attachment) {
$att_name = $attachment->getName();
$att_extarr = explode('.', $att_name);
$att_extension = strtolower(end($att_extarr));
if (in_array($att_extension, $allowed_extensions)) {
$att_saved_filename = md5(uniqid(rand(), true)) . '.' . $att_extension;
$att_saved_path = "uploads/tickets/" . $ticket_id . "/" . $att_saved_filename;
$attachment->save("uploads/tickets/" . $ticket_id); // Save the attachment to the directory
rename("uploads/tickets/" . $ticket_id . "/" . $attachment->getName(), $att_saved_path); // Rename the saved file to the hashed name
$ticket_attachment_name = sanitizeInput($att_name);
$ticket_attachment_reference_name = sanitizeInput($att_saved_filename);
$ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_name);
$ticket_attachment_reference_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_reference_name);
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id");
} else {
$ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name);
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Ticket', log_action = 'Update', log_description = 'Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $from_email_esc for ticket $config_ticket_prefix$ticket_number_esc', log_client_id = $client_id");
}
}
$ticket_assigned_to = mysqli_query($mysqli, "SELECT ticket_assigned_to FROM tickets WHERE ticket_id = $ticket_id LIMIT 1");
if ($ticket_assigned_to) {
$row = mysqli_fetch_array($ticket_assigned_to);
$ticket_assigned_to = intval($row['ticket_assigned_to']);
if ($ticket_assigned_to) {
$tech_sql = mysqli_query($mysqli, "SELECT user_email, user_name FROM users WHERE user_id = $ticket_assigned_to LIMIT 1");
$tech_row = mysqli_fetch_array($tech_sql);
$tech_email = sanitizeInput($tech_row['user_email']);
$tech_name = sanitizeInput($tech_row['user_name']);
$email_subject = "$config_app_name - Ticket updated - [$config_ticket_prefix$ticket_number] $ticket_subject";
$email_body = "Hello $tech_name,<br><br>A new reply has been added to the below ticket, check ITFlow for full details.<br><br>Client: $client_name<br>Ticket: $config_ticket_prefix$ticket_number<br>Subject: $ticket_subject<br><br>https://$config_base_url/ticket.php?ticket_id=$ticket_id";
$data = [
[
'from' => $config_ticket_from_email,
'from_name' => $config_ticket_from_name,
'recipient' => $tech_email,
'recipient_name' => $tech_name,
'subject' => mysqli_real_escape_string($mysqli, $email_subject),
'body' => mysqli_real_escape_string($mysqli, $email_body)
]
];
addToMailQueue($mysqli, $data);
}
}
mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 2, ticket_resolved_at = NULL WHERE ticket_id = $ticket_id AND ticket_client_id = $client_id LIMIT 1");
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Ticket', log_action = 'Update', log_description = 'Email parser: Client contact $from_email_esc updated ticket $config_ticket_prefix$ticket_number_esc ($subject)', log_client_id = $client_id");
customAction('ticket_reply_client', $ticket_id);
return true;
} else {
return false;
}
}
// Function to create a folder in the mailbox if it doesn't exist
function createMailboxFolder($client, $folderName) {
try {
// Attempt to get the folder
$folder = $client->getFolder($folderName);
// If the folder doesn't exist, create it
if (!$folder) {
$client->createFolder($folderName);
echo "Folder '$folderName' created successfully.";
// Disconnect and reconnect to ensure the server registers the new folder
$client->disconnect();
sleep(1); // Pause before reconnecting
$client->connect();
} else {
echo "Folder '$folderName' already exists.";
}
// Re-fetch the folder after reconnecting
return $client->getFolder($folderName);
} catch (Exception $e) {
echo "Error creating folder '$folderName': " . $e->getMessage();
return null;
}
}
// Function to subscribe to a folder in the mailbox
function subscribeMailboxFolder($folder) {
if ($folder) {
try {
// Subscribe to the folder
$folder->subscribe();
echo "Folder '{$folder->name}' subscribed successfully.";
} catch (Exception $e) {
echo "Error subscribing to folder '{$folder->name}': " . $e->getMessage();
}
} else {
echo "Cannot subscribe to folder because it does not exist.";
}
}
// Initialize the client manager and create the client
$clientManager = new ClientManager();
$client = $clientManager->make([
'host' => $config_imap_host,
'port' => $config_imap_port,
'encryption' => $config_imap_encryption,
'validate_cert' => true,
'username' => $config_imap_username,
'password' => $config_imap_password,
'protocol' => 'imap'
]);
// Connect to the IMAP server
$client->connect();
// Create the "ITFlow" mailbox folder if it doesn't exist
$folder = createMailboxFolder($client, 'ITFlow');
// Subscribe to the "ITFlow" mailbox folder
subscribeMailboxFolder($folder);
// Possible names for the inbox folder
$inboxNames = ['Inbox', 'INBOX', 'inbox'];
// Function to get the correct inbox folder
function getInboxFolder($client, $inboxNames) {
foreach ($inboxNames as $name) {
try {
$folder = $client->getFolder($name);
if ($folder) {
return $folder;
}
} catch (Exception $e) {
// Continue to the next name if the current one fails
continue;
}
}
throw new Exception("No inbox folder found.");
}
try {
$inbox = getInboxFolder($client, $inboxNames);
$messages = $inbox->query()->unseen()->get();
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
if ($messages->count() > 0) {
foreach ($messages as $message) {
$email_processed = false;
// Save original message
mkdirMissing('uploads/tmp/');
$original_message_file = "processed-eml-" . randomString(200) . ".eml";
$eml_content = json_decode(json_encode($message->getHeader()), true)['raw'];
$eml_content .= $message->getRawBody();
file_put_contents("uploads/tmp/{$original_message_file}", $eml_content);
$from_address = $message->getFrom();
$from_name = sanitizeInput($from_address[0]->personal ?? 'Unknown');
$from_email = sanitizeInput($from_address[0]->mail ?? 'itflow-guest@example.com');
$from_domain = explode("@", $from_email);
$from_domain = sanitizeInput(end($from_domain));
$subject = sanitizeInput($message->getSubject() ?? 'No Subject');
$date = sanitizeInput($message->getDate() ?? date('Y-m-d H:i:s'));
$message_body = $message->getHtmlBody() ?? '';
if (empty($message_body)) {
$text_body = $message->getTextBody() ?? '';
$message_body = nl2br(htmlspecialchars($text_body));
}
if (preg_match("/\[$config_ticket_prefix\d+\]/", $subject, $ticket_number)) {
preg_match('/\d+/', $ticket_number[0], $ticket_number);
$ticket_number = intval($ticket_number[0]);
if (addReply($from_email, $date, $subject, $ticket_number, $message_body, $message->getAttachments())) {
$email_processed = true;
}
} else {
$from_email_esc = mysqli_real_escape_string($mysqli, $from_email);
$any_contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from_email_esc' LIMIT 1");
$row = mysqli_fetch_array($any_contact_sql);
if ($row) {
$contact_name = sanitizeInput($row['contact_name']);
$contact_id = intval($row['contact_id']);
$contact_email = sanitizeInput($row['contact_email']);
$client_id = intval($row['contact_client_id']);
if (addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $message->getAttachments(), $original_message_file)) {
$email_processed = true;
}
} else {
$from_domain_esc = mysqli_real_escape_string($mysqli, $from_domain);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM domains WHERE domain_name = '$from_domain_esc' LIMIT 1"));
if ($row && $from_domain == $row['domain_name']) {
$client_id = intval($row['domain_client_id']);
$password = password_hash(randomString(), PASSWORD_DEFAULT);
$contact_name = $from_name;
$contact_email = $from_email;
mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '".mysqli_real_escape_string($mysqli, $contact_name)."', contact_email = '".mysqli_real_escape_string($mysqli, $contact_email)."', contact_notes = 'Added automatically via email parsing.', contact_password_hash = '$password', contact_client_id = $client_id");
$contact_id = mysqli_insert_id($mysqli);
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Contact', log_action = 'Create', log_description = 'Email parser: created contact ".mysqli_real_escape_string($mysqli, $contact_name)."', log_client_id = $client_id");
customAction('contact_create', $ticket_id);
if (addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $message->getAttachments(), $original_message_file)) {
$email_processed = true;
}
} elseif ($config_ticket_email_parse_unknown_senders) {
// Parse even if the sender is unknown
$bad_from_pattern = "/daemon|postmaster/i";
if (!(preg_match($bad_from_pattern, $from_email))) {
if (addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $message->getAttachments(), $original_message_file)) {
$email_processed = true;
}
}
}
}
}
if ($email_processed) {
$message->setFlag(['Seen']);
$message->move('ITFlow');
} else {
echo "Failed to process email - flagging for manual review.";
$message->setFlag(['Flagged']);
}
if (file_exists("uploads/tmp/{$original_message_file}")) {
unlink("uploads/tmp/{$original_message_file}");
}
}
}
$client->expunge();
$client->disconnect();
// Remove the lock file
unlink($lock_file_path);

View File

@ -1,559 +0,0 @@
<?php
/*
* CRON - Email Parser
* Process emails and create/update tickets
*/
/*
TODO:
- Process unregistered contacts/clients into an inbox to allow a ticket to be created/ignored
- Support for authenticating with OAuth
- Separate Mailbox Account for tickets 2022-12-14 - JQ
*/
// Set working directory to the directory this cron script lives at.
chdir(dirname(__FILE__));
// Get ITFlow config & helper functions
require_once "config.php";
// Set Timezone
require_once "inc_set_timezone.php";
require_once "functions.php";
// Get settings for the "default" company
require_once "get_settings.php";
$config_ticket_prefix = sanitizeInput($config_ticket_prefix);
$config_ticket_from_name = sanitizeInput($config_ticket_from_name);
// Get company name & phone & timezone
$sql = mysqli_query($mysqli, "SELECT * FROM companies, settings WHERE companies.company_id = settings.company_id AND companies.company_id = 1");
$row = mysqli_fetch_array($sql);
$company_name = sanitizeInput($row['company_name']);
$company_phone = sanitizeInput(formatPhoneNumber($row['company_phone']));
// Check setting enabled
if ($config_ticket_email_parse == 0) {
exit("Email Parser: Feature is not enabled - check Settings > Ticketing > Email-to-ticket parsing. See https://docs.itflow.org/ticket_email_parse -- Quitting..");
}
$argv = $_SERVER['argv'];
// Check Cron Key
if ( $argv[1] !== $config_cron_key ) {
exit("Cron Key invalid -- Quitting..");
}
// Check IMAP extension works/installed
if (!function_exists('imap_open')) {
exit("Email Parser: PHP IMAP extension is not installed. See https://docs.itflow.org/ticket_email_parse -- Quitting..");
}
// Check mailparse extension works/installed
if (!function_exists('mailparse_msg_parse_file')) {
exit("Email Parser: PHP mailparse extension is not installed. See https://docs.itflow.org/ticket_email_parse -- Quitting..");
}
// Get system temp directory
$temp_dir = sys_get_temp_dir();
// Create the path for the lock file using the temp directory
$lock_file_path = "{$temp_dir}/itflow_legacy_email_parser_{$installation_id}.lock";
// Check for lock file to prevent concurrent script runs
if (file_exists($lock_file_path)) {
$file_age = time() - filemtime($lock_file_path);
// If file is older than 3 minutes (180 seconds), delete and continue
if ($file_age > 300) {
unlink($lock_file_path);
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Cron-Email-Parser', log_action = 'Delete', log_description = 'Cron Email Parser detected a lock file was present but was over 10 minutes old so it removed it'");
} else {
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Cron-Email-Parser', log_action = 'Locked', log_description = 'Cron Email Parser attempted to execute but was already executing, so instead it terminated.'");
exit("Script is already running. Exiting.");
}
}
// Create a lock file
file_put_contents($lock_file_path, "Locked");
// PHP Mail Parser
use PhpMimeMailParser\Parser;
require_once "plugins/php-mime-mail-parser/src/Contracts/CharsetManager.php";
require_once "plugins/php-mime-mail-parser/src/Contracts/Middleware.php";
require_once "plugins/php-mime-mail-parser/src/Attachment.php";
require_once "plugins/php-mime-mail-parser/src/Charset.php";
require_once "plugins/php-mime-mail-parser/src/Exception.php";
require_once "plugins/php-mime-mail-parser/src/Middleware.php";
require_once "plugins/php-mime-mail-parser/src/MiddlewareStack.php";
require_once "plugins/php-mime-mail-parser/src/MimePart.php";
require_once "plugins/php-mime-mail-parser/src/Parser.php";
// Allowed attachment extensions
$allowed_extensions = array('jpg', 'jpeg', 'gif', 'png', 'webp', 'pdf', 'txt', 'md', 'doc', 'docx', 'csv', 'xls', 'xlsx', 'xlsm', 'zip', 'tar', 'gz');
// Function to raise a new ticket for a given contact and email them confirmation (if configured)
function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file) {
// Access global variables
global $mysqli,$config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_ticket_client_general_notifications, $config_ticket_new_ticket_notification_email, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $config_smtp_host, $config_smtp_port, $config_smtp_encryption, $config_smtp_username, $config_smtp_password, $allowed_extensions;
// Get the next Ticket Number and add 1 for the new ticket number
$ticket_number_sql = mysqli_fetch_array(mysqli_query($mysqli, "SELECT config_ticket_next_number FROM settings WHERE company_id = 1"));
$ticket_number = intval($ticket_number_sql['config_ticket_next_number']);
$new_config_ticket_next_number = $ticket_number + 1;
mysqli_query($mysqli, "UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = 1");
// Prep ticket details
$message = nl2br($message);
$message = mysqli_escape_string($mysqli, "<i>Email from: $contact_email at $date:-</i> <br><br>$message");
//Generate a unique URL key for clients to access
$url_key = randomString(156);
mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$config_ticket_prefix', ticket_number = $ticket_number, ticket_subject = '$subject', ticket_details = '$message', ticket_priority = 'Low', ticket_status = 1, ticket_created_by = 0, ticket_contact_id = $contact_id, ticket_url_key = '$url_key', ticket_client_id = $client_id");
$id = mysqli_insert_id($mysqli);
// Logging
echo "Created new ticket.<br>";
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Ticket', log_action = 'Create', log_description = 'Email parser: Client contact $contact_email created ticket $config_ticket_prefix$ticket_number ($subject) ($id)', log_client_id = $client_id");
// -- Process attachments (after ticket is logged as created because we save to the folder named after the ticket ID) --
mkdirMissing('uploads/tickets/'); // Create tickets dir
// Setup directory for this ticket ID
$att_dir = "uploads/tickets/" . $id . "/";
mkdirMissing($att_dir);
// Save original email message as ticket attachment
rename("uploads/tmp/{$original_message_file}", "{$att_dir}/{$original_message_file}");
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = 'Original-parsed-email.eml', ticket_attachment_reference_name = '$original_message_file', ticket_attachment_ticket_id = $id");
// Process each attachment
foreach ($attachments as $attachment) {
// Get name and extension
$att_name = $attachment->getFileName();
$att_extarr = explode('.', $att_name);
$att_extension = strtolower(end($att_extarr));
// Check the extension is allowed
if (in_array($att_extension, $allowed_extensions)) {
// Save attachment with a random name
$att_saved_path = $attachment->save($att_dir, Parser::ATTACHMENT_RANDOM_FILENAME);
// Access the random name to add into the database (this won't work on Windows)
$att_tmparr = explode($att_dir, $att_saved_path);
$ticket_attachment_name = sanitizeInput($att_name);
$ticket_attachment_reference_name = sanitizeInput(end($att_tmparr));
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name', ticket_attachment_reference_name = '$ticket_attachment_reference_name', ticket_attachment_ticket_id = $id");
} else {
$ticket_attachment_name = sanitizeInput($att_name);
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Ticket', log_action = 'Update', log_description = 'Email parser: Blocked attachment $ticket_attachment_name from Client contact $contact_email for ticket $config_ticket_prefix$ticket_number', log_client_id = $client_id");
}
}
$data = [];
// E-mail client notification that ticket has been created
if ($config_ticket_client_general_notifications == 1) {
$subject_email = "Ticket created - [$config_ticket_prefix$ticket_number] - $subject";
$body = "<i style=\'color: #808080\'>##- Please type your reply above this line -##</i><br><br>Hello $contact_name,<br><br>Thank you for your email. A ticket regarding \"$subject\" has been automatically created for you.<br><br>Ticket: $config_ticket_prefix$ticket_number<br>Subject: $subject<br>Status: New<br>https://$config_base_url/portal/ticket.php?id=$id<br><br>--<br>$company_name - Support<br>$config_ticket_from_email<br>$company_phone";
$data[] = [
'from' => $config_ticket_from_email,
'from_name' => $config_ticket_from_name,
'recipient' => $contact_email,
'recipient_name' => $contact_name,
'subject' => $subject_email,
'body' => $body
];
}
// Notify agent DL of the new ticket, if populated with a valid email
if ($config_ticket_new_ticket_notification_email) {
// Get client info
$client_sql = mysqli_query($mysqli, "SELECT client_name FROM clients WHERE client_id = $client_id");
$client_row = mysqli_fetch_array($client_sql);
$client_name = sanitizeInput($client_row['client_name']);
$email_subject = "$config_app_name - New Ticket - $client_name: $subject";
$email_body = "Hello, <br><br>This is a notification that a new ticket has been raised in ITFlow. <br>Client: $client_name<br>Priority: Low (email parsed)<br>Link: https://$config_base_url/ticket.php?ticket_id=$id <br><br>--------------------------------<br><br><b>$subject</b><br>$details";
$data[] = [
'from' => $config_ticket_from_email,
'from_name' => $config_ticket_from_name,
'recipient' => $config_ticket_new_ticket_notification_email,
'recipient_name' => $config_ticket_from_name,
'subject' => $email_subject,
'body' => $email_body
];
}
addToMailQueue($mysqli, $data);
return true;
}
// End Add Ticket Function
// Add Reply Function
function addReply($from_email, $date, $subject, $ticket_number, $message, $attachments) {
// Add email as a comment/reply to an existing ticket
// Access global variables
global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $config_smtp_host, $config_smtp_port, $config_smtp_encryption, $config_smtp_username, $config_smtp_password, $allowed_extensions;
// Set default reply type
$ticket_reply_type = 'Client';
// Capture just the latest/most recent email reply content
// based off the "##- Please type your reply above this line -##" line that we prepend the outgoing emails with
$message = explode("##- Please type your reply above this line -##", $message);
$message = nl2br($message[0]);
$message = mysqli_escape_string($mysqli, "<i>Email from: $from_email at $date:-</i> <br><br>$message");
// Lookup the ticket ID
$row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT ticket_id, ticket_subject, ticket_status, ticket_contact_id, ticket_client_id, contact_email, client_name
FROM tickets
LEFT JOIN contacts on tickets.ticket_contact_id = contacts.contact_id
LEFT JOIN clients on tickets.ticket_client_id = clients.client_id
WHERE ticket_number = $ticket_number LIMIT 1"));
if ($row) {
// Get ticket details
$ticket_id = intval($row['ticket_id']);
$ticket_subject = sanitizeInput($row['ticket_subject']);
$ticket_status = sanitizeInput($row['ticket_status']);
$ticket_reply_contact = intval($row['ticket_contact_id']);
$ticket_contact_email = sanitizeInput($row['contact_email']);
$client_id = intval($row['ticket_client_id']);
$client_name = sanitizeInput($row['client_name']);
// Check ticket isn't closed - tickets can't be re-opened
if ($ticket_status == 5) {
mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = 'Email parser: $from_email attempted to re-open ticket $config_ticket_prefix$ticket_number (ID $ticket_id) - check inbox manually to see email', notification_action = 'ticket.php?ticket_id=$ticket_id', notification_client_id = $client_id");
$email_subject = "Action required: This ticket is already closed";
$email_body = "Hi there, <br><br>You\'ve tried to reply to a ticket that is closed - we won\'t see your response. <br><br>Please raise a new ticket by sending a fresh e-mail to our support address below. <br><br>--<br>$company_name - Support<br>$config_ticket_from_email<br>$company_phone";
$data = [
[
'from' => $config_ticket_from_email,
'from_name' => $config_ticket_from_name,
'recipient' => $from_email,
'recipient_name' => $from_email,
'subject' => $email_subject,
'body' => $email_body
]
];
addToMailQueue($mysqli, $data);
return true;
}
// Check WHO replied (was it the owner of the ticket or someone else on CC?)
if (empty($ticket_contact_email) || $ticket_contact_email !== $from_email) {
// It wasn't the contact currently assigned to the ticket, check if it's another registered contact for that client
$row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE contact_email = '$from_email' AND contact_client_id = $client_id LIMIT 1"));
if ($row) {
// Contact is known - we can keep the reply type as client
$ticket_reply_contact = intval($row['contact_id']);
} else {
// Mark the reply as internal as we don't recognise the contact (so the actual contact doesn't see it, and the tech can edit/delete if needed)
$ticket_reply_type = 'Internal';
$ticket_reply_contact = '0';
$message = "<b>WARNING: Contact email mismatch</b><br>$message"; // Add a warning at the start of the message - for the techs benefit (think phishing/scams)
}
}
// Add the comment
mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$message', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $ticket_reply_contact, ticket_reply_ticket_id = $ticket_id");
$reply_id = mysqli_insert_id($mysqli);
// Process attachments
mkdirMissing('uploads/tickets/');
foreach ($attachments as $attachment) {
// Get name and extension
$att_name = $attachment->getFileName();
$att_extarr = explode('.', $att_name);
$att_extension = strtolower(end($att_extarr));
// Check the extension is allowed
if (in_array($att_extension, $allowed_extensions)) {
// Setup directory for this ticket ID
$att_dir = "uploads/tickets/" . $ticket_id . "/";
mkdirMissing($att_dir);
// Save attachment with a random name
$att_saved_path = $attachment->save($att_dir, Parser::ATTACHMENT_RANDOM_FILENAME);
// Access the random name to add into the database (this won't work on Windows)
$att_tmparr = explode($att_dir, $att_saved_path);
$ticket_attachment_name = sanitizeInput($att_name);
$ticket_attachment_reference_name = sanitizeInput(end($att_tmparr));
mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name', ticket_attachment_reference_name = '$ticket_attachment_reference_name', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id");
} else {
$ticket_attachment_name = sanitizeInput($att_name);
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Ticket', log_action = 'Update', log_description = 'Email parser: Blocked attachment $ticket_attachment_name from Client contact $from_email for ticket $config_ticket_prefix$ticket_number', log_client_id = $client_id");
}
}
// E-mail techs assigned to the ticket to notify them of the reply
$ticket_assigned_to = mysqli_query($mysqli, "SELECT ticket_assigned_to FROM tickets WHERE ticket_id = $ticket_id LIMIT 1");
if ($ticket_assigned_to) {
$row = mysqli_fetch_array($ticket_assigned_to);
$ticket_assigned_to = intval($row['ticket_assigned_to']);
if ($ticket_assigned_to) {
// Get tech details
$tech_sql = mysqli_query($mysqli, "SELECT user_email, user_name FROM users WHERE user_id = $ticket_assigned_to LIMIT 1");
$tech_row = mysqli_fetch_array($tech_sql);
$tech_email = sanitizeInput($tech_row['user_email']);
$tech_name = sanitizeInput($tech_row['user_name']);
$email_subject = "$config_app_name - Ticket updated - [$config_ticket_prefix$ticket_number] $ticket_subject";
$email_body = "Hello $tech_name,<br><br>A new reply has been added to the below ticket, check ITFlow for full details.<br><br>Client: $client_name<br>Ticket: $config_ticket_prefix$ticket_number<br>Subject: $ticket_subject<br><br>https://$config_base_url/ticket.php?ticket_id=$ticket_id";
$data = [
[
'from' => $config_ticket_from_email,
'from_name' => $config_ticket_from_name,
'recipient' => $tech_email,
'recipient_name' => $tech_name,
'subject' => $email_subject,
'body' => $email_body
]
];
addToMailQueue($mysqli, $data);
}
}
// Update Ticket Last Response Field & set ticket to open as client has replied
mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 2, ticket_resolved_at = NULL WHERE ticket_id = $ticket_id AND ticket_client_id = $client_id LIMIT 1");
echo "Updated existing ticket.<br>";
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Ticket', log_action = 'Update', log_description = 'Email parser: Client contact $from_email updated ticket $config_ticket_prefix$ticket_number ($subject)', log_client_id = $client_id");
return true;
} else {
// Invalid ticket number
return false;
}
}
// END ADD REPLY FUNCTION -------------------------------------------------
// Prepare connection string with encryption (TLS/SSL/<blank>)
$imap_mailbox = "$config_imap_host:$config_imap_port/imap/$config_imap_encryption";
// Connect to host via IMAP
$imap = imap_open("{{$imap_mailbox}}INBOX", $config_imap_username, $config_imap_password);
// Check connection
if (!$imap) {
// Logging
//$extended_log_description = var_export(imap_errors(), true);
// Remove the lock file
unlink($lock_file_path);
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Email parser: Failed to connect to IMAP. Details'");
exit("Could not connect to IMAP");
}
// Check for the ITFlow mailbox that we move messages to once processed
$imap_folder = 'ITFlow';
$list = imap_list($imap, "{{$imap_mailbox}}", "*");
if (array_search("{{$imap_mailbox}}$imap_folder", $list) === false) {
imap_createmailbox($imap, imap_utf7_encode("{{$imap_mailbox}}$imap_folder"));
imap_subscribe($imap, imap_utf7_encode("{{$imap_mailbox}}$imap_folder"));
}
// Search for unread ("UNSEEN") emails
$emails = imap_search($imap, 'UNSEEN');
if ($emails) {
// Sort
rsort($emails);
// Loop through each email
foreach ($emails as $email) {
// Default false
$email_processed = false;
// Save the original email (to be moved later)
mkdirMissing('uploads/tmp/'); // Create tmp dir
$original_message_file = "processed-eml-" . randomString(200) . ".eml";
imap_savebody($imap, "uploads/tmp/{$original_message_file}", $email);
// Get details from message and invoke PHP Mime Mail Parser
$msg_to_parse = imap_fetchheader($imap, $email, FT_PREFETCHTEXT) . imap_body($imap, $email, FT_PEEK);
$parser = new PhpMimeMailParser\Parser();
$parser->setText($msg_to_parse);
// Process message attributes
$from_array = $parser->getAddresses('from')[0];
$from_name = sanitizeInput($from_array['display']);
// Handle blank 'From' emails
$from_email = "itflow-guest@example.com";
if (filter_var($from_array['address'], FILTER_VALIDATE_EMAIL)) {
$from_email = sanitizeInput($from_array['address']);
}
$from_domain = explode("@", $from_array['address']);
$from_domain = sanitizeInput(end($from_domain));
$subject = sanitizeInput($parser->getHeader('subject'));
$date = sanitizeInput($parser->getHeader('date'));
$attachments = $parser->getAttachments();
// Get the message content
// (first try HTML parsing, but switch to plain text if the email is empty/plain-text only)
// $message = $parser->getMessageBody('htmlEmbedded');
// if (empty($message)) {
// echo "DEBUG: Switching to plain text parsing for this message ($subject)";
// $message = $parser->getMessageBody('text');
// }
// TODO: Default to getting HTML and fallback to plaintext, but HTML emails seem to break the forward/agent notifications
$message = $parser->getMessageBody('text');
// Check if we can identify a ticket number (in square brackets)
if (preg_match("/\[$config_ticket_prefix\d+\]/", $subject, $ticket_number)) {
// Looks like there's a ticket number in the subject line (e.g. [TCK-091]
// Process as a ticket reply
// Get the actual ticket number (without the brackets)
preg_match('/\d+/', $ticket_number[0], $ticket_number);
$ticket_number = intval($ticket_number[0]);
if (addReply($from_email, $date, $subject, $ticket_number, $message, $attachments)) {
$email_processed = true;
}
} else {
// Couldn't match this email to an existing ticket
// Check if we can match the sender to a pre-existing contact
$any_contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from_email' LIMIT 1");
$row = mysqli_fetch_array($any_contact_sql);
if ($row) {
// Sender exists as a contact
$contact_name = sanitizeInput($row['contact_name']);
$contact_id = intval($row['contact_id']);
$contact_email = sanitizeInput($row['contact_email']);
$client_id = intval($row['contact_client_id']);
if (addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file)) {
$email_processed = true;
}
} else {
// Couldn't match this email to an existing ticket or an existing client contact
// Checking to see if the sender domain matches a client website
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM domains WHERE domain_name = '$from_domain' LIMIT 1"));
if ($row && $from_domain == $row['domain_name']) {
// We found a match - create a contact under this client and raise a ticket for them
// Client details
$client_id = intval($row['domain_client_id']);
// Contact details
$password = password_hash(randomString(), PASSWORD_DEFAULT);
$contact_name = $from_name; // This was already Sanitized above
$contact_email = $from_email; // This was already Sanitized above
mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '$contact_name', contact_email = '$contact_email', contact_notes = 'Added automatically via email parsing.', contact_password_hash = '$password', contact_client_id = $client_id");
$contact_id = mysqli_insert_id($mysqli);
// Logging for contact creation
echo "Created new contact.<br>";
mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Contact', log_action = 'Create', log_description = 'Email parser: created contact $contact_name', log_client_id = $client_id");
if (addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file)) {
$email_processed = true;
}
} else {
// Couldn't match this email to an existing ticket, existing contact or an existing client via the "from" domain
// In the future we might make a page where these can be nicely viewed / managed, but for now we'll just flag them in the Inbox as needing attention
}
}
}
// Deal with the message (move it if processed, flag it if not)
if ($email_processed) {
imap_setflag_full($imap, $email, "\\Seen");
imap_mail_move($imap, $email, $imap_folder);
} else {
// Basically just flags all emails to be manually checked
echo "Failed to process email - flagging for manual review.";
imap_setflag_full($imap, $email, "\\Flagged");
}
// Remove temp original message if still there
if (file_exists("uploads/tmp/{$original_message_file}")) {
unlink("uploads/tmp/{$original_message_file}");
}
}
}
imap_expunge($imap);
imap_close($imap);
// Remove the lock file
unlink($lock_file_path);

View File

@ -28,23 +28,6 @@ if (isset($_POST['add_ticket'])) {
$use_primary_contact = intval($_POST['use_primary_contact']);
$ticket_template_id = intval($_POST['ticket_template_id']);
// Check to see if adding a ticket by template
if($ticket_template_id) {
$sql = mysqli_query($mysqli, "SELECT * FROM ticket_templates WHERE ticket_template_id = $ticket_template_id");
$row = mysqli_fetch_array($sql);
// Override Template Subject
if(empty($subject)) {
$subject = sanitizeInput($row['ticket_template_subject']);
}
$details = mysqli_escape_string($mysqli, $row['ticket_template_details']);
// Get Associated Tasks from the ticket template
$sql_task_templates = mysqli_query($mysqli, "SELECT * FROM task_templates WHERE task_template_ticket_template_id = $ticket_template_id");
}
// Add the primary contact as the ticket contact if "Use primary contact" is checked
if ($use_primary_contact == 1) {
$sql = mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE contact_client_id = $client_id AND contact_primary = 1");
@ -79,6 +62,9 @@ if (isset($_POST['add_ticket'])) {
// Add Tasks from Template if Template was selected
if($ticket_template_id) {
// Get Associated Tasks from the ticket template
$sql_task_templates = mysqli_query($mysqli, "SELECT * FROM task_templates WHERE task_template_ticket_template_id = $ticket_template_id");
if (mysqli_num_rows($sql_task_templates) > 0) {
while ($row = mysqli_fetch_array($sql_task_templates)) {
$task_order = intval($row['task_template_order']);

View File

@ -1,344 +0,0 @@
<div class="modal" id="addTicketFromTemplateModal" tabindex="-1">
<div class="modal-dialog modal-lg">
<div class="modal-content bg-dark">
<div class="modal-header">
<h5 class="modal-title"><i class="fas fa-fw fa-life-ring mr-2"></i>New Ticket From Template</h5>
<button type="button" class="close text-white" data-dismiss="modal">
<span>&times;</span>
</button>
</div>
<form action="post.php" method="post" autocomplete="off">
<input type="hidden" name="subject" value="">
<input type="hidden" name="details" value="">
<div class="modal-body bg-white">
<?php if (isset($_GET['client_id'])) { ?>
<ul class="nav nav-pills nav-justified mb-3">
<li class="nav-item">
<a class="nav-link active" data-toggle="pill" href="#pills-details-template"><i class="fa fa-fw fa-life-ring mr-2"></i>Details</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="pill" href="#pills-contacts-template"><i class="fa fa-fw fa-users mr-2"></i>Contact</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="pill" href="#pills-assets-template"><i class="fa fa-fw fa-desktop mr-2"></i>Asset</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="pill" href="#pills-locations-template"><i class="fa fa-fw fa-map-marker-alt mr-2"></i>Location</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="pill" href="#pills-vendors-template"><i class="fa fa-fw fa-building mr-2"></i>Vendor</a>
</li>
<li class="nav-item">
<a class="nav-link" data-toggle="pill" href="#pills-project-template"><i class="fa fa-fw fa-project-diagram mr-2"></i>Project</a>
</li>
</ul>
<hr>
<?php } ?>
<div class="tab-content">
<div class="tab-pane fade show active" id="pills-details-template">
<div class="form-group">
<label>Template</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-cube"></i></span>
</div>
<select class="form-control select2" name="ticket_template_id" required>
<option value="0">- Choose a Template -</option>
<?php
$sql_ticket_templates = mysqli_query($mysqli, "SELECT * FROM ticket_templates WHERE ticket_template_archived_at IS NULL ORDER BY ticket_template_name ASC");
while ($row = mysqli_fetch_array($sql_ticket_templates)) {
$ticket_template_id_select = intval($row['ticket_template_id']);
$ticket_template_name_select = nullable_htmlentities($row['ticket_template_name']);
?>
<option value="<?php echo $ticket_template_id_select; ?>"><?php echo $ticket_template_name_select; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Override Subject</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
</div>
<input type="text" class="form-control" name="subject" placeholder="Fill this in to override the templates subject">
</div>
</div>
<?php if (empty($_GET['client_id'])) { ?>
<div class="form-group">
<label>Client <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
</div>
<select class="form-control select2" name="client" required>
<option value="">- Client -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT * FROM clients WHERE client_archived_at IS NULL $access_permission_query ORDER BY client_name ASC");
while ($row = mysqli_fetch_array($sql)) {
$client_id = intval($row['client_id']);
$client_name = nullable_htmlentities($row['client_name']); ?>
<option value="<?php echo $client_id; ?>"><?php echo $client_name; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input class="custom-control-input" type="checkbox" id="primaryContactCheckboxTemplate" name="use_primary_contact" value="1">
<label for="primaryContactCheckboxTemplate" class="custom-control-label">Use Primary Contact</label>
</div>
</div>
<?php } ?>
<div class="form-group">
<label>Priority <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-thermometer-half"></i></span>
</div>
<select class="form-control select2" name="priority" required>
<option>Low</option>
<option>Medium</option>
<option>High</option>
</select>
</div>
</div>
<div class="form-group">
<label>Assign to</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-user-check"></i></span>
</div>
<select class="form-control select2" name="assigned_to">
<option value="0">Not Assigned</option>
<?php
$sql = mysqli_query(
$mysqli,
"SELECT users.user_id, user_name FROM users
LEFT JOIN user_settings on users.user_id = user_settings.user_id
WHERE user_role > 1 AND user_status = 1 AND user_archived_at IS NULL ORDER BY user_name ASC"
);
while ($row = mysqli_fetch_array($sql)) {
$user_id = intval($row['user_id']);
$user_name = nullable_htmlentities($row['user_name']); ?>
<option <?php if ($session_user_id == $user_id) { echo "selected"; } ?> value="<?php echo $user_id; ?>"><?php echo $user_name; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<?php if (isset($_GET['client_id'])) { ?>
<div class="tab-pane fade" id="pills-contacts-template">
<input type="hidden" name="client" value="<?php echo $client_id; ?>">
<div class="form-group">
<label>Contact</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-user"></i></span>
</div>
<select class="form-control select2" name="contact">
<option value="0">- No One -</option>
<?php
$sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_client_id = $client_id AND contact_archived_at IS NULL ORDER BY contact_primary DESC, contact_technical DESC, contact_name ASC");
while ($row = mysqli_fetch_array($sql)) {
$contact_id = intval($row['contact_id']);
$contact_name = nullable_htmlentities($row['contact_name']);
$contact_primary = intval($row['contact_primary']);
if($contact_primary == 1) {
$contact_primary_display = " (Primary)";
} else {
$contact_primary_display = "";
}
$contact_technical = intval($row['contact_technical']);
if($contact_technical == 1) {
$contact_technical_display = " (Technical)";
} else {
$contact_technical_display = "";
}
$contact_title = nullable_htmlentities($row['contact_title']);
if(!empty($contact_title)) {
$contact_title_display = " - $contact_title";
} else {
$contact_title_display = "";
}
?>
<option value="<?php echo $contact_id; ?>" <?php if ($contact_primary == 1 || $contact_id == isset($_GET['contact_id'])) { echo "selected"; } ?>><?php echo "$contact_name$contact_title_display$contact_primary_display$contact_technical_display"; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Watchers</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-envelope"></i></span>
</div>
<select class="form-control select2" name="watchers[]" data-tags="true" data-placeholder="Enter or select email address" multiple>
<option value=""></option>
<?php
$sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_client_id = $client_id AND contact_archived_at IS NULL AND contact_email IS NOT NULL ORDER BY contact_email ASC");
while ($row = mysqli_fetch_array($sql)) {
$contact_email = nullable_htmlentities($row['contact_email']);
?>
<option><?php echo $contact_email; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="tab-pane fade" id="pills-assets-template">
<div class="form-group">
<label>Asset</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-desktop"></i></span>
</div>
<select class="form-control select2" name="asset">
<option value="0">- None -</option>
<?php
$sql_assets = mysqli_query($mysqli, "SELECT * FROM assets LEFT JOIN contacts ON contact_id = asset_contact_id WHERE asset_client_id = $client_id AND asset_archived_at IS NULL ORDER BY asset_name ASC");
while ($row = mysqli_fetch_array($sql_assets)) {
$asset_id_select = intval($row['asset_id']);
$asset_name_select = nullable_htmlentities($row['asset_name']);
$asset_contact_name_select = nullable_htmlentities($row['contact_name']);
?>
<option value="<?php echo $asset_id_select; ?>"><?php echo "$asset_name_select - $asset_contact_name_select"; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="tab-pane fade" id="pills-locations-template">
<div class="form-group">
<label>Location</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-map-marker-alt"></i></span>
</div>
<select class="form-control select2" name="location">
<option value="0">- None -</option>
<?php
$sql_locations = mysqli_query($mysqli, "SELECT * FROM locations WHERE location_client_id = $client_id AND location_archived_at IS NULL ORDER BY location_name ASC");
while ($row = mysqli_fetch_array($sql_locations)) {
$location_id_select = intval($row['location_id']);
$location_name_select = nullable_htmlentities($row['location_name']);
?>
<option value="<?php echo $location_id_select; ?>"><?php echo $location_name_select; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<div class="tab-pane fade" id="pills-vendors-template">
<div class="form-group">
<label>Vendor</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-building"></i></span>
</div>
<select class="form-control select2" name="vendor">
<option value="0">- None -</option>
<?php
$sql_vendors = mysqli_query($mysqli, "SELECT * FROM vendors WHERE vendor_client_id = $client_id AND vendor_template = 0 AND vendor_archived_at IS NULL ORDER BY vendor_name ASC");
while ($row = mysqli_fetch_array($sql_vendors)) {
$vendor_id_select = intval($row['vendor_id']);
$vendor_name_select = nullable_htmlentities($row['vendor_name']); ?>
<option value="<?php echo $vendor_id_select; ?>"><?php echo $vendor_name_select; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Vendor Ticket Number</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
</div>
<input type="text" class="form-control" name="vendor_ticket_number" placeholder="Vendor ticket number">
</div>
</div>
</div>
<div class="tab-pane fade" id="pills-project-template">
<div class="form-group">
<label>Project</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-project-diagram"></i></span>
</div>
<select class="form-control select2" name="project">
<option value="0">- None -</option>
<?php
$sql_projects = mysqli_query($mysqli, "SELECT * FROM projects WHERE project_client_id = $client_id AND project_completed_at IS NULL AND project_archived_at IS NULL ORDER BY project_name ASC");
while ($row = mysqli_fetch_array($sql_projects)) {
$project_id_select = intval($row['project_id']);
$project_name_select = nullable_htmlentities($row['project_name']); ?>
<option value="<?php echo $project_id_select; ?>"><?php echo $project_name_select; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
<div class="modal-footer bg-white">
<button type="submit" name="add_ticket" class="btn btn-primary text-bold"><i class="fas fa-check mr-2"></i>Create</button>
<button type="button" class="btn btn-light" data-dismiss="modal"><i class="fas fa-times mr-2"></i>Cancel</button>
</div>
</form>
</div>
</div>
</div>

View File

@ -62,19 +62,44 @@
<?php } ?>
<div class="form-group">
<label>Template</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-cube"></i></span>
</div>
<select class="form-control select2" id="ticket_template_select" name="ticket_template_id" required>
<option value="0">- Choose a Template -</option>
<?php
$sql_ticket_templates = mysqli_query($mysqli, "SELECT * FROM ticket_templates WHERE ticket_template_archived_at IS NULL ORDER BY ticket_template_name ASC");
while ($row = mysqli_fetch_array($sql_ticket_templates)) {
$ticket_template_id_select = intval($row['ticket_template_id']);
$ticket_template_name_select = nullable_htmlentities($row['ticket_template_name']);
$ticket_template_details_select = nullable_htmlentities($row['ticket_template_details']);
?>
<option value="<?php echo $ticket_template_id_select; ?>"
data-subject="<?php echo $ticket_template_name_select; ?>"
data-details="<?php echo $ticket_template_details_select; ?>">
<?php echo $ticket_template_name_select; ?>
</option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label>Subject <strong class="text-danger">*</strong></label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-tag"></i></span>
</div>
<input type="text" class="form-control" name="subject" placeholder="Subject" required>
<input type="text" class="form-control" id="subjectInput" name="subject" placeholder="Subject" required>
</div>
</div>
<?php if($config_ai_enable) { ?>
<div class="form-group">
<textarea class="form-control tinymceai" id="textInput" name="details"></textarea>
<textarea class="form-control tinymceai" id="detailsInput" name="details"></textarea>
</div>
<div class="mb-3">
@ -83,7 +108,7 @@
</div>
<?php } else { ?>
<div class="form-group">
<textarea class="form-control tinymce" rows="5" name="details"></textarea>
<textarea class="form-control tinymce" id="detailsInput" rows="5" name="details"></textarea>
</div>
<?php } ?>
@ -361,3 +386,32 @@
</div>
</div>
</div>
<script>
document.addEventListener("DOMContentLoaded", function() {
var templateSelect = $('#ticket_template_select');
var subjectInput = document.getElementById('subjectInput');
var detailsInput = document.getElementById('detailsInput');
templateSelect.on('select2:select', function(e) {
var selectedOption = e.params.data.element;
var templateSubject = selectedOption.getAttribute('data-subject');
var templateDetails = selectedOption.getAttribute('data-details');
// Update Subject
subjectInput.value = templateSubject || '';
// Update Details
if (typeof tinymce !== 'undefined') {
var editor = tinymce.get('detailsInput');
if (editor) {
editor.setContent(templateDetails || '');
} else {
detailsInput.value = templateDetails || '';
}
} else {
detailsInput.value = templateDetails || '';
}
});
});
</script>

View File

@ -118,12 +118,6 @@ $user_active_assigned_tickets = intval($row['total_tickets_assigned']);
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#addTicketModal">
<i class="fas fa-plus mr-2"></i>New Ticket
</button>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" data-toggle="dropdown"></button>
<div class="dropdown-menu">
<a class="dropdown-item text-dark" href="#" data-toggle="modal" data-target="#addTicketFromTemplateModal">
<i class="fa fa-fw fa-plus mr-2"></i>From Template
</a>
</div>
</div>
</div>
</div>
@ -595,6 +589,4 @@ $user_active_assigned_tickets = intval($row['total_tickets_assigned']);
<?php
require_once "ticket_add_modal.php";
require_once "ticket_add_from_template_modal.php";
require_once "footer.php";