Merge pull request #502 from wrongecho/email-to-ticket

Email to ticket (Beta)
This commit is contained in:
Johnny 2022-12-11 13:14:13 -05:00 committed by GitHub
commit 77fb936099
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 292 additions and 14 deletions

View File

@ -369,9 +369,18 @@ if(LATEST_DATABASE_VERSION > CURRENT_DATABASE_VERSION){
mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.1'");
}
//if(CURRENT_DATABASE_VERSION == '0.2.1'){
if(CURRENT_DATABASE_VERSION == '0.2.1'){
// Insert queries here required to update to DB version 0.2.2
mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_ticket_email_parse` INT(1) NOT NULL DEFAULT '0' AFTER `config_ticket_from_email`");
mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_imap_host` VARCHAR(200) NULL DEFAULT NULL AFTER `config_mail_from_name`, ADD `config_imap_port` INT(5) NULL DEFAULT NULL AFTER `config_imap_host`, ADD `config_imap_encryption` VARCHAR(200) NULL DEFAULT NULL AFTER `config_imap_port`;");
// Then, update the database to the next sequential version
mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.2'");
}
//if(CURRENT_DATABASE_VERSION == '0.2.2'){
// Insert queries here required to update to DB version 0.2.3
// Then, update the database to the next sequential version
// mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.2'");
//}

View File

@ -5,4 +5,4 @@
* It is used in conjunction with database_updates.php
*/
DEFINE("LATEST_DATABASE_VERSION", "0.2.1");
DEFINE("LATEST_DATABASE_VERSION", "0.2.2");

177
email_parser_cron.php Normal file
View File

