From d3fbdfb743e9275097b61224d38044896c0a2102 Mon Sep 17 00:00:00 2001 From: Marcus Hill Date: Sun, 11 Dec 2022 01:34:15 +0000 Subject: [PATCH] Add email to ticket functionality - beta --- database_updates.php | 11 +- database_version.php | 2 +- email_parser_cron.php | 176 ++++++++++++++++++ get_settings.php | 5 + ...e061fc6632c745df51b43504cb541c9339de,1.ser | Bin 0 -> 516 bytes post.php | 36 +++- settings_mail.php | 55 +++++- settings_ticket.php | 6 + test.php | 64 +++++++ 9 files changed, 346 insertions(+), 9 deletions(-) create mode 100644 plugins/htmlpurifier/standalone/HTMLPurifier/DefinitionCache/Serializer/URI/4.14.0,b359e061fc6632c745df51b43504cb541c9339de,1.ser create mode 100644 test.php diff --git a/database_updates.php b/database_updates.php index 163c8b07..adcb06b8 100644 --- a/database_updates.php +++ b/database_updates.php @@ -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'"); //} diff --git a/database_version.php b/database_version.php index 21d3b411..24a33029 100644 --- a/database_version.php +++ b/database_version.php @@ -5,4 +5,4 @@ * It is used in conjunction with database_updates.php */ -DEFINE("LATEST_DATABASE_VERSION", "0.2.1"); \ No newline at end of file +DEFINE("LATEST_DATABASE_VERSION", "0.2.2"); \ No newline at end of file diff --git a/email_parser_cron.php b/email_parser_cron.php index b3d9bbc7..92e2a82c 100644 --- a/email_parser_cron.php +++ b/email_parser_cron.php @@ -1 +1,177 @@ 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/) +$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 = "Email from: $from at $date:-

$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 = 'Client'; // 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 = "WARNING: Contact email mismatch
$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.
"; + 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,"Email from: $from at $date:-

$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.
"; + 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 + + } + + } + + + } + +} \ No newline at end of file diff --git a/get_settings.php b/get_settings.php index fdc30792..76f58b93 100644 --- a/get_settings.php +++ b/get_settings.php @@ -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']; diff --git a/plugins/htmlpurifier/standalone/HTMLPurifier/DefinitionCache/Serializer/URI/4.14.0,b359e061fc6632c745df51b43504cb541c9339de,1.ser b/plugins/htmlpurifier/standalone/HTMLPurifier/DefinitionCache/Serializer/URI/4.14.0,b359e061fc6632c745df51b43504cb541c9339de,1.ser new file mode 100644 index 0000000000000000000000000000000000000000..f6d3e812b706751db73261e535cbc8e9e3632a7d GIT binary patch literal 516 zcmZvYK~BRk5Jh{IS+Yt}Krr4Rgjxw&L}48{?YOb(CXww3N|n1ab|OkkcJ}Cd-t%8# zc8f53e|dgwtyY?B{_!?{B&93ubzK48;nCqWfHw6XBF52$QRc(#Df@AS7lX zn{r}SJO5zhdS|rrAeJ~Cp*+Qh`FWO6J+G4c$QxP5j4Yyy6GCEw$1a*S3aRa z#S<7y6` literal 0 HcmV?d00001 diff --git a/post.php b/post.php index e15eeb78..c7eda8ce 100644 --- a/post.php +++ b/post.php @@ -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/) + $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

Your ticket regarding \"$ticket_subject\" has been updated.

--------------------------------
$ticket_reply--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status
https://$config_base_url/portal/ticket.php?id=$ticket_id

~
$session_company_name
Support Department
$config_ticket_from_email
$company_phone"; + $mail->Body = "#--itflow--#

Hello, $contact_name

Your ticket regarding \"$ticket_subject\" has been updated.

--------------------------------
$ticket_reply--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status
https://$config_base_url/portal/ticket.php?id=$ticket_id

~
$session_company_name
Support Department
$config_ticket_from_email
$company_phone"; $mail->send(); } catch(Exception $e){ diff --git a/settings_mail.php b/settings_mail.php index c674996b..51d16087 100644 --- a/settings_mail.php +++ b/settings_mail.php @@ -85,6 +85,40 @@
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
@@ -96,14 +130,14 @@
-

Test Email

+

Test Email Sending

- +
@@ -112,4 +146,21 @@ + + +
+
+

Test Email Receiving

+
+
+
+
+ +
+
+
+
+ + + ">
+ + +
+ value="1" id="customSwitch1"> + +

diff --git a/test.php b/test.php new file mode 100644 index 00000000..4bc62402 --- /dev/null +++ b/test.php @@ -0,0 +1,64 @@ + array("capture_peer_cert" => TRUE, "verify_peer" => FALSE,))); + $read = stream_socket_client($socket, $errno, $errstr, 10, STREAM_CLIENT_CONNECT, $get); + + if($read){ + $cert = stream_context_get_params($read); + $cert_public_key_obj = openssl_x509_parse($cert['options']['ssl']['peer_certificate']); + openssl_x509_export($cert['options']['ssl']['peer_certificate'], $export); + + // Success - process data + if($cert_public_key_obj){ + $expire = mysqli_real_escape_string($mysqli, date('Y-m-d', $cert_public_key_obj['validTo_time_t'])); + $issued_by = mysqli_real_escape_string($mysqli, strip_tags($cert_public_key_obj['issuer']['O'])); + $public_key = mysqli_real_escape_string($mysqli, $export); + + // Update the record (forcing certificate_created_at field to be updated to ensure we don't try and update the same record every day) + mysqli_query($mysqli, "UPDATE certificates SET certificate_issued_by = '$issued_by', certificate_expire = '$expire', certificate_public_key = '$public_key', certificate_updated_at = NOW() WHERE certificate_id = '$certificate_id' LIMIT 1"); + echo "Updated $certificate_domain"; + } + else{ + // Likely the SSL socket failed, log an error notification + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Cron', notification = 'Nightly SSL update for $certificate_domain failed. Please check and manually update this record.', notification_timestamp = NOW(), company_id = $company_id"); + echo "Update $certificate_domain failed"; + } + } + else{ + // Likely the SSL socket failed, log an error notification + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Cron', notification = 'Nightly SSL update for $certificate_domain failed. Please check and manually update this record.', notification_timestamp = NOW(), company_id = $company_id"); + echo "Update $certificate_domain failed"; + } + +} + +echo "Carried on!"; + +?> \ No newline at end of file