@ -0,0 +1,177 @@
<?php
/*
* CRON - Email Parser
* Process emails and create/update tickets
*/
/*
TODO:
- Attachments
- Allow unregistered contacts for clients to create contacts/raise tickets based on email domain
- Process unregistered contacts/clients into an inbox to allow a ticket to be created/ignored
- Better handle replying to closed tickets
- Support for authenticating with OAuth
- Documentation
Relate PRs to https://github.com/itflow-org/itflow/issues/225 & https://forum.itflow.org/d/11-road-map & https://forum.itflow.org/d/31-tickets-from-email
*/
// Get ITFlow config & helper functions
include_once("config.php");
include_once("functions.php");
// Get settings for the "default" company
$session_company_id = 1;
include_once("get_settings.php");
// Check setting enabled
if ($config_ticket_email_parse == 0) {
exit("Feature is not enabled - see Settings > Ticketing > Email-to-ticket parsing");
}
// Check IMAP function exists
if (!function_exists('imap_open')) {
echo "PHP IMAP extension is not installed, quitting..";
exit();
}
// 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_smtp_username, $config_smtp_password);
// Check connection
if (!$imap) {
// Logging
$extended_log_description = var_export(imap_errors(), true);
mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Failed to connect to IMAP: $extended_log_description', company_id = $session_company_id");
exit("Could not connect to IMAP");
}
// Search for unread (UNSEEN) emails
$emails = imap_search($imap,'UNSEEN');
if ($emails) {
// Sort
rsort($emails);
// Loop through each email
foreach($emails as $email) {
// Get message details
$metadata = imap_fetch_overview($imap, $email,0); // Date, Subject, Size
$header = imap_headerinfo($imap, $email); // To get the From as an email, not a contact name
$message = imap_fetchbody($imap, $email, 1); // Body
$from = trim(mysqli_real_escape_string($mysqli, htmlentities(strip_tags($header->from[0]->mailbox . "@" . $header->from[0]->host))));
$subject = trim(mysqli_real_escape_string($mysqli, htmlentities(strip_tags($metadata[0]->subject))));
$date = trim(mysqli_real_escape_string($mysqli, htmlentities(strip_tags($metadata[0]->date))));
// Check if we can identify a ticket number (in square brackets)
if (preg_match('/\[TCK-\d+\]/', $subject, $ticket_number)) {
// Get the actual ticket number (without the brackets)
preg_match('/\d+/', $ticket_number[0], $ticket_number);
$ticket_number = intval($ticket_number[0]);
// Split the email into just the latest reply, with some metadata
// We base this off the string "#--itflow--#" that we prepend the outgoing emails with (similar to the old school --reply above this line--)
$message = explode("#--itflow--#", $message);
$message = nl2br(htmlentities(strip_tags($message[0])));
$message = "<i>Email from: $from at $date:-</i> <br><br>$message";
// Lookup the ticket ID to add the reply to (just to check in-case the ID is different from the number).
$ticket_sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_number = '$ticket_number' LIMIT 1");
$row = mysqli_fetch_array($ticket_sql);
$ticket_id = $row['ticket_id'];
$ticket_reply_contact = $row['ticket_contact_id'];
$ticket_assigned_to = $row['ticket_assigned_to'];
$client_id = $row['ticket_client_id'];
$session_company_id = $row['company_id'];
$ticket_reply_type = 'Public'; // Setting to client as a default value
// Check the ticket ID is valid
if (intval($ticket_id) && $ticket_id !== '0') {
// Check that ticket is open
if ($row['ticket_status'] == "Closed") {
// It's closed - let's notify someone that a client tried to reply
mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Ticket', notification = '$from attempted to re-open ticket ID $ticket_id ($config_ticket_prefix$ticket_number) - check inbox manually to see email', notification_timestamp = NOW(), notification_client_id = '$client_id', company_id = '$session_company_id'");
} else {
// Ticket is open, proceed.
// Check the email matches the contact's email - if it doesn't then mark the reply as internal (so the contact doesn't see it, and the tech can edit/delete if needed)
// Niche edge case - possibly where CC's on an email reply to a ticket?
$contact_sql = mysqli_query($mysqli, "SELECT contact_email FROM contacts WHERE contact_id = '$ticket_reply_contact'");
$row = mysqli_fetch_array($contact_sql);
if ($from !== $row['contact_email']) {
$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)
}
// Sanitize ticket reply
$comment = trim(mysqli_real_escape_string($mysqli,$message));
// 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_created_at = NOW(), ticket_reply_by = '$ticket_reply_contact', ticket_reply_ticket_id = '$ticket_id', company_id = '$session_company_id'");
// Update Ticket Last Response Field & set ticket to open as client has replied
mysqli_query($mysqli,"UPDATE tickets SET ticket_status = 'Open', ticket_updated_at = NOW() 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 = 'Client contact $from updated ticket $subject via email', log_created_at = NOW(), log_client_id = $client_id, company_id = $session_company_id");
}
}
} 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' LIMIT 1");
$row = mysqli_fetch_array($any_contact_sql);
$contact_id = $row['contact_id'];
$contact_email = $row['contact_email'];
$client_id = $row['contact_client_id'];
$session_company_id = $row['company_id'];
if ($from == $contact_email) {
// Prep ticket details
$message = nl2br(htmlentities(strip_tags($message)));
$message = trim(mysqli_real_escape_string($mysqli,"<i>Email from: $from at $date:-</i> <br><br>$message"));
// Get the next Ticket Number and add 1 for the new ticket number
$ticket_number = $config_ticket_next_number;
$new_config_ticket_next_number = $config_ticket_next_number + 1;
mysqli_query($mysqli,"UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = $session_company_id");
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 = 'Open', ticket_created_at = NOW(), ticket_created_by = '0', ticket_contact_id = $contact_id, ticket_client_id = $client_id, company_id = $session_company_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 = 'Client contact $from created ticket $subject via email', log_created_at = NOW(), log_client_id = $client_id, company_id = $session_company_id");
} else {
// Couldn't match this against a specific client contact -- do nothing for now
// In the future, we'll try to match on client domain
// or even log this to an inbox in the ITFlow portal or something to allow a new contact/ticket to be created manually
}
}
}
}

View File

@ -35,10 +35,12 @@ function key32gen()
}
function initials($str) {
$ret = '';
foreach (explode(' ', $str) as $word)
$ret .= strtoupper($word[0]);
return $ret;
if(!empty($str)){
$ret = '';
foreach (explode(' ', $str) as $word)
$ret .= strtoupper($word[0]);
return $ret;
}
}
function removeDirectory($path) {

View File

@ -19,6 +19,10 @@ $config_smtp_username = $row['config_smtp_username'];
$config_smtp_password = $row['config_smtp_password'];
$config_mail_from_email = $row['config_mail_from_email'];
$config_mail_from_name = $row['config_mail_from_name'];
// Mail - IMAP
$config_imap_host = $row['config_imap_host'];
$config_imap_port = $row['config_imap_port'];
$config_imap_encryption = $row['config_imap_encryption'];
// Defaults
$config_default_transfer_from_account = $row['config_default_transfer_from_account'];
@ -53,6 +57,7 @@ $config_ticket_prefix = $row['config_ticket_prefix'];
$config_ticket_next_number = $row['config_ticket_next_number'];
$config_ticket_from_name = $row['config_ticket_from_name'];
$config_ticket_from_email = $row['config_ticket_from_email'];
$config_ticket_email_parse = $row['config_ticket_email_parse'];
// Alerts
$config_enable_cron = $row['config_enable_cron'];

View File

@ -809,8 +809,11 @@ if(isset($_POST['edit_mail_settings'])){
$config_smtp_password = trim(mysqli_real_escape_string($mysqli,$_POST['config_smtp_password']));
$config_mail_from_email = trim(strip_tags(mysqli_real_escape_string($mysqli,$_POST['config_mail_from_email'])));
$config_mail_from_name = trim(strip_tags(mysqli_real_escape_string($mysqli,$_POST['config_mail_from_name'])));
$config_imap_host = trim(strip_tags(mysqli_real_escape_string($mysqli,$_POST['config_imap_host'])));
$config_imap_port = intval($_POST['config_imap_port']);
$config_imap_encryption = trim(strip_tags(mysqli_real_escape_string($mysqli,$_POST['config_imap_encryption'])));
mysqli_query($mysqli,"UPDATE settings SET config_smtp_host = '$config_smtp_host', config_smtp_port = $config_smtp_port, config_smtp_encryption = '$config_smtp_encryption', config_smtp_username = '$config_smtp_username', config_smtp_password = '$config_smtp_password', config_mail_from_email = '$config_mail_from_email', config_mail_from_name = '$config_mail_from_name' WHERE company_id = $session_company_id");
mysqli_query($mysqli,"UPDATE settings SET config_smtp_host = '$config_smtp_host', config_smtp_port = $config_smtp_port, config_smtp_encryption = '$config_smtp_encryption', config_smtp_username = '$config_smtp_username', config_smtp_password = '$config_smtp_password', config_mail_from_email = '$config_mail_from_email', config_mail_from_name = '$config_mail_from_name', config_imap_host = '$config_imap_host', config_imap_port = $config_imap_port, config_imap_encryption = '$config_imap_encryption' WHERE company_id = $session_company_id");
//Update From Email and From Name if Invoice/Quote or Ticket fields are blank
@ -838,7 +841,7 @@ if(isset($_POST['edit_mail_settings'])){
mysqli_query($mysqli,"UPDATE settings SET config_ticket_from_email = '$config_mail_from_email' WHERE company_id = $session_company_id");
}
//Logging
// Logging
mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Settings', log_action = 'Modify', log_description = '$session_name modified mail settings', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_user_id = $session_user_id, company_id = $session_company_id");
$_SESSION['alert_message'] = "Mail settings updated";
@ -847,7 +850,7 @@ if(isset($_POST['edit_mail_settings'])){
}
if(isset($_POST['test_email'])){
if(isset($_POST['test_email_smtp'])){
validateAdminRole();
@ -886,6 +889,27 @@ if(isset($_POST['test_email'])){
header("Location: " . $_SERVER["HTTP_REFERER"]);
}
if(isset($_POST['test_email_imap'])){
validateAdminRole();
// Prepare connection string with encryption (TLS/SSL/<blank>)
$imap_mailbox = "$config_imap_host:$config_imap_port/imap/readonly/$config_imap_encryption";
// Connect
$imap = imap_open("{{$imap_mailbox}}INBOX", $config_smtp_username, $config_smtp_password);
if ($imap) {
$_SESSION['alert_message'] = "Connected successfully";
} else {
$_SESSION['alert_type'] = "error";
$_SESSION['alert_message'] = "Test IMAP connection failed";
}
header("Location: " . $_SERVER["HTTP_REFERER"]);
}
if(isset($_POST['edit_invoice_settings'])){
validateAdminRole();
@ -939,8 +963,10 @@ if(isset($_POST['edit_ticket_settings'])){
$config_ticket_next_number = intval($_POST['config_ticket_next_number']);
$config_ticket_from_email = trim(strip_tags(mysqli_real_escape_string($mysqli,$_POST['config_ticket_from_email'])));
$config_ticket_from_name = trim(strip_tags(mysqli_real_escape_string($mysqli,$_POST['config_ticket_from_name'])));
$config_ticket_email_parse = intval($_POST['config_ticket_email_parse']);
mysqli_query($mysqli,"UPDATE settings SET config_ticket_prefix = '$config_ticket_prefix', config_ticket_next_number = $config_ticket_next_number, config_ticket_from_email = '$config_ticket_from_email', config_ticket_from_name = '$config_ticket_from_name' WHERE company_id = $session_company_id");
mysqli_query($mysqli,"UPDATE settings SET config_ticket_prefix = '$config_ticket_prefix', config_ticket_next_number = $config_ticket_next_number, config_ticket_from_email = '$config_ticket_from_email', config_ticket_from_name = '$config_ticket_from_name', config_ticket_email_parse = '$config_ticket_email_parse' WHERE company_id = $session_company_id");
//Logging
mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Settings', log_action = 'Modify', log_description = 'Ticket settings', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_user_id = $session_user_id, company_id = $session_company_id");
@ -6104,7 +6130,7 @@ if(isset($_POST['add_ticket_reply'])){
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = "Ticket update - [$ticket_prefix$ticket_number] - $ticket_subject";
$mail->Body = "Hello, $contact_name<br><br>Your ticket regarding \"$ticket_subject\" has been updated.<br><br>--------------------------------<br>$ticket_reply--------------------------------<br><br>Ticket: $ticket_prefix$ticket_number<br>Subject: $ticket_subject<br>Status: $ticket_status<br>https://$config_base_url/portal/ticket.php?id=$ticket_id<br><br>~<br>$session_company_name<br>Support Department<br>$config_ticket_from_email<br>$company_phone";
$mail->Body = "<i style='color: #808080'>#--itflow--#</i><br><br>Hello, $contact_name<br><br>Your ticket regarding \"$ticket_subject\" has been updated.<br><br>--------------------------------<br>$ticket_reply--------------------------------<br><br>Ticket: $ticket_prefix$ticket_number<br>Subject: $ticket_subject<br>Status: $ticket_status<br>https://$config_base_url/portal/ticket.php?id=$ticket_id<br><br>~<br>$session_company_name<br>Support Department<br>$config_ticket_from_email<br>$company_phone";
$mail->send();
}
catch(Exception $e){

View File

@ -85,6 +85,40 @@
</div>
<hr>
<div class="form-group">
<label>IMAP Host</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-server"></i></span>
</div>
<input type="text" class="form-control" name="config_imap_host" placeholder="Incoming Mail Server Address (for email to ticket parsing)" value="<?php echo htmlentities($config_imap_host); ?>">
</div>
</div>
<div class="form-group">
<label>IMAP Port</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-plug"></i></span>
</div>
<input type="number" min="0" class="form-control" name="config_imap_port" placeholder="Incoming Mail Server Port Number (993)" value="<?php echo htmlentities($config_imap_port); ?>">
</div>
</div>
<div class="form-group">
<label>IMAP Encryption</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fa fa-fw fa-lock"></i></span>
</div>
<select class="form-control" name="config_imap_encryption">
<option value=''>None</option>
<option <?php if($config_imap_encryption == 'tls'){ echo "selected"; } ?> value="tls">TLS</option>
<option <?php if($config_imap_encryption == 'ssl'){ echo "selected"; } ?> value="ssl">SSL</option>
</select>
</div>
</div>
<button type="submit" name="edit_mail_settings" class="btn btn-primary">Save</button>
@ -96,14 +130,14 @@
<div class="card card-dark">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-fw fa-paper-plane"></i> Test Email</h3>
<h3 class="card-title"><i class="fa fa-fw fa-paper-plane"></i> Test Email Sending</h3>
</div>
<div class="card-body">
<form action="post.php" method="post" autocomplete="off">
<div class="input-group">
<input type="email" class="form-control " name="email" placeholder="Email address to test">
<div class="input-group-append">
<button type="submit" name="test_email" class="btn btn-success"><i class="fa fa-fw fa-paper-plane"></i> Send</button>
<button type="submit" name="test_email_smtp" class="btn btn-success"><i class="fa fa-fw fa-paper-plane"></i> Send</button>
</div>
</div>
</form>
@ -112,4 +146,21 @@
<?php } ?>
<?php if(!empty($config_smtp_username) && !empty($config_smtp_password) && !empty($config_imap_host) && !empty($config_imap_port)){ ?>
<div class="card card-dark">
<div class="card-header">
<h3 class="card-title"><i class="fa fa-fw fa-paper-plane"></i> Test Email Receiving</h3>
</div>
<div class="card-body">
<form action="post.php" method="post" autocomplete="off">
<div class="input-group-append">
<button type="submit" name="test_email_imap" class="btn btn-success"><i class="fa fa-fw fa-inbox"></i> Test</button>
</div>
</form>
</div>
</div>
<?php } ?>
<?php include("footer.php");

View File

@ -46,6 +46,12 @@
<input type="text" class="form-control" name="config_ticket_from_name" placeholder="Name" value="<?php echo htmlentities($config_ticket_from_name); ?>">
</div>
</div>
<div class="custom-control custom-switch mb-2">
<input type="checkbox" class="custom-control-input" disabled name="config_ticket_email_parse" <?php if($config_ticket_email_parse == 1){ echo "checked"; } ?> value="1" id="customSwitch1">
<label class="custom-control-label" for="customSwitch1">Email-to-ticket parsing (Beta) <small>(email_parser_cron.php must also be added to cron and run every few mins)</small></label>
</div>
<hr>

View File

@ -276,7 +276,7 @@ if(isset($_GET['ticket_id'])){
<?php
$sql = mysqli_query($mysqli,"SELECT * FROM ticket_replies LEFT JOIN users ON ticket_reply_by = user_id LEFT JOIN contacts ON ticket_reply_by = contact_id WHERE ticket_reply_ticket_id = $ticket_id AND ticket_reply_archived_at IS NULL ORDER BY ticket_reply_id DESC");
while($row = mysqli_fetch_array($sql)){;
while($row = mysqli_fetch_array($sql)){
$ticket_reply_id = $row['ticket_reply_id'];
$ticket_reply = $row['ticket_reply'];
$ticket_reply_type = htmlentities($row['ticket_reply_type']);

View File

@ -16,12 +16,14 @@
<textarea class="form-control summernote" rows="8" name="ticket_reply"><?php echo $ticket_reply; ?></textarea>
</div>
<?php if(!empty($ticket_reply_time_worked)) { ?>
<b>Time worked</b>
<div class="col-3">
<div class="form-group">
<input class="form-control timepicker" id="time_worked" name="time" type="time" step="1" value="<?php echo date_format($ticket_reply_time_worked, 'H:i:s') ?>"/>
</div>
</div>
<?php } ?>
</div>
<div class="modal-footer bg-white">