diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..73555192 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,20 @@ +# Editor defaults for ITFlow - see CONTRIBUTING.md ("Style") +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.md] +trim_trailing_whitespace = false + +# Vendored - do not reformat +[libs/**] +indent_style = unset +indent_size = unset +trim_trailing_whitespace = false +insert_final_newline = false diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..2cc86d97 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,44 @@ +# ITFlow line-ending policy +# +# Everything ITFlow ships is LF in the repository and LF in the working tree. +# Contributors on Windows get LF too - this is deliberate. ITFlow is deployed +# to Linux/Apache and edited over sftp/ssh as often as it is cloned, so a +# checkout must be byte-identical everywhere. + +* text=auto eol=lf + +# Explicit for the file types we author, so nothing depends on git's guess. +*.php text eol=lf +*.js text eol=lf +*.css text eol=lf +*.html text eol=lf +*.sql text eol=lf +*.md text eol=lf +*.json text eol=lf +*.yml text eol=lf +*.xsd text eol=lf +*.svg text eol=lf +*.txt text eol=lf +*.ini text eol=lf +.htaccess text eol=lf + +# Binary assets: never touched, never diffed as text. +*.png binary +*.gif binary +*.jpg binary +*.jpeg binary +*.webp binary +*.ico binary +*.icc binary +*.woff binary +*.woff2 binary +*.ttf binary +*.eot binary +*.crt binary +*.ser binary +*.z binary + +# Vendored third-party code is preserved byte-for-byte as shipped upstream. +# Per CONTRIBUTING.md libs/ is never edited in place - it is replaced wholesale - +# so normalizing it here would create spurious diffs on the next library update. +libs/** -text diff --git a/admin/oauth_microsoft_mail_callback.php b/admin/oauth_microsoft_mail_callback.php index 85ce5f26..52d659a6 100644 --- a/admin/oauth_microsoft_mail_callback.php +++ b/admin/oauth_microsoft_mail_callback.php @@ -1,103 +1,103 @@ - $session_state_expires) { - flashAlert("Microsoft OAuth callback validation failed. Please try connecting again.", 'error'); - redirect($settings_mail_path); -} - -if (empty($config_mail_oauth_client_id) || empty($config_mail_oauth_client_secret) || empty($config_mail_oauth_tenant_id)) { - flashAlert("Microsoft OAuth settings are incomplete. Please fill Client ID, Client Secret, and Tenant ID.", 'error'); - redirect($settings_mail_path); -} - -if (defined('BASE_URL') && !empty(BASE_URL)) { - $base_url = rtrim((string) BASE_URL, '/'); -} else { - $base_url = 'https://' . rtrim((string) $config_base_url, '/'); -} - -$redirect_uri = $base_url . '/admin/oauth_microsoft_mail_callback.php'; -$token_url = 'https://login.microsoftonline.com/' . rawurlencode($config_mail_oauth_tenant_id) . '/oauth2/v2.0/token'; -$scope = 'offline_access openid profile https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send'; - -$ch = curl_init($token_url); -curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); -curl_setopt($ch, CURLOPT_POST, true); -curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ - 'client_id' => $config_mail_oauth_client_id, - 'client_secret' => $config_mail_oauth_client_secret, - 'grant_type' => 'authorization_code', - 'code' => $code, - 'redirect_uri' => $redirect_uri, - 'scope' => $scope, -], '', '&')); -curl_setopt($ch, CURLOPT_TIMEOUT, 20); - -$raw_body = curl_exec($ch); -$curl_err = curl_error($ch); -$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); -curl_close($ch); - -if ($raw_body === false || $http_code < 200 || $http_code >= 300) { - $reason = !empty($curl_err) ? $curl_err : "HTTP $http_code"; - flashAlert("Microsoft OAuth token exchange failed: $reason", 'error'); - redirect($settings_mail_path); -} - -$json = json_decode($raw_body, true); -if (!is_array($json) || empty($json['refresh_token']) || empty($json['access_token'])) { - flashAlert("Microsoft OAuth token exchange failed: refresh token or access token missing.", 'error'); - redirect($settings_mail_path); -} - -$refresh_token = (string) $json['refresh_token']; -$access_token = (string) $json['access_token']; -$expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600)); - -$refresh_token_esc = mysqli_real_escape_string($mysqli, $refresh_token); -$access_token_esc = mysqli_real_escape_string($mysqli, $access_token); -$expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at); - -mysqli_query($mysqli, "UPDATE settings SET - config_imap_provider = 'microsoft_oauth', - config_smtp_provider = 'microsoft_oauth', - config_mail_oauth_refresh_token = '$refresh_token_esc', - config_mail_oauth_access_token = '$access_token_esc', - config_mail_oauth_access_token_expires_at = '$expires_at_esc' - WHERE company_id = 1 -"); - -logAudit("Settings", "Edit", "$session_name completed Microsoft OAuth connect flow for mail settings"); -flashAlert("Microsoft OAuth connected successfully. Token expires at $expires_at."); -redirect($settings_mail_path); + $session_state_expires) { + flashAlert("Microsoft OAuth callback validation failed. Please try connecting again.", 'error'); + redirect($settings_mail_path); +} + +if (empty($config_mail_oauth_client_id) || empty($config_mail_oauth_client_secret) || empty($config_mail_oauth_tenant_id)) { + flashAlert("Microsoft OAuth settings are incomplete. Please fill Client ID, Client Secret, and Tenant ID.", 'error'); + redirect($settings_mail_path); +} + +if (defined('BASE_URL') && !empty(BASE_URL)) { + $base_url = rtrim((string) BASE_URL, '/'); +} else { + $base_url = 'https://' . rtrim((string) $config_base_url, '/'); +} + +$redirect_uri = $base_url . '/admin/oauth_microsoft_mail_callback.php'; +$token_url = 'https://login.microsoftonline.com/' . rawurlencode($config_mail_oauth_tenant_id) . '/oauth2/v2.0/token'; +$scope = 'offline_access openid profile https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send'; + +$ch = curl_init($token_url); +curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); +curl_setopt($ch, CURLOPT_POST, true); +curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([ + 'client_id' => $config_mail_oauth_client_id, + 'client_secret' => $config_mail_oauth_client_secret, + 'grant_type' => 'authorization_code', + 'code' => $code, + 'redirect_uri' => $redirect_uri, + 'scope' => $scope, +], '', '&')); +curl_setopt($ch, CURLOPT_TIMEOUT, 20); + +$raw_body = curl_exec($ch); +$curl_err = curl_error($ch); +$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); +curl_close($ch); + +if ($raw_body === false || $http_code < 200 || $http_code >= 300) { + $reason = !empty($curl_err) ? $curl_err : "HTTP $http_code"; + flashAlert("Microsoft OAuth token exchange failed: $reason", 'error'); + redirect($settings_mail_path); +} + +$json = json_decode($raw_body, true); +if (!is_array($json) || empty($json['refresh_token']) || empty($json['access_token'])) { + flashAlert("Microsoft OAuth token exchange failed: refresh token or access token missing.", 'error'); + redirect($settings_mail_path); +} + +$refresh_token = (string) $json['refresh_token']; +$access_token = (string) $json['access_token']; +$expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600)); + +$refresh_token_esc = mysqli_real_escape_string($mysqli, $refresh_token); +$access_token_esc = mysqli_real_escape_string($mysqli, $access_token); +$expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at); + +mysqli_query($mysqli, "UPDATE settings SET + config_imap_provider = 'microsoft_oauth', + config_smtp_provider = 'microsoft_oauth', + config_mail_oauth_refresh_token = '$refresh_token_esc', + config_mail_oauth_access_token = '$access_token_esc', + config_mail_oauth_access_token_expires_at = '$expires_at_esc' + WHERE company_id = 1 +"); + +logAudit("Settings", "Edit", "$session_name completed Microsoft OAuth connect flow for mail settings"); +flashAlert("Microsoft OAuth connected successfully. Token expires at $expires_at."); +redirect($settings_mail_path); diff --git a/admin/post/settings_mail.php b/admin/post/settings_mail.php index 237b3ad4..f22ffd61 100644 --- a/admin/post/settings_mail.php +++ b/admin/post/settings_mail.php @@ -1,501 +1,501 @@ - $config_mail_oauth_client_id, - 'response_type' => 'code', - 'redirect_uri' => $redirect_uri, - 'response_mode' => 'query', - 'scope' => $scope, - 'state' => $state, - 'prompt' => 'consent', - ], '', '&', PHP_QUERY_RFC3986); - - logAudit("Settings", "Edit", "$session_name started Microsoft OAuth connect flow for mail settings"); - - redirect($authorize_url); -} - -if (isset($_POST['edit_mail_smtp_settings'])) { - - validateCSRFToken(); - - $config_smtp_provider = escapeSql($_POST['config_smtp_provider']); - $config_smtp_host = escapeSql($_POST['config_smtp_host'] ?? $config_smtp_host); - $config_smtp_port = intval($_POST['config_smtp_port'] ?? $config_smtp_port); - $config_smtp_encryption = escapeSql($_POST['config_smtp_encryption'] ?? $config_smtp_encryption); - $config_smtp_username = escapeSql($_POST['config_smtp_username'] ?? $config_smtp_username); - $config_smtp_password = escapeSql($_POST['config_smtp_password'] ?? $config_smtp_password); - - mysqli_query($mysqli, " - UPDATE settings SET - config_smtp_provider = '$config_smtp_provider', - 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' - WHERE company_id = 1 - "); - - logAudit("Settings", "Edit", "$session_name edited SMTP settings"); - - flashAlert("SMTP Mail Settings updated"); - - redirect($mail_tab_redirect); - -} - -if (isset($_POST['edit_mail_imap_settings'])) { - - validateCSRFToken(); - - $config_imap_provider = escapeSql($_POST['config_imap_provider']); - $config_imap_host = escapeSql($_POST['config_imap_host'] ?? $config_imap_host); - $config_imap_port = intval($_POST['config_imap_port'] ?? $config_imap_port); - $config_imap_encryption = escapeSql($_POST['config_imap_encryption'] ?? $config_imap_encryption); - $config_imap_username = escapeSql($_POST['config_imap_username'] ?? $config_imap_username); - $config_imap_password = escapeSql($_POST['config_imap_password'] ?? $config_imap_password); - - mysqli_query($mysqli, " - UPDATE settings SET - config_imap_provider = '$config_imap_provider', - config_imap_host = '$config_imap_host', - config_imap_port = $config_imap_port, - config_imap_encryption = '$config_imap_encryption', - config_imap_username = '$config_imap_username', - config_imap_password = '$config_imap_password' - WHERE company_id = 1 - "); - - logAudit("Settings", "Edit", "$session_name edited IMAP settings"); - - flashAlert("IMAP Mail Settings updated"); - - redirect($mail_tab_redirect); - -} - -if (isset($_POST['edit_mail_oauth_settings'])) { - - validateCSRFToken(); - - $config_mail_oauth_client_id = escapeSql($_POST['config_mail_oauth_client_id'] ?? ''); - $config_mail_oauth_client_secret = escapeSql($_POST['config_mail_oauth_client_secret'] ?? ''); - $config_mail_oauth_tenant_id = escapeSql($_POST['config_mail_oauth_tenant_id'] ?? $config_mail_oauth_tenant_id); - $config_mail_oauth_refresh_token = escapeSql($_POST['config_mail_oauth_refresh_token'] ?? ''); - $config_mail_oauth_access_token = escapeSql($_POST['config_mail_oauth_access_token'] ?? ''); - - mysqli_query($mysqli, "UPDATE settings SET - config_mail_oauth_client_id = '$config_mail_oauth_client_id', - config_mail_oauth_client_secret = '$config_mail_oauth_client_secret', - config_mail_oauth_tenant_id = '$config_mail_oauth_tenant_id', - config_mail_oauth_refresh_token = '$config_mail_oauth_refresh_token', - config_mail_oauth_access_token = '$config_mail_oauth_access_token' - WHERE company_id = 1 - "); - - logAudit("Settings", "Edit", "$session_name edited mail OAuth settings"); - flashAlert("Mail OAuth Settings updated"); - redirect($mail_tab_redirect); -} - -if (isset($_POST['edit_mail_from_settings'])) { - - validateCSRFToken(); - - $config_mail_from_email = escapeSql(filter_var($_POST['config_mail_from_email'], FILTER_VALIDATE_EMAIL)); - $config_mail_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_mail_from_name'])); - - $config_invoice_from_email = escapeSql(filter_var($_POST['config_invoice_from_email'], FILTER_VALIDATE_EMAIL)); - $config_invoice_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_invoice_from_name'])); - - $config_quote_from_email = escapeSql(filter_var($_POST['config_quote_from_email'], FILTER_VALIDATE_EMAIL)); - $config_quote_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_quote_from_name'])); - - $config_ticket_from_email = escapeSql(filter_var($_POST['config_ticket_from_email'], FILTER_VALIDATE_EMAIL)); - $config_ticket_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_ticket_from_name'])); - - mysqli_query($mysqli,"UPDATE settings SET config_mail_from_email = '$config_mail_from_email', config_mail_from_name = '$config_mail_from_name', config_invoice_from_email = '$config_invoice_from_email', config_invoice_from_name = '$config_invoice_from_name', config_quote_from_email = '$config_quote_from_email', config_quote_from_name = '$config_quote_from_name', config_ticket_from_email = '$config_ticket_from_email', config_ticket_from_name = '$config_ticket_from_name' WHERE company_id = 1"); - - logAudit("Settings", "Edit", "$session_name edited mail from settings"); - - flashAlert("Mail From Settings updated"); - - redirect($mail_tab_redirect); - -} - -if (isset($_POST['test_email_smtp'])) { - - validateCSRFToken(); - - $test_email = intval($_POST['test_email']); - - if($test_email == 1) { - $email_from = escapeSql($config_mail_from_email); - $email_from_name = escapeSql($config_mail_from_name); - } elseif ($test_email == 2) { - $email_from = escapeSql($config_invoice_from_email); - $email_from_name = escapeSql($config_invoice_from_name); - } elseif ($test_email == 3) { - $email_from = escapeSql($config_quote_from_email); - $email_from_name = escapeSql($config_quote_from_name); - } else { - $email_from = escapeSql($config_ticket_from_email); - $email_from_name = escapeSql($config_ticket_from_name); - } - - $email_to = escapeSql($_POST['email_to']); - $subject = "Test email from ITFlow"; - $body = "This is a test email from ITFlow. If you are reading this, it worked!"; - - $data = [ - [ - 'from' => $email_from, - 'from_name' => $email_from_name, - 'recipient' => $email_to, - 'recipient_name' => 'Chap', - 'subject' => $subject, - 'body' => $body - ] - ]; - - $mail = addToMailQueue($data); - - if ($mail === true) { - flashAlert("Test email queued! Check Admin > Mail queue"); - } else { - flashAlert("Failed to add test mail to queue", 'error'); - } - - redirect($mail_tab_redirect); - -} - -if (isset($_POST['test_email_imap'])) { - - validateCSRFToken(); - - $provider = escapeSql($config_imap_provider ?? ''); - - $host = $config_imap_host; - $port = (int) $config_imap_port; - $encryption = strtolower(trim($config_imap_encryption)); // e.g. "ssl", "tls", "none" - $username = $config_imap_username; - $password = $config_imap_password; - - // Shared OAuth fields - $config_mail_oauth_client_id = $config_mail_oauth_client_id ?? ''; - $config_mail_oauth_client_secret = $config_mail_oauth_client_secret ?? ''; - $config_mail_oauth_tenant_id = $config_mail_oauth_tenant_id ?? ''; - $config_mail_oauth_refresh_token = $config_mail_oauth_refresh_token ?? ''; - $config_mail_oauth_access_token = $config_mail_oauth_access_token ?? ''; - $config_mail_oauth_access_token_expires_at = $config_mail_oauth_access_token_expires_at ?? ''; - - $is_oauth = ($provider === 'google_oauth' || $provider === 'microsoft_oauth'); - - if ($provider === 'google_oauth') { - if (empty($host)) { - $host = 'imap.gmail.com'; - } - if (empty($port)) { - $port = 993; - } - if (empty($encryption)) { - $encryption = 'ssl'; - } - } elseif ($provider === 'microsoft_oauth') { - if (empty($host)) { - $host = 'outlook.office365.com'; - } - if (empty($port)) { - $port = 993; - } - if (empty($encryption)) { - $encryption = 'ssl'; - } - } - - if (empty($host) || empty($port) || empty($username)) { - flashAlert("IMAP connection failed: Missing host, port, or username.", 'error'); - redirect($mail_tab_redirect); - } - - $token_is_expired = function (?string $expires_at): bool { - if (empty($expires_at)) { - return true; - } - - $ts = strtotime($expires_at); - - if ($ts === false) { - return true; - } - - return ($ts - 60) <= time(); - }; - - $http_form_post = function (string $url, array $fields): array { - $ch = curl_init($url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields, '', '&')); - curl_setopt($ch, CURLOPT_TIMEOUT, 20); - - $raw = curl_exec($ch); - $err = curl_error($ch); - $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - - curl_close($ch); - - return [ - 'ok' => ($raw !== false && $code >= 200 && $code < 300), - 'body' => $raw, - 'code' => $code, - 'err' => $err, - ]; - }; - - if ($is_oauth) { - if (!empty($config_mail_oauth_access_token) && !$token_is_expired($config_mail_oauth_access_token_expires_at)) { - $password = $config_mail_oauth_access_token; - } else { - if (empty($config_mail_oauth_client_id) || empty($config_mail_oauth_client_secret) || empty($config_mail_oauth_refresh_token)) { - flashAlert("IMAP OAuth failed: Missing OAuth client credentials or refresh token.", 'error'); - redirect($mail_tab_redirect); - } - - if ($provider === 'google_oauth') { - $response = $http_form_post('https://oauth2.googleapis.com/token', [ - 'client_id' => $config_mail_oauth_client_id, - 'client_secret' => $config_mail_oauth_client_secret, - 'refresh_token' => $config_mail_oauth_refresh_token, - 'grant_type' => 'refresh_token', - ]); - } else { - if (empty($config_mail_oauth_tenant_id)) { - flashAlert("IMAP OAuth failed: Microsoft tenant ID is required.", 'error'); - redirect($mail_tab_redirect); - } - - $token_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($config_mail_oauth_tenant_id) . "/oauth2/v2.0/token"; - $response = $http_form_post($token_url, [ - 'client_id' => $config_mail_oauth_client_id, - 'client_secret' => $config_mail_oauth_client_secret, - 'refresh_token' => $config_mail_oauth_refresh_token, - 'grant_type' => 'refresh_token', - ]); - } - - if (!$response['ok']) { - flashAlert("IMAP OAuth failed: Could not refresh access token.", 'error'); - redirect($mail_tab_redirect); - } - - $json = json_decode($response['body'], true); - if (!is_array($json) || empty($json['access_token'])) { - flashAlert("IMAP OAuth failed: Token response did not include an access token.", 'error'); - redirect($mail_tab_redirect); - } - - $password = $json['access_token']; - $expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600)); - $refresh_token_to_save = $json['refresh_token'] ?? null; - - $token_esc = mysqli_real_escape_string($mysqli, $password); - $expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at); - - $refresh_sql = ''; - if (!empty($refresh_token_to_save)) { - $refresh_token_esc = mysqli_real_escape_string($mysqli, $refresh_token_to_save); - $refresh_sql = ", config_mail_oauth_refresh_token = '{$refresh_token_esc}'"; - } - - mysqli_query($mysqli, "UPDATE settings SET config_mail_oauth_access_token = '{$token_esc}', config_mail_oauth_access_token_expires_at = '{$expires_at_esc}'{$refresh_sql} WHERE company_id = 1"); - } - } - - // Build remote socket (implicit SSL vs plain TCP) - require_once $_SERVER['DOCUMENT_ROOT'] . '/libs/vendor/autoload.php'; // ImapEngine (composer) - - // Map the stored encryption value to an ImapEngine transport (matches the cron sync) - $imap_transport = match ($encryption) { - 'ssl' => 'ssl', // implicit TLS (993) - 'tls' => 'starttls', // STARTTLS upgrade (143) - Webklex semantics - 'starttls' => 'starttls', - default => '', // 'none' / plain TCP - }; - - try { - // Same ImapEngine client the cron sync uses, so a passing test predicts a - // working sync. Typed errors instead of raw banners; host validated at save. - $mailbox = new \DirectoryTree\ImapEngine\Mailbox([ - 'host' => $host, - 'port' => $port, - 'encryption' => $imap_transport, - 'validate_cert' => true, - 'username' => $username, - 'password' => $password, // access token when OAuth - 'authentication' => $is_oauth ? 'oauth' : 'plain', - ]); - - $mailbox->connect(); - $mailbox->inbox(); // confirm auth + mailbox access, like the sync does - - flashAlert($is_oauth ? "Connected successfully using OAuth" : "Connected successfully"); - } catch (\Throwable $e) { - flashAlert("IMAP connection failed. Check the host, port, encryption, and credentials.", 'error'); - } - - redirect($mail_tab_redirect); -} - - -if (isset($_POST['test_oauth_token_refresh'])) { - - validateCSRFToken(); - - $provider = escapeSql($_POST['oauth_provider'] ?? ''); - - if ($provider !== 'google_oauth' && $provider !== 'microsoft_oauth') { - flashAlert("OAuth token test failed: unsupported provider.", 'error'); - redirect($mail_tab_redirect); - } - - $oauth_client_id = escapeSql($config_mail_oauth_client_id ?? ''); - $oauth_client_secret = escapeSql($config_mail_oauth_client_secret ?? ''); - $oauth_tenant_id = escapeSql($config_mail_oauth_tenant_id ?? ''); - $oauth_refresh_token = escapeSql($config_mail_oauth_refresh_token ?? ''); - - if (empty($oauth_client_id) || empty($oauth_client_secret) || empty($oauth_refresh_token)) { - flashAlert("OAuth token test failed: missing client ID, client secret, or refresh token.", 'error'); - redirect($mail_tab_redirect); - } - - if ($provider === 'microsoft_oauth' && empty($oauth_tenant_id)) { - flashAlert("OAuth token test failed: Microsoft tenant ID is required.", 'error'); - redirect($mail_tab_redirect); - } - - $token_url = 'https://oauth2.googleapis.com/token'; - if ($provider === 'microsoft_oauth') { - $token_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($oauth_tenant_id) . "/oauth2/v2.0/token"; - } - - $post_fields = http_build_query([ - 'client_id' => $oauth_client_id, - 'client_secret' => $oauth_client_secret, - 'refresh_token' => $oauth_refresh_token, - 'grant_type' => 'refresh_token', - ]); - - $ch = curl_init($token_url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); - curl_setopt($ch, CURLOPT_TIMEOUT, 20); - - $raw_body = curl_exec($ch); - $curl_err = curl_error($ch); - $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - curl_close($ch); - - if ($raw_body === false || $http_code < 200 || $http_code >= 300) { - $err_msg = !empty($curl_err) ? $curl_err : "HTTP $http_code"; - flashAlert("OAuth token test failed: $err_msg", 'error'); - redirect($mail_tab_redirect); - } - - $json = json_decode($raw_body, true); - - if (!is_array($json) || empty($json['access_token'])) { - flashAlert("OAuth token test failed: access token missing in provider response.", 'error'); - redirect($mail_tab_redirect); - } - - $new_access_token = escapeSql($json['access_token']); - $new_expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600)); - $new_refresh_token = !empty($json['refresh_token']) ? escapeSql($json['refresh_token']) : ''; - - $new_access_token_esc = mysqli_real_escape_string($mysqli, $new_access_token); - $new_expires_at_esc = mysqli_real_escape_string($mysqli, $new_expires_at); - - $refresh_sql = ''; - if (!empty($new_refresh_token)) { - $new_refresh_token_esc = mysqli_real_escape_string($mysqli, $new_refresh_token); - $refresh_sql = ", config_mail_oauth_refresh_token = '$new_refresh_token_esc'"; - } - - mysqli_query($mysqli, "UPDATE settings SET config_mail_oauth_access_token = '$new_access_token_esc', config_mail_oauth_access_token_expires_at = '$new_expires_at_esc'$refresh_sql WHERE company_id = 1"); - - $provider_label = $provider === 'microsoft_oauth' ? 'Microsoft 365' : 'Google Workspace'; - logAudit("Settings", "Edit", "$session_name tested OAuth token refresh for $provider_label mail settings"); - - flashAlert("OAuth token refresh successful for $provider_label. Access token expires at $new_expires_at."); - redirect($mail_tab_redirect); -} + $config_mail_oauth_client_id, + 'response_type' => 'code', + 'redirect_uri' => $redirect_uri, + 'response_mode' => 'query', + 'scope' => $scope, + 'state' => $state, + 'prompt' => 'consent', + ], '', '&', PHP_QUERY_RFC3986); + + logAudit("Settings", "Edit", "$session_name started Microsoft OAuth connect flow for mail settings"); + + redirect($authorize_url); +} + +if (isset($_POST['edit_mail_smtp_settings'])) { + + validateCSRFToken(); + + $config_smtp_provider = escapeSql($_POST['config_smtp_provider']); + $config_smtp_host = escapeSql($_POST['config_smtp_host'] ?? $config_smtp_host); + $config_smtp_port = intval($_POST['config_smtp_port'] ?? $config_smtp_port); + $config_smtp_encryption = escapeSql($_POST['config_smtp_encryption'] ?? $config_smtp_encryption); + $config_smtp_username = escapeSql($_POST['config_smtp_username'] ?? $config_smtp_username); + $config_smtp_password = escapeSql($_POST['config_smtp_password'] ?? $config_smtp_password); + + mysqli_query($mysqli, " + UPDATE settings SET + config_smtp_provider = '$config_smtp_provider', + 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' + WHERE company_id = 1 + "); + + logAudit("Settings", "Edit", "$session_name edited SMTP settings"); + + flashAlert("SMTP Mail Settings updated"); + + redirect($mail_tab_redirect); + +} + +if (isset($_POST['edit_mail_imap_settings'])) { + + validateCSRFToken(); + + $config_imap_provider = escapeSql($_POST['config_imap_provider']); + $config_imap_host = escapeSql($_POST['config_imap_host'] ?? $config_imap_host); + $config_imap_port = intval($_POST['config_imap_port'] ?? $config_imap_port); + $config_imap_encryption = escapeSql($_POST['config_imap_encryption'] ?? $config_imap_encryption); + $config_imap_username = escapeSql($_POST['config_imap_username'] ?? $config_imap_username); + $config_imap_password = escapeSql($_POST['config_imap_password'] ?? $config_imap_password); + + mysqli_query($mysqli, " + UPDATE settings SET + config_imap_provider = '$config_imap_provider', + config_imap_host = '$config_imap_host', + config_imap_port = $config_imap_port, + config_imap_encryption = '$config_imap_encryption', + config_imap_username = '$config_imap_username', + config_imap_password = '$config_imap_password' + WHERE company_id = 1 + "); + + logAudit("Settings", "Edit", "$session_name edited IMAP settings"); + + flashAlert("IMAP Mail Settings updated"); + + redirect($mail_tab_redirect); + +} + +if (isset($_POST['edit_mail_oauth_settings'])) { + + validateCSRFToken(); + + $config_mail_oauth_client_id = escapeSql($_POST['config_mail_oauth_client_id'] ?? ''); + $config_mail_oauth_client_secret = escapeSql($_POST['config_mail_oauth_client_secret'] ?? ''); + $config_mail_oauth_tenant_id = escapeSql($_POST['config_mail_oauth_tenant_id'] ?? $config_mail_oauth_tenant_id); + $config_mail_oauth_refresh_token = escapeSql($_POST['config_mail_oauth_refresh_token'] ?? ''); + $config_mail_oauth_access_token = escapeSql($_POST['config_mail_oauth_access_token'] ?? ''); + + mysqli_query($mysqli, "UPDATE settings SET + config_mail_oauth_client_id = '$config_mail_oauth_client_id', + config_mail_oauth_client_secret = '$config_mail_oauth_client_secret', + config_mail_oauth_tenant_id = '$config_mail_oauth_tenant_id', + config_mail_oauth_refresh_token = '$config_mail_oauth_refresh_token', + config_mail_oauth_access_token = '$config_mail_oauth_access_token' + WHERE company_id = 1 + "); + + logAudit("Settings", "Edit", "$session_name edited mail OAuth settings"); + flashAlert("Mail OAuth Settings updated"); + redirect($mail_tab_redirect); +} + +if (isset($_POST['edit_mail_from_settings'])) { + + validateCSRFToken(); + + $config_mail_from_email = escapeSql(filter_var($_POST['config_mail_from_email'], FILTER_VALIDATE_EMAIL)); + $config_mail_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_mail_from_name'])); + + $config_invoice_from_email = escapeSql(filter_var($_POST['config_invoice_from_email'], FILTER_VALIDATE_EMAIL)); + $config_invoice_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_invoice_from_name'])); + + $config_quote_from_email = escapeSql(filter_var($_POST['config_quote_from_email'], FILTER_VALIDATE_EMAIL)); + $config_quote_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_quote_from_name'])); + + $config_ticket_from_email = escapeSql(filter_var($_POST['config_ticket_from_email'], FILTER_VALIDATE_EMAIL)); + $config_ticket_from_name = escapeSql(preg_replace('/[^a-zA-Z0-9\s]/', '', $_POST['config_ticket_from_name'])); + + mysqli_query($mysqli,"UPDATE settings SET config_mail_from_email = '$config_mail_from_email', config_mail_from_name = '$config_mail_from_name', config_invoice_from_email = '$config_invoice_from_email', config_invoice_from_name = '$config_invoice_from_name', config_quote_from_email = '$config_quote_from_email', config_quote_from_name = '$config_quote_from_name', config_ticket_from_email = '$config_ticket_from_email', config_ticket_from_name = '$config_ticket_from_name' WHERE company_id = 1"); + + logAudit("Settings", "Edit", "$session_name edited mail from settings"); + + flashAlert("Mail From Settings updated"); + + redirect($mail_tab_redirect); + +} + +if (isset($_POST['test_email_smtp'])) { + + validateCSRFToken(); + + $test_email = intval($_POST['test_email']); + + if($test_email == 1) { + $email_from = escapeSql($config_mail_from_email); + $email_from_name = escapeSql($config_mail_from_name); + } elseif ($test_email == 2) { + $email_from = escapeSql($config_invoice_from_email); + $email_from_name = escapeSql($config_invoice_from_name); + } elseif ($test_email == 3) { + $email_from = escapeSql($config_quote_from_email); + $email_from_name = escapeSql($config_quote_from_name); + } else { + $email_from = escapeSql($config_ticket_from_email); + $email_from_name = escapeSql($config_ticket_from_name); + } + + $email_to = escapeSql($_POST['email_to']); + $subject = "Test email from ITFlow"; + $body = "This is a test email from ITFlow. If you are reading this, it worked!"; + + $data = [ + [ + 'from' => $email_from, + 'from_name' => $email_from_name, + 'recipient' => $email_to, + 'recipient_name' => 'Chap', + 'subject' => $subject, + 'body' => $body + ] + ]; + + $mail = addToMailQueue($data); + + if ($mail === true) { + flashAlert("Test email queued! Check Admin > Mail queue"); + } else { + flashAlert("Failed to add test mail to queue", 'error'); + } + + redirect($mail_tab_redirect); + +} + +if (isset($_POST['test_email_imap'])) { + + validateCSRFToken(); + + $provider = escapeSql($config_imap_provider ?? ''); + + $host = $config_imap_host; + $port = (int) $config_imap_port; + $encryption = strtolower(trim($config_imap_encryption)); // e.g. "ssl", "tls", "none" + $username = $config_imap_username; + $password = $config_imap_password; + + // Shared OAuth fields + $config_mail_oauth_client_id = $config_mail_oauth_client_id ?? ''; + $config_mail_oauth_client_secret = $config_mail_oauth_client_secret ?? ''; + $config_mail_oauth_tenant_id = $config_mail_oauth_tenant_id ?? ''; + $config_mail_oauth_refresh_token = $config_mail_oauth_refresh_token ?? ''; + $config_mail_oauth_access_token = $config_mail_oauth_access_token ?? ''; + $config_mail_oauth_access_token_expires_at = $config_mail_oauth_access_token_expires_at ?? ''; + + $is_oauth = ($provider === 'google_oauth' || $provider === 'microsoft_oauth'); + + if ($provider === 'google_oauth') { + if (empty($host)) { + $host = 'imap.gmail.com'; + } + if (empty($port)) { + $port = 993; + } + if (empty($encryption)) { + $encryption = 'ssl'; + } + } elseif ($provider === 'microsoft_oauth') { + if (empty($host)) { + $host = 'outlook.office365.com'; + } + if (empty($port)) { + $port = 993; + } + if (empty($encryption)) { + $encryption = 'ssl'; + } + } + + if (empty($host) || empty($port) || empty($username)) { + flashAlert("IMAP connection failed: Missing host, port, or username.", 'error'); + redirect($mail_tab_redirect); + } + + $token_is_expired = function (?string $expires_at): bool { + if (empty($expires_at)) { + return true; + } + + $ts = strtotime($expires_at); + + if ($ts === false) { + return true; + } + + return ($ts - 60) <= time(); + }; + + $http_form_post = function (string $url, array $fields): array { + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields, '', '&')); + curl_setopt($ch, CURLOPT_TIMEOUT, 20); + + $raw = curl_exec($ch); + $err = curl_error($ch); + $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + + curl_close($ch); + + return [ + 'ok' => ($raw !== false && $code >= 200 && $code < 300), + 'body' => $raw, + 'code' => $code, + 'err' => $err, + ]; + }; + + if ($is_oauth) { + if (!empty($config_mail_oauth_access_token) && !$token_is_expired($config_mail_oauth_access_token_expires_at)) { + $password = $config_mail_oauth_access_token; + } else { + if (empty($config_mail_oauth_client_id) || empty($config_mail_oauth_client_secret) || empty($config_mail_oauth_refresh_token)) { + flashAlert("IMAP OAuth failed: Missing OAuth client credentials or refresh token.", 'error'); + redirect($mail_tab_redirect); + } + + if ($provider === 'google_oauth') { + $response = $http_form_post('https://oauth2.googleapis.com/token', [ + 'client_id' => $config_mail_oauth_client_id, + 'client_secret' => $config_mail_oauth_client_secret, + 'refresh_token' => $config_mail_oauth_refresh_token, + 'grant_type' => 'refresh_token', + ]); + } else { + if (empty($config_mail_oauth_tenant_id)) { + flashAlert("IMAP OAuth failed: Microsoft tenant ID is required.", 'error'); + redirect($mail_tab_redirect); + } + + $token_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($config_mail_oauth_tenant_id) . "/oauth2/v2.0/token"; + $response = $http_form_post($token_url, [ + 'client_id' => $config_mail_oauth_client_id, + 'client_secret' => $config_mail_oauth_client_secret, + 'refresh_token' => $config_mail_oauth_refresh_token, + 'grant_type' => 'refresh_token', + ]); + } + + if (!$response['ok']) { + flashAlert("IMAP OAuth failed: Could not refresh access token.", 'error'); + redirect($mail_tab_redirect); + } + + $json = json_decode($response['body'], true); + if (!is_array($json) || empty($json['access_token'])) { + flashAlert("IMAP OAuth failed: Token response did not include an access token.", 'error'); + redirect($mail_tab_redirect); + } + + $password = $json['access_token']; + $expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600)); + $refresh_token_to_save = $json['refresh_token'] ?? null; + + $token_esc = mysqli_real_escape_string($mysqli, $password); + $expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at); + + $refresh_sql = ''; + if (!empty($refresh_token_to_save)) { + $refresh_token_esc = mysqli_real_escape_string($mysqli, $refresh_token_to_save); + $refresh_sql = ", config_mail_oauth_refresh_token = '{$refresh_token_esc}'"; + } + + mysqli_query($mysqli, "UPDATE settings SET config_mail_oauth_access_token = '{$token_esc}', config_mail_oauth_access_token_expires_at = '{$expires_at_esc}'{$refresh_sql} WHERE company_id = 1"); + } + } + + // Build remote socket (implicit SSL vs plain TCP) + require_once $_SERVER['DOCUMENT_ROOT'] . '/libs/vendor/autoload.php'; // ImapEngine (composer) + + // Map the stored encryption value to an ImapEngine transport (matches the cron sync) + $imap_transport = match ($encryption) { + 'ssl' => 'ssl', // implicit TLS (993) + 'tls' => 'starttls', // STARTTLS upgrade (143) - Webklex semantics + 'starttls' => 'starttls', + default => '', // 'none' / plain TCP + }; + + try { + // Same ImapEngine client the cron sync uses, so a passing test predicts a + // working sync. Typed errors instead of raw banners; host validated at save. + $mailbox = new \DirectoryTree\ImapEngine\Mailbox([ + 'host' => $host, + 'port' => $port, + 'encryption' => $imap_transport, + 'validate_cert' => true, + 'username' => $username, + 'password' => $password, // access token when OAuth + 'authentication' => $is_oauth ? 'oauth' : 'plain', + ]); + + $mailbox->connect(); + $mailbox->inbox(); // confirm auth + mailbox access, like the sync does + + flashAlert($is_oauth ? "Connected successfully using OAuth" : "Connected successfully"); + } catch (\Throwable $e) { + flashAlert("IMAP connection failed. Check the host, port, encryption, and credentials.", 'error'); + } + + redirect($mail_tab_redirect); +} + + +if (isset($_POST['test_oauth_token_refresh'])) { + + validateCSRFToken(); + + $provider = escapeSql($_POST['oauth_provider'] ?? ''); + + if ($provider !== 'google_oauth' && $provider !== 'microsoft_oauth') { + flashAlert("OAuth token test failed: unsupported provider.", 'error'); + redirect($mail_tab_redirect); + } + + $oauth_client_id = escapeSql($config_mail_oauth_client_id ?? ''); + $oauth_client_secret = escapeSql($config_mail_oauth_client_secret ?? ''); + $oauth_tenant_id = escapeSql($config_mail_oauth_tenant_id ?? ''); + $oauth_refresh_token = escapeSql($config_mail_oauth_refresh_token ?? ''); + + if (empty($oauth_client_id) || empty($oauth_client_secret) || empty($oauth_refresh_token)) { + flashAlert("OAuth token test failed: missing client ID, client secret, or refresh token.", 'error'); + redirect($mail_tab_redirect); + } + + if ($provider === 'microsoft_oauth' && empty($oauth_tenant_id)) { + flashAlert("OAuth token test failed: Microsoft tenant ID is required.", 'error'); + redirect($mail_tab_redirect); + } + + $token_url = 'https://oauth2.googleapis.com/token'; + if ($provider === 'microsoft_oauth') { + $token_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($oauth_tenant_id) . "/oauth2/v2.0/token"; + } + + $post_fields = http_build_query([ + 'client_id' => $oauth_client_id, + 'client_secret' => $oauth_client_secret, + 'refresh_token' => $oauth_refresh_token, + 'grant_type' => 'refresh_token', + ]); + + $ch = curl_init($token_url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); + curl_setopt($ch, CURLOPT_TIMEOUT, 20); + + $raw_body = curl_exec($ch); + $curl_err = curl_error($ch); + $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); + + if ($raw_body === false || $http_code < 200 || $http_code >= 300) { + $err_msg = !empty($curl_err) ? $curl_err : "HTTP $http_code"; + flashAlert("OAuth token test failed: $err_msg", 'error'); + redirect($mail_tab_redirect); + } + + $json = json_decode($raw_body, true); + + if (!is_array($json) || empty($json['access_token'])) { + flashAlert("OAuth token test failed: access token missing in provider response.", 'error'); + redirect($mail_tab_redirect); + } + + $new_access_token = escapeSql($json['access_token']); + $new_expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600)); + $new_refresh_token = !empty($json['refresh_token']) ? escapeSql($json['refresh_token']) : ''; + + $new_access_token_esc = mysqli_real_escape_string($mysqli, $new_access_token); + $new_expires_at_esc = mysqli_real_escape_string($mysqli, $new_expires_at); + + $refresh_sql = ''; + if (!empty($new_refresh_token)) { + $new_refresh_token_esc = mysqli_real_escape_string($mysqli, $new_refresh_token); + $refresh_sql = ", config_mail_oauth_refresh_token = '$new_refresh_token_esc'"; + } + + mysqli_query($mysqli, "UPDATE settings SET config_mail_oauth_access_token = '$new_access_token_esc', config_mail_oauth_access_token_expires_at = '$new_expires_at_esc'$refresh_sql WHERE company_id = 1"); + + $provider_label = $provider === 'microsoft_oauth' ? 'Microsoft 365' : 'Google Workspace'; + logAudit("Settings", "Edit", "$session_name tested OAuth token refresh for $provider_label mail settings"); + + flashAlert("OAuth token refresh successful for $provider_label. Access token expires at $new_expires_at."); + redirect($mail_tab_redirect); +} diff --git a/admin/settings_mail.php b/admin/settings_mail.php index 05d521f5..bb1866d7 100644 --- a/admin/settings_mail.php +++ b/admin/settings_mail.php @@ -1,565 +1,565 @@ -' - : ''; -} - -$smtp_on = !empty($config_smtp_provider); -$imap_on = !empty($config_imap_provider); -$oauth_needed = in_array($config_smtp_provider, ['google_oauth', 'microsoft_oauth'], true) - || in_array($config_imap_provider, ['google_oauth', 'microsoft_oauth'], true); - -// ---- Active tab ------------------------------------------------------------- -// The tab lives in the URL (?tab=imap) so it can be linked, bookmarked, survives a -// reload, and lets the POST handlers send you back to the tab you saved from -$mail_tabs = ['smtp', 'imap', 'oauth', 'from', 'tests']; -$active_tab = isset($_GET['tab']) && in_array($_GET['tab'], $mail_tabs, true) ? $_GET['tab'] : 'smtp'; - -// A direct link to the OAuth tab reveals it even when no OAuth provider is selected yet -if ($active_tab === 'oauth') { - $oauth_needed = true; -} - -// ---- OAuth callback URI (for Entra App Registration) ------------------------ -if (defined('BASE_URL') && !empty(BASE_URL)) { - $mail_oauth_callback_uri = rtrim((string) BASE_URL, '/') . '/admin/oauth_microsoft_mail_callback.php'; -} else { - $mail_oauth_callback_uri = 'https://' . rtrim((string) $config_base_url, '/') . '/admin/oauth_microsoft_mail_callback.php'; -} - -// ---- Readiness checks (drive the Tests tab) -------------------------------- -$smtp_standard_ready = !empty($config_smtp_host) && !empty($config_smtp_port) - && !empty($config_mail_from_email) && !empty($config_mail_from_name); - -$smtp_oauth_ready = in_array($config_smtp_provider, ['google_oauth', 'microsoft_oauth'], true) - && !empty($config_mail_from_email) && !empty($config_mail_from_name) - && !empty($config_mail_oauth_client_id) && !empty($config_mail_oauth_client_secret) - && !empty($config_mail_oauth_refresh_token) - && ($config_smtp_provider !== 'microsoft_oauth' || !empty($config_mail_oauth_tenant_id)); - -$imap_standard_ready = !empty($config_imap_username) && !empty($config_imap_password) - && !empty($config_imap_host) && !empty($config_imap_port); - -$imap_oauth_ready = in_array($config_imap_provider, ['google_oauth', 'microsoft_oauth'], true) - && !empty($config_imap_username) - && !empty($config_mail_oauth_client_id) && !empty($config_mail_oauth_client_secret) - && !empty($config_mail_oauth_refresh_token) - && ($config_imap_provider !== 'microsoft_oauth' || !empty($config_mail_oauth_tenant_id)); - -$oauth_provider_for_test = ''; -if (in_array($config_imap_provider, ['google_oauth', 'microsoft_oauth'], true)) { - $oauth_provider_for_test = $config_imap_provider; -} elseif (in_array($config_smtp_provider, ['google_oauth', 'microsoft_oauth'], true)) { - $oauth_provider_for_test = $config_smtp_provider; -} - -$oauth_has_required_fields = !empty($oauth_provider_for_test) - && !empty($config_mail_oauth_client_id) && !empty($config_mail_oauth_client_secret) - && !empty($config_mail_oauth_refresh_token) - && ($oauth_provider_for_test !== 'microsoft_oauth' || !empty($config_mail_oauth_tenant_id)); - -$send_ready = $smtp_standard_ready || $smtp_oauth_ready; -$imap_ready = $imap_standard_ready || $imap_oauth_ready; -?> - -
-
-

Mail Configuration

-
-
- - - -
- - -
-
- - - -
- -
-
- -
- Choose your outbound mail provider. -
- -
-
-
- -
-
- -
-
-
- -
-
- -
-
-
- -
-
- -
-
-
-
- -
-
- -
-
- -
- Leave blank if no authentication is required. -
-
- -
-
- -
-
-
-
- - - -
- -
-
- - -
-
- - - -
- -
-
- -
- Select your mailbox provider. -
- -
-
-
- -
-
- -
-
-
- -
-
- -
-
-
- -
-
- -
-
-
-
- -
-
- -
-
- -
- The mailbox address to monitor for incoming tickets. -
-
- -
-
- -
-
-
-
- - - -
- -
-
- - -
-
- - - -
- These credentials are shared by any Sending or Receiving provider set to Google / Microsoft OAuth. -
- -
-
- -
-
- -
-
-
- -
-
- -
-
-
-
- - - -
-
- - -
-
- - - Expires at: -
-
- - - -
- -
-
- - -
-
- - - -

Each From address must be allowed to send on behalf of the SMTP user.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PurposeFrom EmailFrom Name
System Default
share links & system tasks
Invoices
sent when emailing invoices
Quotes
sent when emailing quotes
Tickets
ticket creation & client replies
- - -
-
- - -
- - -
- Finish configuring Sending, Receiving, or OAuth (plus at least one From address) to unlock the tests. -
- - - -
-
Send a Test Email
-
- - -
- - -
- -
-
-
-
- - - -
-
Test IMAP Connection
-
- - - -
-
- - - -
-
Test OAuth Token Refresh
-
- - - -

Validates the refresh token and stores a new access token for .

- -
-
- - -
- -
-
-
- - - +' + : ''; +} + +$smtp_on = !empty($config_smtp_provider); +$imap_on = !empty($config_imap_provider); +$oauth_needed = in_array($config_smtp_provider, ['google_oauth', 'microsoft_oauth'], true) + || in_array($config_imap_provider, ['google_oauth', 'microsoft_oauth'], true); + +// ---- Active tab ------------------------------------------------------------- +// The tab lives in the URL (?tab=imap) so it can be linked, bookmarked, survives a +// reload, and lets the POST handlers send you back to the tab you saved from +$mail_tabs = ['smtp', 'imap', 'oauth', 'from', 'tests']; +$active_tab = isset($_GET['tab']) && in_array($_GET['tab'], $mail_tabs, true) ? $_GET['tab'] : 'smtp'; + +// A direct link to the OAuth tab reveals it even when no OAuth provider is selected yet +if ($active_tab === 'oauth') { + $oauth_needed = true; +} + +// ---- OAuth callback URI (for Entra App Registration) ------------------------ +if (defined('BASE_URL') && !empty(BASE_URL)) { + $mail_oauth_callback_uri = rtrim((string) BASE_URL, '/') . '/admin/oauth_microsoft_mail_callback.php'; +} else { + $mail_oauth_callback_uri = 'https://' . rtrim((string) $config_base_url, '/') . '/admin/oauth_microsoft_mail_callback.php'; +} + +// ---- Readiness checks (drive the Tests tab) -------------------------------- +$smtp_standard_ready = !empty($config_smtp_host) && !empty($config_smtp_port) + && !empty($config_mail_from_email) && !empty($config_mail_from_name); + +$smtp_oauth_ready = in_array($config_smtp_provider, ['google_oauth', 'microsoft_oauth'], true) + && !empty($config_mail_from_email) && !empty($config_mail_from_name) + && !empty($config_mail_oauth_client_id) && !empty($config_mail_oauth_client_secret) + && !empty($config_mail_oauth_refresh_token) + && ($config_smtp_provider !== 'microsoft_oauth' || !empty($config_mail_oauth_tenant_id)); + +$imap_standard_ready = !empty($config_imap_username) && !empty($config_imap_password) + && !empty($config_imap_host) && !empty($config_imap_port); + +$imap_oauth_ready = in_array($config_imap_provider, ['google_oauth', 'microsoft_oauth'], true) + && !empty($config_imap_username) + && !empty($config_mail_oauth_client_id) && !empty($config_mail_oauth_client_secret) + && !empty($config_mail_oauth_refresh_token) + && ($config_imap_provider !== 'microsoft_oauth' || !empty($config_mail_oauth_tenant_id)); + +$oauth_provider_for_test = ''; +if (in_array($config_imap_provider, ['google_oauth', 'microsoft_oauth'], true)) { + $oauth_provider_for_test = $config_imap_provider; +} elseif (in_array($config_smtp_provider, ['google_oauth', 'microsoft_oauth'], true)) { + $oauth_provider_for_test = $config_smtp_provider; +} + +$oauth_has_required_fields = !empty($oauth_provider_for_test) + && !empty($config_mail_oauth_client_id) && !empty($config_mail_oauth_client_secret) + && !empty($config_mail_oauth_refresh_token) + && ($oauth_provider_for_test !== 'microsoft_oauth' || !empty($config_mail_oauth_tenant_id)); + +$send_ready = $smtp_standard_ready || $smtp_oauth_ready; +$imap_ready = $imap_standard_ready || $imap_oauth_ready; +?> + +
+
+

Mail Configuration

+
+
+ + + +
+ + +
+
+ + + +
+ +
+
+ +
+ Choose your outbound mail provider. +
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+ +
+ Leave blank if no authentication is required. +
+
+ +
+
+ +
+
+
+
+ + + +
+ +
+
+ + +
+
+ + + +
+ +
+
+ +
+ Select your mailbox provider. +
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+
+ +
+
+ +
+
+ +
+ The mailbox address to monitor for incoming tickets. +
+
+ +
+
+ +
+
+
+
+ + + +
+ +
+
+ + +
+
+ + + +
+ These credentials are shared by any Sending or Receiving provider set to Google / Microsoft OAuth. +
+ +
+
+ +
+
+ +
+
+
+ +
+
+ +
+
+
+
+ + + +
+
+ + +
+
+ + + Expires at: +
+
+ + + +
+ +
+
+ + +
+
+ + + +

Each From address must be allowed to send on behalf of the SMTP user.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PurposeFrom EmailFrom Name
System Default
share links & system tasks
Invoices
sent when emailing invoices
Quotes
sent when emailing quotes
Tickets
ticket creation & client replies
+ + +
+
+ + +
+ + +
+ Finish configuring Sending, Receiving, or OAuth (plus at least one From address) to unlock the tests. +
+ + + +
+
Send a Test Email
+
+ + +
+ + +
+ +
+
+
+
+ + + +
+
Test IMAP Connection
+
+ + + +
+
+ + + +
+
Test OAuth Token Refresh
+
+ + + +

Validates the refresh token and stores a new access token for .

+ +
+
+ + +
+ +
+
+
+ + + \ No newline at end of file diff --git a/agent/post/ticket.php b/agent/post/ticket.php index 33834d08..16fcd5b9 100644 --- a/agent/post/ticket.php +++ b/agent/post/ticket.php @@ -1,2976 +1,2976 @@ - - if ($d !== false) { - $due = "'" . $d->format('Y-m-d H:i:s') . "'"; // wrap in quotes for SQL - } else { - $due = 'NULL'; // fallback if invalid - } - } - - enforceClientAccess(); - - // 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"); - $row = mysqli_fetch_assoc($sql); - $contact_id = intval($row['contact_id']); - } - - // Atomically increment and get the new ticket number - mysqli_query($mysqli, " - UPDATE settings - SET - config_ticket_next_number = LAST_INSERT_ID(config_ticket_next_number), - config_ticket_next_number = config_ticket_next_number + 1 - WHERE company_id = 1 - "); - - $ticket_number = mysqli_insert_id($mysqli); - - // Sanitize Config Vars from get_settings.php and Session Vars from check_login.php - $config_ticket_prefix = escapeSql($config_ticket_prefix); - $config_ticket_from_name = escapeSql($config_ticket_from_name); - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $config_base_url = escapeSql($config_base_url); - - //Generate a unique URL key for clients to access - $url_key = randomString(32); - - mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$config_ticket_prefix', ticket_number = $ticket_number, ticket_source = 'Agent', ticket_category = $category_id, ticket_subject = '$subject', ticket_details = '$details', ticket_priority = '$priority', ticket_billable = '$billable', ticket_status = '$ticket_status', ticket_vendor_ticket_number = '$vendor_ticket_number', ticket_vendor_id = $vendor_id, ticket_location_id = $location_id, ticket_asset_id = $asset_id, ticket_created_by = $session_user_id, ticket_assigned_to = $assigned_to, ticket_contact_id = $contact_id, ticket_url_key = '$url_key', ticket_due_at = $due, ticket_client_id = $client_id, ticket_invoice_id = 0, ticket_project_id = $project_id"); - - $ticket_id = mysqli_insert_id($mysqli); - - // 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_assoc($sql_task_templates)) { - $task_order = intval($row['task_template_order']); - $task_name = escapeSql($row['task_template_name']); - $task_completion_estimate = intval($row['task_template_completion_estimate']); - - mysqli_query($mysqli,"INSERT INTO tasks SET task_name = '$task_name', task_order = $task_order, task_completion_estimate = $task_completion_estimate, task_ticket_id = $ticket_id"); - } - } - } - - // Add Watchers - if (isset($_POST['watchers'])) { - foreach ($_POST['watchers'] as $watcher) { - $watcher_email = escapeSql($watcher); - mysqli_query($mysqli, "INSERT INTO ticket_watchers SET watcher_email = '$watcher_email', watcher_ticket_id = $ticket_id"); - } - } - - // Add Additional Assets - if (isset($_POST['additional_assets'])) { - foreach ($_POST['additional_assets'] as $additional_asset) { - $additional_asset_id = intval($additional_asset); - mysqli_query($mysqli, "INSERT INTO ticket_assets SET ticket_id = $ticket_id, asset_id = $additional_asset_id"); - } - } - - // E-mail client - if ((!empty($config_smtp_provider) || !empty($config_smtp_provider)) && $config_ticket_client_general_notifications == 1) { - - // Get contact/ticket details - $sql = mysqli_query($mysqli, "SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_category, ticket_subject, ticket_details, ticket_priority, ticket_status, ticket_created_by, ticket_assigned_to, ticket_client_id FROM tickets - LEFT JOIN clients ON ticket_client_id = client_id - LEFT JOIN contacts ON ticket_contact_id = contact_id - WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_category = escapeSql($row['ticket_category']); - $ticket_subject = escapeSql($row['ticket_subject']); - $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); - $ticket_priority = escapeSql($row['ticket_priority']); - $ticket_status = escapeSql($row['ticket_status']); - $ticket_status_name = escapeSql(getTicketStatusName($row['ticket_status'])); - $client_id = intval($row['ticket_client_id']); - $ticket_created_by = intval($row['ticket_created_by']); - $ticket_assigned_to = intval($row['ticket_assigned_to']); - - // Get Company Phone Number - $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - // EMAILING - - $subject = "Ticket Created [$ticket_prefix$ticket_number] - $ticket_subject"; - $body = "##- Please type your reply above this line -##

Hello $contact_name,

A ticket regarding \"$ticket_subject\" has been created for you.

--------------------------------
$ticket_details--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: Open
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - - // Verify contact email is valid - if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { - - - // Email Ticket Contact - // Queue Mail - $data = []; - - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - } - - // Also Email all the watchers - $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); - $body .= "

----------------------------------------
YOU HAVE BEEN ADDED AS A COLLABORATOR FOR THIS TICKET"; - while ($row = mysqli_fetch_assoc($sql_watchers)) { - $watcher_email = escapeSql($row['watcher_email']); - - // Queue Mail - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $watcher_email, - 'recipient_name' => $watcher_email, - 'subject' => $subject, - 'body' => $body - ]; - } - addToMailQueue($data); - - // END EMAILING - - } - - // Custom action/notif handler - triggerCustomAction('ticket_create', $ticket_id); - - logAudit("Ticket", "Create", "$session_name created ticket $config_ticket_prefix$ticket_number - $ticket_subject", $client_id, $ticket_id); - - flashAlert("Ticket $config_ticket_prefix$ticket_number created"); - - redirect("ticket.php?client_id=$client_id&ticket_id=$ticket_id"); - -} - -if (isset($_POST['edit_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); - $contact_id = intval($_POST['contact_id']); - $assigned_to = intval($_POST['assigned_to']); - $notify = intval($_POST['contact_notify'] ?? 0); - $category_id = intval($_POST['category_id']); - $ticket_subject = escapeSql($_POST['subject']); - $billable = intval($_POST['billable'] ?? 0); - $ticket_priority = escapeSql($_POST['priority']); - $details = mysqli_real_escape_string($mysqli, $_POST['details']); - $vendor_ticket_number = escapeSql($_POST['vendor_ticket_number']); - $vendor_id = intval($_POST['vendor_id']); - $asset_id = intval($_POST['asset_id']); - $location_id = intval($_POST['location_id']); - $project_id = intval($_POST['project_id']); - // Validate/clean due field - $dueInput = $_POST['due'] ?? null; - if ($dueInput === null || trim($dueInput) === '') { - $due = 'NULL'; // prepare as SQL-safe string - } else { - $d = DateTime::createFromFormat('Y-m-d\TH:i', $dueInput); // for - if ($d !== false) { - $due = "'" . $d->format('Y-m-d H:i:s') . "'"; // wrap in quotes for SQL - } else { - $due = 'NULL'; // fallback if invalid - } - } - - $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "UPDATE tickets SET ticket_category = $category_id, ticket_subject = '$ticket_subject', ticket_priority = '$ticket_priority', ticket_billable = $billable, ticket_details = '$details', ticket_due_at = $due, ticket_vendor_ticket_number = '$vendor_ticket_number', ticket_contact_id = $contact_id, ticket_assigned_to = $assigned_to, ticket_vendor_id = $vendor_id, ticket_location_id = $location_id, ticket_asset_id = $asset_id, ticket_project_id = $project_id WHERE ticket_id = $ticket_id"); - - // Add Additional Assets - if (isset($_POST['additional_assets'])) { - mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id"); - foreach ($_POST['additional_assets'] as $additional_asset) { - $additional_asset_id = intval($additional_asset); - mysqli_query($mysqli, "INSERT INTO ticket_assets SET ticket_id = $ticket_id, asset_id = $additional_asset_id"); - } - } else { - // If no additional assets are provided, delete them all - // This handles cases where the assets input might be cleared or not set at all. - mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id"); - } - - // Get contact/ticket details after update for logging / email purposes - $sql = mysqli_query($mysqli, "SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_category, ticket_details, ticket_status_name, ticket_created_by, ticket_assigned_to, ticket_url_key, ticket_client_id FROM tickets - LEFT JOIN clients ON ticket_client_id = client_id - LEFT JOIN contacts ON ticket_contact_id = contact_id - LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id - WHERE ticket_id = $ticket_id - AND ticket_closed_at IS NULL"); - $row = mysqli_fetch_assoc($sql); - - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_category = escapeSql($row['ticket_category']); - $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); - $ticket_status = escapeSql($row['ticket_status_name']); - $ticket_created_by = intval($row['ticket_created_by']); - $ticket_assigned_to = intval($row['ticket_assigned_to']); - $url_key = escapeSql($row['ticket_url_key']); - $client_id = intval($row['ticket_client_id']); - - // Notify new contact if selected - if ($notify && (!empty($config_smtp_provider) || !empty($config_smtp_provider))) { - - // Get Company Name Phone Number and Sanitize for Email Sending - $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - // Email content - $data = []; // Queue array - - $subject = "Ticket Created - [$ticket_prefix$ticket_number] - $ticket_subject"; - $body = "##- Please type your reply above this line -##

Hello $contact_name,

A ticket regarding \"$ticket_subject\" has been created for you.

--------------------------------
$ticket_details--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - - - // Only add contact to email queue if email is valid - if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - } - - addToMailQueue($data); - } - - // Custom action/notif handler - triggerCustomAction('ticket_update', $ticket_id); - - logAudit("Ticket", "Edit", "$session_name edited ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); - - flashAlert("Ticket $ticket_prefix$ticket_number updated"); - - redirect(); - -} - -if (isset($_POST['edit_ticket_priority'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); - $priority = escapeSql($_POST['priority']); - - // Get ticket details before updating - $sql = mysqli_query($mysqli, "SELECT - ticket_prefix, ticket_number, ticket_priority, ticket_status_name, ticket_client_id - FROM tickets - LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id - WHERE ticket_id = $ticket_id" - ); - $row = mysqli_fetch_assoc($sql); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $original_priority = escapeSql($row['ticket_priority']); - $ticket_status = escapeSql($row['ticket_status_name']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "UPDATE tickets SET ticket_priority = '$priority' WHERE ticket_id = $ticket_id"); - - // Update Ticket History - mysqli_query($mysqli, "INSERT INTO ticket_history SET ticket_history_status = '$ticket_status', ticket_history_description = '$session_name changed priority from $original_priority to $priority', ticket_history_ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name changed priority from $original_priority to $priority for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); - - triggerCustomAction('ticket_update', $ticket_id); - - flashAlert("Priority updated from $original_priority to $priority"); - - redirect(); - -} - -if (isset($_POST['edit_ticket_contact'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); - $contact_id = intval($_POST['contact']); - $notify = intval($_POST['contact_notify']) ?? 0; - - // Get Original contact, and ticket details - $sql = mysqli_query($mysqli, "SELECT - contact_name, ticket_prefix, ticket_number, ticket_status_name, ticket_subject, ticket_details, ticket_url_key, ticket_client_id - FROM tickets - LEFT JOIN contacts ON ticket_contact_id = contact_id - LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id - WHERE ticket_id = $ticket_id" - ); - $row = mysqli_fetch_assoc($sql); - - // Original contact - $original_contact_name = !empty($row['contact_name']) ? escapeSql($row['contact_name']) : 'No one'; - - // Ticket details - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_status = escapeSql($row['ticket_status_name']); - $ticket_subject = escapeSql($row['ticket_subject']); - $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); - $url_key = escapeSql($row['ticket_url_key']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - // Update the contact - mysqli_query($mysqli, "UPDATE tickets SET ticket_contact_id = $contact_id WHERE ticket_id = $ticket_id"); - - // Get New contact details - $sql = mysqli_query($mysqli, "SELECT contact_name, contact_email FROM contacts WHERE contact_id = $contact_id"); - $row = mysqli_fetch_assoc($sql); - - $contact_name = !empty($row['contact_name']) ? escapeSql($row['contact_name']) : 'No one'; - $contact_email = escapeSql($row['contact_email']); - - // Notify new contact (if selected, valid & configured) - if ($notify && filter_var($contact_email, FILTER_VALIDATE_EMAIL) && (!empty($config_smtp_provider) || !empty($config_smtp_provider))) { - - // Get Company Phone Number - $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $config_ticket_from_name = escapeSql($config_ticket_from_name); - - // Email content - $data = []; // Queue array - - $subject = "Ticket Created - [$ticket_prefix$ticket_number] - $ticket_subject"; - $body = "##- Please type your reply above this line -##

Hello $contact_name,

A ticket regarding \"$ticket_subject\" has been created for you.

--------------------------------
$ticket_details--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - - addToMailQueue($data); - } - - // Custom action/notif handler - triggerCustomAction('ticket_update', $ticket_id); - - // Update Ticket History - mysqli_query($mysqli, "INSERT INTO ticket_history SET ticket_history_status = '$ticket_status', ticket_history_description = '$session_name changed the contact from $original_contact_name to $contact_name', ticket_history_ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name changed the contact from $original_contact_name to $contact_name for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); - - flashAlert("Contact changed from $original_contact_name to $contact_name"); - - redirect(); - -} - -if (isset($_POST['edit_ticket_project'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); - $project_id = intval($_POST['project']); - - $project_name = escapeSql(getFieldById('projects', $project_id, 'project_name')); - $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); - $ticket_prefix = escapeSql(getFieldById('tickets', $ticket_id, 'ticket_prefix')); - $ticket_number = escapeSql(getFieldById('tickets', $ticket_id, 'ticket_number')); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "UPDATE tickets SET ticket_project_id = $project_id WHERE ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name set ticket $ticket_prefix$ticket_number project to $project_name", $client_id, $ticket_id); - - flashAlert("Project changed to $project_name for Ticket $ticket_prefix$ticket_number"); - - redirect(); - -} - -if (isset($_POST['add_ticket_watcher'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); - $watcher_emails = preg_split("/,| |;/", $_POST['watcher_email']); // Split on comma, semicolon or space, we sanitize later - $notify = intval($_POST['watcher_notify'] ?? 0); - - // Get contact/ticket details - $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_category, ticket_subject, ticket_details, ticket_priority, ticket_status_name, ticket_url_key, ticket_created_by, ticket_assigned_to, ticket_client_id FROM tickets - LEFT JOIN clients ON ticket_client_id = client_id - LEFT JOIN contacts ON ticket_contact_id = contact_id - LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id - WHERE ticket_id = $ticket_id - AND ticket_closed_at IS NULL"); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_category = escapeSql($row['ticket_category']); - $ticket_subject = escapeSql($row['ticket_subject']); - $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); - $ticket_priority = escapeSql($row['ticket_priority']); - $ticket_status = escapeSql($row['ticket_status_name']); - $url_key = escapeSql($row['ticket_url_key']); - $client_id = intval($row['ticket_client_id']); - $ticket_created_by = intval($row['ticket_created_by']); - $ticket_assigned_to = intval($row['ticket_assigned_to']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - // Get Company Phone Number - $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - // Process each watcher in list - foreach ($watcher_emails as $watcher_email) { - - if (filter_var($watcher_email, FILTER_VALIDATE_EMAIL)) { - - $watcher_email = escapeSql($watcher_email); - - mysqli_query($mysqli, "INSERT INTO ticket_watchers SET watcher_email = '$watcher_email', watcher_ticket_id = $ticket_id"); - - // Notify watcher - if ($notify && (!empty($config_smtp_provider))) { - - - - // Email content - $data = []; // Queue array - - $subject = "Ticket Notification - [$ticket_prefix$ticket_number] - $ticket_subject"; - $body = "##- Please type your reply above this line -##

Hello,

You have been added as a collaborator on this ticket regarding \"$ticket_subject\".

--------------------------------
$ticket_details--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status
Guest link: https://$config_base_url/guest/guest_view_ticket.php?ticket_id=$ticket_id&url_key=$url_key

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $watcher_email, - 'recipient_name' => $watcher_email, - 'subject' => $subject, - 'body' => $body - ]; - - addToMailQueue($data); - } - - logAudit("Ticket", "Edit", "$session_name added $watcher_email as a watcher for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); - } - - } - - flashAlert("Added watcher(s)"); - - redirect(); - -} - -if (isset($_GET['delete_ticket_watcher'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $watcher_id = intval($_GET['delete_ticket_watcher']); - - // Get ticket / watcher details for logging - $sql = mysqli_query($mysqli, "SELECT watcher_email, ticket_prefix, ticket_number, ticket_status_name, ticket_client_id, ticket_id FROM ticket_watchers - LEFT JOIN tickets ON watcher_ticket_id = ticket_id - LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id - WHERE watcher_id = $watcher_id" - ); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_status_name = escapeSql($row['ticket_status_name']); - $watcher_email = escapeSql($row['watcher_email']); - $client_id = intval($row['ticket_client_id']); - $ticket_id = intval($row['ticket_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "DELETE FROM ticket_watchers WHERE watcher_id = $watcher_id"); - - // History - mysqli_query($mysqli, "INSERT INTO ticket_history SET ticket_history_status = '$ticket_status_name', ticket_history_description = '$session_name removed ticket $watcher_email as a watcher', ticket_history_ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name removed $watcher_email as a watcher for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); - - flashAlert("Removed ticket watcher $watcher_email", 'error'); - - redirect(); - -} - -if (isset($_GET['delete_ticket_additional_asset'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $asset_id = intval($_GET['delete_ticket_additional_asset']); - $ticket_id = intval($_GET['ticket_id']); - - // Get ticket / asset details for logging - $sql = mysqli_query($mysqli, "SELECT asset_name, ticket_prefix, ticket_number, ticket_status_name, ticket_client_id FROM assets - JOIN tickets ON ticket_id = $ticket_id - JOIN ticket_statuses ON ticket_status = ticket_status_id - WHERE asset_id = $asset_id" - ); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_status_name = escapeSql($row['ticket_status_name']); - $asset_name = escapeSql($row['asset_name']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id AND asset_id = $asset_id"); - - // History - mysqli_query($mysqli, "INSERT INTO ticket_history SET ticket_history_status = '$ticket_status_name', ticket_history_description = '$session_name removed additional asset $asset_name', ticket_history_ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name removed asset $asset_name from ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); - - flashAlert("Removed asset $asset_name from ticket.", 'error'); - - redirect(); - -} - -if (isset($_POST['edit_ticket_asset'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); - $asset_id = intval($_POST['asset']); - - $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "UPDATE tickets SET ticket_asset_id = $asset_id WHERE ticket_id = $ticket_id"); - - // Add Additional Assets - if (isset($_POST['additional_assets'])) { - mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id"); - foreach ($_POST['additional_assets'] as $additional_asset) { - $additional_asset_id = intval($additional_asset); - mysqli_query($mysqli, "INSERT INTO ticket_assets SET ticket_id = $ticket_id, asset_id = $additional_asset_id"); - } - } else { - // If no additional assets are provided, delete them all - // This handles cases where the assets input might be cleared or not set at all. - mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id"); - } - - // Get ticket / asset details for logging - $sql = mysqli_query($mysqli, "SELECT asset_name, ticket_prefix, ticket_number, ticket_status_name, ticket_client_id FROM assets - LEFT JOIN tickets ON ticket_asset_id = asset_id - LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id - WHERE ticket_id = $ticket_id" - ); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_status_name = escapeSql($row['ticket_status_name']); - $asset_name = escapeSql($row['asset_name']); - $client_id = intval($row['ticket_client_id']); - - logAudit("Ticket", "Edit", "$session_name changed asset to $asset_name for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); - - flashAlert("Ticket $ticket_prefix$ticket_number asset updated to $asset_name"); - - redirect(); - -} - -if (isset($_POST['edit_ticket_vendor'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); - $vendor_id = intval($_POST['vendor']); - - $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "UPDATE tickets SET ticket_vendor_id = $vendor_id WHERE ticket_id = $ticket_id"); - - // Get ticket / vendor details for logging - $sql = mysqli_query($mysqli, "SELECT vendor_name, ticket_prefix, ticket_number, ticket_status_name, ticket_client_id FROM vendors - LEFT JOIN tickets ON ticket_vendor_id = $vendor_id - LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id - WHERE ticket_id = $ticket_id" - ); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_status_name = escapeSql($row['ticket_status_name']); - $vendor_name = escapeSql($row['vendor_name']); - $client_id = intval($row['ticket_client_id']); - - logAudit("Ticket", "Edit", "$session_name set vendor to $vendor_name for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); - - flashAlert("Set vendor to $vendor_name for ticket $ticket_prefix$ticket_number"); - - redirect(); - -} - -if (isset($_POST['assign_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - // POST variables - $ticket_id = intval($_POST['ticket_id']); - $assigned_to = intval($_POST['assigned_to']); - $ticket_status = intval($_POST['ticket_status']); - - // New > Open as assigned - if ($ticket_status == 1 && $assigned_to !== 0) { - $ticket_status = 2; - } - - // Allow for un-assigning tickets - if ($assigned_to == 0) { - $ticket_reply = "Ticket unassigned."; - $agent_name = "No One"; - } else { - // Get & verify assigned agent details - $agent_details_sql = mysqli_query($mysqli, "SELECT user_name, user_email FROM users WHERE users.user_id = $assigned_to"); - $agent_details = mysqli_fetch_assoc($agent_details_sql); - - $agent_name = escapeSql($agent_details['user_name']); - $agent_email = escapeSql($agent_details['user_email']); - $ticket_reply = "Ticket re-assigned to $agent_name."; - - if (!$agent_name) { - flashAlert("Invalid agent!", 'error'); - redirect(); - } - } - - // Get & verify ticket details - $ticket_details_sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, ticket_client_id, client_name FROM tickets LEFT JOIN clients ON ticket_client_id = client_id WHERE ticket_id = '$ticket_id' AND ticket_status != 5"); - $ticket_details = mysqli_fetch_assoc($ticket_details_sql); - - $ticket_prefix = escapeSql($ticket_details['ticket_prefix']); - $ticket_number = intval($ticket_details['ticket_number']); - $ticket_subject = escapeSql($ticket_details['ticket_subject']); - $client_id = intval($ticket_details['ticket_client_id']); - $client_name = escapeSql($ticket_details['client_name']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - if (!$ticket_subject) { - flashAlert("Invalid ticket!", 'error'); - redirect(); - } - - if ($client_id) { - $client_uri = "&client_id=$client_id"; - } else { - $client_uri = ''; - } - - // Update ticket & insert reply - mysqli_query($mysqli, "UPDATE tickets SET ticket_assigned_to = $assigned_to, ticket_status = '$ticket_status' WHERE ticket_id = $ticket_id"); - - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name reassigned $ticket_prefix$ticket_number to $agent_name", $client_id, $ticket_id); - - // Notification - if ($session_user_id != $assigned_to && $assigned_to != 0) { - - // App Notification - mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = 'Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject has been assigned to you by $session_name', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $assigned_to"); - - // Email Notification - if (!empty($config_smtp_provider)) { - - // Sanitize Config vars from get_settings.php - $config_ticket_from_name = escapeSql($config_ticket_from_name); - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $company_name = escapeSql($session_company_name); - - $subject = "$config_app_name - Ticket $ticket_prefix$ticket_number assigned to you - $ticket_subject"; - $body = "Hi $agent_name,

A ticket has been assigned to you!

Client: $client_name
Ticket Number: $ticket_prefix$ticket_number
Subject: $ticket_subject

https://$config_base_url/agent/ticket.php?ticket_id=$ticket_id$client_uri

Thanks,
$session_name
$company_name"; - - // Email Ticket Agent - // Queue Mail - $data = [ - [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $agent_email, - 'recipient_name' => $agent_name, - 'subject' => $subject, - 'body' => $body, - ] - ]; - addToMailQueue($data); - } - } - - triggerCustomAction('ticket_assign', $ticket_id); - - flashAlert("Ticket $ticket_prefix$ticket_number assigned to $agent_name"); - - redirect(); - -} - -if (isset($_GET['delete_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 3); - - $ticket_id = intval($_GET['delete_ticket']); - - // Get Ticket and Client ID for logging and alert message - $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_closed_at, ticket_client_id FROM tickets WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = escapeSql($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $ticket_status = escapeSql($row['ticket_status']); - $ticket_closed_at = escapeSql($row['ticket_closed_at']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - if (empty($ticket_closed_at)) { - mysqli_query($mysqli, "DELETE FROM tickets WHERE ticket_id = $ticket_id"); - - // Delete all ticket replies - mysqli_query($mysqli, "DELETE FROM ticket_replies WHERE ticket_reply_ticket_id = $ticket_id"); - - // Delete all ticket views - mysqli_query($mysqli, "DELETE FROM ticket_views WHERE view_ticket_id = $ticket_id"); - - // Delete ticket watchers - mysqli_query($mysqli, "DELETE FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); - - // Delete Ticket Attachements - mysqli_query($mysqli, "DELETE FROM ticket_attachments WHERE ticket_attachment_ticket_id = $ticket_id"); - removeDirectory("../uploads/tickets/$ticket_id"); - - // No Need to delete ticket assets as this is cascadely deleted via the database. - - logAudit("Ticket", "Delete", "$session_name deleted $ticket_prefix$ticket_number along with all replies", $client_id); - - flashAlert("Ticket $ticket_prefix$ticket_number along with all replies deleted", 'error'); - - triggerCustomAction('ticket_delete', $ticket_id); - - redirect("tickets.php"); - } - -} - -if (isset($_POST['bulk_delete_tickets'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 3); - - if (isset($_POST['ticket_ids'])) { - - $count = count($_POST['ticket_ids']); - - // Cycle through array and delete each recurring scheduled ticket - foreach ($_POST['ticket_ids'] as $ticket_id) { - - $ticket_id = intval($ticket_id); - - $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "DELETE FROM tickets WHERE ticket_id = $ticket_id"); - - // Delete all ticket replies - mysqli_query($mysqli, "DELETE FROM ticket_replies WHERE ticket_reply_ticket_id = $ticket_id"); - - // Delete all ticket views - mysqli_query($mysqli, "DELETE FROM ticket_views WHERE view_ticket_id = $ticket_id"); - - // Delete ticket watchers - mysqli_query($mysqli, "DELETE FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); - - // Delete Ticket Attachements - mysqli_query($mysqli, "DELETE FROM ticket_attachments WHERE ticket_attachment_ticket_id = $ticket_id"); - removeDirectory("../uploads/tickets/$ticket_id"); - - // No Need to delete ticket assets as this is cascadely deleted via the database. - - logAudit("Ticket", "Delete", "$session_name deleted ticket", 0, $ticket_id); - - } - - logAudit("Ticket", "Bulk Delete", "$session_name deleted $count ticket(s)"); - - flashAlert("Deleted $count ticket(s)", 'error'); - } - - redirect(); - -} - -if (isset($_POST['bulk_assign_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - // POST variables - $assign_to = intval($_POST['assign_to']); - - // Get a Ticket Count - $ticket_count = count($_POST['ticket_ids']); - - // Assign Tech to Selected Tickets - if (!empty($_POST['ticket_ids'])) { - foreach ($_POST['ticket_ids'] as $ticket_id) { - $ticket_id = intval($ticket_id); - - $sql = mysqli_query($mysqli, "SELECT * FROM tickets LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_status = intval($row['ticket_status']); - $ticket_name = escapeSql($row['ticket_name']); - $ticket_subject = escapeSql($row['ticket_subject']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - if ($ticket_status == 1 && $assigned_to !== 0) { - $ticket_status = 2; - } - - // Allow for un-assigning tickets - if ($assign_to == 0) { - $ticket_reply = "Ticket unassigned, pending re-assignment."; - $agent_name = "No One"; - } else { - // Get & verify assigned agent details - $agent_details_sql = mysqli_query($mysqli, "SELECT user_name, user_email FROM users LEFT JOIN user_settings ON users.user_id = user_settings.user_id WHERE users.user_id = $assign_to"); - $agent_details = mysqli_fetch_assoc($agent_details_sql); - - $agent_name = escapeSql($agent_details['user_name']); - $agent_email = escapeSql($agent_details['user_email']); - $ticket_reply = "Ticket re-assigned to $agent_name."; - - if (!$agent_name) { - flashAlert("Invalid agent!", 'error'); - redirect(); - } - } - - // Update ticket & insert reply - mysqli_query($mysqli, "UPDATE tickets SET ticket_assigned_to = $assign_to, ticket_status = $ticket_status WHERE ticket_id = $ticket_id"); - - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name reassigned ticket $ticket_prefix$ticket_number to $agent_name", $client_id, $ticket_id); - - triggerCustomAction('ticket_assign', $ticket_id); - - $tickets_assigned_body .= "$ticket_prefix$ticket_number - $ticket_subject
"; - } // End For Each Ticket ID Loop - - // Notification - if ($session_user_id != $assign_to && $assign_to != 0) { - - // App Notification - mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$ticket_count Tickets have been assigned to you by $session_name', notification_action = 'tickets.php?status=Open&assigned=$assign_to', notification_client_id = $client_id, notification_user_id = $assign_to"); - - // Agent Email Notification - if (!empty($config_smtp_provider)) { - - // Sanitize Config vars from get_settings.php - $config_ticket_from_name = escapeSql($config_ticket_from_name); - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $company_name = escapeSql($session_company_name); - - $subject = "$config_app_name - $ticket_count tickets have been assigned to you"; - $body = "Hi $agent_name,

$session_name assigned $ticket_count tickets to you!

$tickets_assigned_body
Thanks,
$session_name
$company_name"; - - // Email Ticket Agent - // Queue Mail - $data = [ - [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $agent_email, - 'recipient_name' => $agent_name, - 'subject' => $subject, - 'body' => $body, - ] - ]; - addToMailQueue($data); - } - } - } - - flashAlert("You assigned $ticket_count Tickets to $agent_name"); - - redirect(); - -} - -if (isset($_POST['bulk_edit_ticket_priority'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - // POST variables - $priority = escapeSql($_POST['bulk_priority']); - - // Assign Tech to Selected Tickets - if (isset($_POST['ticket_ids'])) { - - // Get a Ticket Count - $ticket_count = count($_POST['ticket_ids']); - - foreach ($_POST['ticket_ids'] as $ticket_id) { - $ticket_id = intval($ticket_id); - - $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $original_ticket_priority = escapeSql($row['ticket_priority']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - // Update ticket & insert reply - mysqli_query($mysqli, "UPDATE tickets SET ticket_priority = '$priority' WHERE ticket_id = $ticket_id"); - - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$session_name updated the priority from $current_ticket_priority to $priority', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name updated the priority on ticket $ticket_prefix$ticket_number - $ticket_subject from $original_ticket_priority to $priority", $client_id, $ticket_id); - - triggerCustomAction('ticket_update', $ticket_id); - } // End For Each Ticket ID Loop - - logAudit("Ticket", " Bulk Edit", "$session_name updated the priority on $ticket_count"); - - flashAlert("You updated the priority for $ticket_count Tickets to $priority"); - } - - redirect(); - -} - -if (isset($_POST['bulk_edit_ticket_category'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - // POST variables - $category_id = intval($_POST['bulk_category']); - - // Assign Tech to Selected Tickets - if (isset($_POST['ticket_ids'])) { - - // Get a Ticket Count - $ticket_count = count($_POST['ticket_ids']); - - foreach ($_POST['ticket_ids'] as $ticket_id) { - $ticket_id = intval($ticket_id); - - $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, category_name, ticket_client_id FROM tickets LEFT JOIN categories ON ticket_category = category_id WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $previous_ticket_category_name = escapeSql($row['category_name']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - // Get Category Name - $category_name = escapeSql(getFieldById('categories', $category_id, 'category_name')); - - // Update ticket - mysqli_query($mysqli, "UPDATE tickets SET ticket_category = '$category_id' WHERE ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name updated the category on ticket $ticket_prefix$ticket_number - $ticket_subject from $previous_category_name to $category_name", $client_id, $ticket_id); - - triggerCustomAction('ticket_update', $ticket_id); - } // End For Each Ticket ID Loop - - logAudit("Ticket", " Bulk Edit", "$session_name updated the category to $category_name on $ticket_count"); - - flashAlert("Category set to $category_name for $ticket_count Tickets"); - } - - redirect(); - -} - -if (isset($_POST['bulk_merge_tickets'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $merge_into_ticket_id = intval($_POST['merge_into_ticket_id']); // Parent ticket id - $merge_comment = escapeSql($_POST['merge_comment']); // Merge comment - $ticket_reply_type = 'Internal'; // Default all replies to internal - - // NEW PARENT ticket details - // Get merge into ticket id (as it may differ from the number) - $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_number FROM tickets WHERE ticket_id = $merge_into_ticket_id"); - if (mysqli_num_rows($sql) == 0) { - flashAlert("Cannot merge into that ticket.", 'error'); - redirect(); - } - $merge_row = mysqli_fetch_assoc($sql); - $merge_into_ticket_number = intval($merge_row['ticket_number']); // Parent ticket Number - - // Update & Close the selected tickets - if (isset($_POST['ticket_ids'])) { - - $ticket_count = count($_POST['ticket_ids']); // Get a ticket count - - foreach ($_POST['ticket_ids'] as $ticket_id) { - $ticket_id = intval($ticket_id); - - if ($ticket_id !== $merge_into_ticket_id) { - - $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); - $current_ticket_priority = escapeSql($row['ticket_priority']); - $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - // Update current ticket - if (empty($ticket_first_response_at)) { - mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); - } - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket $ticket_prefix$ticket_number bulk merged into $ticket_prefix$merge_into_ticket_number. Comment: $merge_comment', ticket_reply_time_worked = '00:01:00', ticket_reply_type = '$ticket_reply_type', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - mysqli_query($mysqli, "UPDATE tickets SET ticket_status = '5', ticket_resolved_at = NOW(), ticket_closed_at = NOW(), ticket_closed_by = $session_user_id WHERE ticket_id = $ticket_id") or die(mysqli_error($mysqli)); - - // Update new parent ticket - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket $ticket_prefix$ticket_number was bulk merged into this ticket with comment: $merge_comment.

$ticket_subject
$ticket_details', ticket_reply_time_worked = '00:01:00', ticket_reply_type = 'Internal', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $merge_into_ticket_id"); - - logAudit("Ticket", "Merged", "$session_name Merged ticket $ticket_prefix$ticket_number into $ticket_prefix$merge_into_ticket_number", $client_id, $ticket_id); - - // Custom action/notif handler - triggerCustomAction('ticket_merge', $ticket_id); - - } - } // End For Each Ticket ID Loop - - mysqli_query($mysqli, "UPDATE tickets SET ticket_updated_at = NOW() WHERE ticket_id = $merge_into_ticket_id"); - - flashAlert("$ticket_count tickets merged into $ticket_prefix$merge_into_ticket_number"); - - } - - redirect(); - -} - -if (isset($_POST['bulk_resolve_tickets'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - // POST variables - $details = mysqli_escape_string($mysqli, $_POST['bulk_details']); - $ticket_reply_time_worked = escapeSql($_POST['time']); - $private_note = intval($_POST['bulk_private_note']); - if ($private_note == 1) { - $ticket_reply_type = 'Internal'; - } else { - $ticket_reply_type = 'Public'; - } - - // Resolve Selected Tickets - if (isset($_POST['ticket_ids'])) { - - // Intitialze the counts before the loop - $ticket_count = 0; - $skipped_count = 0; - - foreach ($_POST['ticket_ids'] as $ticket_id) { - $ticket_id = intval($ticket_id); - - // Check to make sure Tasks are complete before resolving - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('task_id') AS num FROM tasks WHERE task_completed_at IS NULL AND task_ticket_id = $ticket_id")); - $num_of_open_tasks = $row['num']; - - if ($num_of_open_tasks == 0) { - // Count the Ticket Loop - $ticket_count++; - - $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $current_ticket_priority = escapeSql($row['ticket_priority']); - $url_key = escapeSql($row['ticket_url_key']); - $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - // Mark FR time if required - if (empty($ticket_first_response_at)) { - mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); - } - - // Update ticket & insert reply - mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 4, ticket_resolved_at = NOW() WHERE ticket_id = $ticket_id"); - - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$details', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '$ticket_reply_time_worked', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - logAudit("Ticket", "Resolve", "$session_name resolved $ticket_prefix$ticket_number - $ticket_subject", $client_id, $ticket_id); - - triggerCustomAction('ticket_resolve', $ticket_id); - - // Client notification email - if ((!empty($config_smtp_provider)) && $config_ticket_client_general_notifications == 1 && $private_note == 0) { - - // Get Contact details - $ticket_sql = mysqli_query($mysqli, "SELECT contact_name, contact_email FROM tickets - LEFT JOIN contacts ON ticket_contact_id = contact_id - WHERE ticket_id = $ticket_id - "); - $row = mysqli_fetch_assoc($ticket_sql); - - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - - // Sanitize Config vars from get_settings.php - $from_name = escapeSql($config_ticket_from_name); - $from_email = escapeSql($config_ticket_from_email); - $base_url = escapeSql($config_base_url); - - // Get Company Info - $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - // EMAIL - $subject = "Ticket resolved - [$ticket_prefix$ticket_number] - $ticket_subject | (pending closure)"; - $body = "##- Please type your reply above this line -##

Hello $contact_name,

Your ticket regarding \"$ticket_subject\" has been marked as solved and is pending closure.

$details

If your request/issue is resolved, you can simply ignore this email. If you need further assistance, please reply or re-open to let us know!

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Portal: https://$base_url/client/ticket.php?id=$ticket_id

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - - // Check email valid - if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { - - $data = []; - - // Email Ticket Contact - // Queue Mail - - $data[] = [ - 'from' => $from_email, - 'from_name' => $from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - } - - // Also Email all the watchers - $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); - $body .= "

----------------------------------------
YOU ARE A COLLABORATOR ON THIS TICKET"; - while ($row = mysqli_fetch_assoc($sql_watchers)) { - $watcher_email = escapeSql($row['watcher_email']); - - // Queue Mail - $data[] = [ - 'from' => $from_email, - 'from_name' => $from_name, - 'recipient' => $watcher_email, - 'recipient_name' => $watcher_email, - 'subject' => $subject, - 'body' => $body - ]; - } - addToMailQueue($data); - } // End Mail IF - } else { - $skipped_count++; - } // End Task Check - } // End Loop - } // End Array Empty Check - - flashAlert("Resolved $ticket_count Tickets"); - - if ($skipped_count > 0) { - flashAlert("Resolved $ticket_count Tickets $skipped_count ticket(s) could not be resolved because they have open tasks.", 'info'); - } - - redirect(); - -} - -if (isset($_POST['bulk_ticket_reply'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - // POST variables - $ticket_reply = mysqli_escape_string($mysqli, $_POST['bulk_reply_details']); - $ticket_status = intval($_POST['bulk_status']); - $ticket_reply_time_worked = escapeSql($_POST['time']); - $private_note = intval($_POST['bulk_private_reply']); - if ($private_note == 1) { - $ticket_reply_type = 'Internal'; - } else { - $ticket_reply_type = 'Public'; - } - - // Loop Through Tickets and Add Reply along with Email notifications - if (isset($_POST['ticket_ids'])) { - - // Get a Ticket Count - $ticket_count = count($_POST['ticket_ids']); - - foreach ($_POST['ticket_ids'] as $ticket_id) { - $ticket_id = intval($ticket_id); - - $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $current_ticket_priority = escapeSql($row['ticket_priority']); - $url_key = escapeSql($row['ticket_url_key']); - $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - if ($client_id) { - $client_uri = "&client_id=$client_id"; - } else { - $client_uri = ''; - } - - // Mark FR time if required - if (empty($ticket_first_response_at)) { - mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); - } - - // Add reply - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_time_worked = '$ticket_reply_time_worked', ticket_reply_type = '$ticket_reply_type', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - $ticket_reply_id = mysqli_insert_id($mysqli); - - // Update Ticket Status - mysqli_query($mysqli, "UPDATE tickets SET ticket_status = '$ticket_status' WHERE ticket_id = $ticket_id"); - - logAudit("Ticket", "Reply", "$session_name replied to ticket $ticket_prefix$ticket_number - $ticket_subject and was a $ticket_reply_type reply", $client_id, $ticket_id); - - // Custom action/notif handler - if ($ticket_reply_type == 'Internal') { - triggerCustomAction('ticket_reply_agent_internal', $ticket_id); - } else { - triggerCustomAction('reply_reply_agent_public', $ticket_id); - } - - // Resolve the ticket, if set - if ($ticket_status == 4) { - mysqli_query($mysqli, "UPDATE tickets SET ticket_resolved_at = NOW() WHERE ticket_id = $ticket_id"); - - // Logging - logAudit("Ticket", "Resolved", "$session_name resolved Ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); - - triggerCustomAction('ticket_resolve', $ticket_id); - } - - // Get Contact Details - $sql = mysqli_query( - $mysqli, - "SELECT contact_name, contact_email, ticket_created_by, ticket_assigned_to - FROM tickets - LEFT JOIN contacts ON ticket_contact_id = contact_id - WHERE ticket_id = $ticket_id" - ); - - $row = mysqli_fetch_assoc($sql); - - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - $ticket_created_by = intval($row['ticket_created_by']); - $ticket_assigned_to = intval($row['ticket_assigned_to']); - - // Sanitize Config vars from get_settings.php - $from_name = escapeSql($config_ticket_from_name); - $from_email = escapeSql($config_ticket_from_email); - $base_url = escapeSql($config_base_url); - - $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - // Send e-mail to client if public update & email is set up - if ($private_note == 0 && (!empty($config_smtp_provider))) { - - $subject = "Ticket update - [$ticket_prefix$ticket_number] - $ticket_subject"; - $body = "##- Please type your reply above this line -##

Hello $contact_name,

Your ticket regarding $ticket_subject has been updated.

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

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status_name
Portal: View ticket

--
$company_name - Support
$from_email
$company_phone"; - - if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { - - $data = []; - - // Email Ticket Contact - // Queue Mail - $data[] = [ - 'from' => $from_email, - 'from_name' => $from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - - } - - // Also Email all the watchers - $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); - $body .= "

----------------------------------------
YOU ARE A COLLABORATOR ON THIS TICKET"; - while ($row = mysqli_fetch_assoc($sql_watchers)) { - $watcher_email = escapeSql($row['watcher_email']); - - // Queue Mail - $data[] = [ - 'from' => $from_email, - 'from_name' => $from_name, - 'recipient' => $watcher_email, - 'recipient_name' => $watcher_email, - 'subject' => $subject, - 'body' => $body - ]; - } - addToMailQueue($data); - } //End Mail IF - - // Notification for assigned ticket user - if ($session_user_id != $ticket_assigned_to && $ticket_assigned_to != 0) { - - mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$session_name updated Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject that is assigned to you', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $ticket_assigned_to"); - } - - // Notification for user that opened the ticket - if ($session_user_id != $ticket_created_by && $ticket_created_by != 0) { - - mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$session_name updated Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject that you opened', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $ticket_created_by"); - } - } // End Ticket Lopp - - } - - flashAlert("Updated $ticket_count tickets"); - - redirect(); - -} - - -// Currently not UI Frontend for this -if (isset($_POST['bulk_add_ticket_project'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - // POST variables - $project_id = intval($_POST['project_id']); - - // Get Project Name - $sql = mysqli_query($mysqli, "SELECT project_name FROM projects WHERE project_id = $project_id"); - $row = mysqli_fetch_assoc($sql); - $project_name = escapeSql($row['project_name']); - - // Assign Project to Selected Tickets - if (isset($_POST['ticket_ids'])) { - - // Get a Ticket Count - $ticket_count = count($_POST['ticket_ids']); - - foreach ($_POST['ticket_ids'] as $ticket_id) { - $ticket_id = intval($ticket_id); - - $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $current_ticket_priority = escapeSql($row['ticket_priority']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - // Update ticket & insert reply - mysqli_query($mysqli, "UPDATE tickets SET ticket_project_id = $project_id WHERE ticket_id = $ticket_id"); - - logAudit("Ticket", "Reply", "$session_name added ticket $ticket_prefix$ticket_number - $ticket_subject to project $project_name", $client_id, $ticket_id); - - - } // End For Each Ticket ID Loop - - flashAlert("$ticket_count Tickets added to Project $project_name"); - - } - - redirect(); - -} - -if (isset($_POST['bulk_add_asset_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $assigned_to = intval($_POST['bulk_assigned_to']); - if ($assigned_to == 0) { - $ticket_status = 1; - } else { - $ticket_status = 2; - } - $subject = escapeSql($_POST['bulk_subject']); - $priority = escapeSql($_POST['bulk_priority']); - $category_id = intval($_POST['bulk_category']); - $details = mysqli_real_escape_string($mysqli, $_POST['bulk_details']); - $project_id = intval($_POST['bulk_project']); - $use_primary_contact = intval($_POST['use_primary_contact']); - $ticket_template_id = intval($_POST['bulk_ticket_template_id']); - $billable = intval($_POST['bulk_billable'] ?? 0); - - // 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_assoc($sql); - - // Override Template Subject - if(empty($subject)) { - $subject = escapeSql($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"); - - } - - // Create ticket for each selected asset - if (isset($_POST['asset_ids'])) { - - // Get a Asset Count - $asset_count = count($_POST['asset_ids']); - - foreach ($_POST['asset_ids'] as $asset_id) { - $asset_id = intval($asset_id); - - $sql = mysqli_query($mysqli, "SELECT * FROM assets WHERE asset_id = $asset_id"); - $row = mysqli_fetch_assoc($sql); - - $asset_name = escapeSql($row['asset_name']); - $client_id = intval($row['asset_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - $subject_asset_prepended = "$asset_name - $subject"; - - // Atomically increment and get the new ticket number - mysqli_query($mysqli, " - UPDATE settings - SET - config_ticket_next_number = LAST_INSERT_ID(config_ticket_next_number), - config_ticket_next_number = config_ticket_next_number + 1 - WHERE company_id = 1 - "); - - $ticket_number = mysqli_insert_id($mysqli); - - // Sanitize Config Vars from get_settings.php and Session Vars from check_login.php - $config_ticket_prefix = escapeSql($config_ticket_prefix); - $config_ticket_from_name = escapeSql($config_ticket_from_name); - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $config_base_url = escapeSql($config_base_url); - - //Generate a unique URL key for clients to access - $url_key = randomString(32); - - mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$config_ticket_prefix', ticket_number = $ticket_number, ticket_category = $category_id, ticket_subject = '$subject_asset_prepended', ticket_details = '$details', ticket_priority = '$priority', ticket_billable = $billable, ticket_status = $ticket_status, ticket_asset_id = $asset_id, ticket_created_by = $session_user_id, ticket_assigned_to = $assigned_to, ticket_url_key = '$url_key', ticket_client_id = $client_id, ticket_project_id = $project_id"); - - $ticket_id = mysqli_insert_id($mysqli); - - // Add Tasks - if (!empty($_POST['tasks'])) { - foreach ($_POST['tasks'] as $task) { - $task_name = escapeSql($task); - // Check that task_name is not-empty (For some reason the !empty on the array doesnt work here like in watchers) - if (!empty($task_name)) { - mysqli_query($mysqli,"INSERT INTO tasks SET task_name = '$task_name', task_ticket_id = $ticket_id"); - } - } - } - - // Add Tasks from Template if Template was selected - if($ticket_template_id) { - if (mysqli_num_rows($sql_task_templates) > 0) { - while ($row = mysqli_fetch_assoc($sql_task_templates)) { - $task_order = intval($row['task_template_order']); - $task_name = escapeSql($row['task_template_name']); - - mysqli_query($mysqli,"INSERT INTO tasks SET task_name = '$task_name', task_order = $task_order, task_ticket_id = $ticket_id"); - } - } - } - - // Custom action/notif handler - triggerCustomAction('ticket_create', $ticket_id); - } - - logAudit("Ticket", "Bulk Create", "$session_name created $asset_count tickets for $asset_count"); - - flashAlert("You created $asset_count tickets for the selected assets"); - - } - - redirect(); - -} - -if (isset($_POST['add_ticket_reply'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); - $ticket_reply = $_POST['ticket_reply']; // Reply is SQL escaped below - $ticket_status = intval($_POST['status']); - - $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - // Time tracking, inputs & combine into string - $hours = intval($_POST['hours']); - $minutes = intval($_POST['minutes']); - $seconds = intval($_POST['seconds']); - $ticket_reply_time_worked = escapeSql(sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds)); - - // Defaults - $send_email = 0; - $ticket_reply_id = 0; - if ($_POST['public_reply_type'] == 1 ){ - $ticket_reply_type = 'Public'; - } elseif ($_POST['public_reply_type'] == 2 ) { - $ticket_reply_type = 'Public'; - $send_email = 1; - } else { - $ticket_reply_type = 'Internal'; - } - // Add Signature to the end of the ticket reply if not Internal and if there is reply - if ($ticket_reply !== '' && $ticket_reply_type !== 'Internal' && $send_email == 1) { - $ticket_reply .= getFieldById('user_settings',$session_user_id,'user_config_signature', 'raw'); - } - - $ticket_reply = mysqli_escape_string($mysqli, $ticket_reply); // SQL Escape Ticket Reply - - // Update Ticket Status & updated at (in case status didn't change) - mysqli_query($mysqli, "UPDATE tickets SET ticket_status = $ticket_status, ticket_updated_at = NOW() WHERE ticket_id = $ticket_id"); - - // Resolve the ticket, if set - if ($ticket_status == 4) { - mysqli_query($mysqli, "UPDATE tickets SET ticket_resolved_at = NOW() WHERE ticket_id = $ticket_id"); - - logAudit("Ticket", "Resolved", "$session_name resolved Ticket ticket ID $ticket_id", $client_id, $ticket_id); - } - - // Process reply actions, if we have a reply to work with (e.g. we're not just editing the status) - if (!empty($ticket_reply)) { - - // Add reply - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_time_worked = '$ticket_reply_time_worked', ticket_reply_type = '$ticket_reply_type', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - $ticket_reply_id = mysqli_insert_id($mysqli); - - // Get Ticket Details - $ticket_sql = mysqli_query($mysqli, "SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_status_name, ticket_url_key, ticket_first_response_at, ticket_created_by, ticket_assigned_to, ticket_client_id - FROM tickets - LEFT JOIN clients ON ticket_client_id = client_id - LEFT JOIN contacts ON ticket_contact_id = contact_id - LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id - WHERE ticket_id = $ticket_id - "); - - $row = mysqli_fetch_assoc($ticket_sql); - - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $ticket_status = intval($row['ticket_status']); - $ticket_status_name = escapeSql($row['ticket_status_name']); - $url_key = escapeSql($row['ticket_url_key']); - $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); - $ticket_created_by = intval($row['ticket_created_by']); - $ticket_assigned_to = intval($row['ticket_assigned_to']); - $client_id = intval($row['ticket_client_id']); - - if ($client_id) { - $client_uri = "&client_id=$client_id"; - } else { - $client_uri = ''; - } - - // Sanitize Config vars from get_settings.php - $config_ticket_from_name = escapeSql($config_ticket_from_name); - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $config_base_url = escapeSql($config_base_url); - - $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - // Send e-mail to client if public update & email is set up - if ($ticket_reply_type == 'Public' && $send_email == 1 && (!empty($config_smtp_provider))) { - - // Slightly different email subject/text depending on if this update set auto-close - - if ($ticket_status == 4) { - // Resolved - $subject = "Ticket resolved - [$ticket_prefix$ticket_number] - $ticket_subject | (pending closure)"; - $body = "##- Please type your reply above this line -##

Hello $contact_name,

Your ticket regarding $ticket_subject has been marked as solved and is pending closure.

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

If your request/issue is resolved, you can simply ignore this email. If you need further assistance, please reply or re-open to let us know!

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status_name
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - } else { - // Anything else - $subject = "Ticket update - [$ticket_prefix$ticket_number] - $ticket_subject"; - $body = "##- Please type your reply above this line -##

Hello $contact_name,

Your ticket regarding $ticket_subject has been updated.

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

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status_name
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - } - - if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { - - $data = []; - - // Email Ticket Contact - // Queue Mail - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - } - - // Also Email all the watchers - $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); - $body .= "

----------------------------------------
YOU ARE A COLLABORATOR ON THIS TICKET"; - while ($row = mysqli_fetch_assoc($sql_watchers)) { - $watcher_email = escapeSql($row['watcher_email']); - - // Queue Mail - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $watcher_email, - 'recipient_name' => $watcher_email, - 'subject' => $subject, - 'body' => $body - ]; - } - addToMailQueue($data); - - } - //End Mail IF - - // Notification for assigned ticket user - if ($session_user_id != $ticket_assigned_to && $ticket_assigned_to != 0) { - mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$session_name updated Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject that is assigned to you', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $ticket_assigned_to"); - } - - // Notification for user that opened the ticket - if ($session_user_id != $ticket_created_by && $ticket_created_by != 0) { - mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$session_name updated Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject that you opened', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $ticket_created_by"); - } - - // Handle first response - if (empty($ticket_first_response_at) && $ticket_reply_type == 'Public') { - mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); - } - - // Custom action/notif handler - if ($ticket_reply_type == 'Internal') { - triggerCustomAction('ticket_reply_agent_internal', $ticket_id); - } else { - triggerCustomAction('reply_reply_agent_public', $ticket_id); - } - - flashAlert("Ticket $ticket_prefix$ticket_number has been updated with your reply and was $ticket_reply_type"); - - } else { - flashAlert("Ticket updated"); - } - - logAudit("Ticket", "Reply", "$session_name replied to ticket $ticket_prefix$ticket_number - $ticket_subject and was a $ticket_reply_type reply", $client_id, $ticket_id); - - redirect(); - -} - -if (isset($_POST['edit_ticket_reply'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_reply_id = intval($_POST['ticket_reply_id']); - $ticket_reply = mysqli_real_escape_string($mysqli, $_POST['ticket_reply']); - $ticket_reply_type = escapeSql($_POST['ticket_reply_type']); - $ticket_reply_time_worked = escapeSql($_POST['time']); - - $sql = mysqli_query($mysqli, "SELECT ticket_client_id FROM ticket_replies - LEFT JOIN tickets ON ticket_id = ticket_reply_ticket_id - WHERE ticket_reply_id = $ticket_reply_id - LIMIT 1" - ); - - $row = mysqli_fetch_assoc($sql); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '$ticket_reply_time_worked' WHERE ticket_reply_id = $ticket_reply_id AND ticket_reply_type != 'Client'") or die(mysqli_error($mysqli)); - - logAudit("Ticket", "Reply", "$session_name edited ticket_reply", $client_id, $ticket_reply_id); - - flashAlert("Ticket reply updated"); - - redirect(); - -} - -if (isset($_POST['redact_ticket_reply'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_reply_id = intval($_POST['ticket_reply_id']); - $ticket_reply = mysqli_real_escape_string($mysqli, $_POST['ticket_reply']); - - $sql = mysqli_query($mysqli, "SELECT ticket_client_id FROM ticket_replies - LEFT JOIN tickets ON ticket_id = ticket_reply_ticket_id - WHERE ticket_reply_id = $ticket_reply_id - LIMIT 1" - ); - - $row = mysqli_fetch_assoc($sql); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply = '$ticket_reply' WHERE ticket_reply_id = $ticket_reply_id"); - - logAudit("Ticket", "Reply", "$session_name redacted ticket_reply", $client_id, $ticket_reply_id); - - flashAlert("Ticket reply redacted"); - - redirect(); - -} - -if (isset($_GET['archive_ticket_reply'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_reply_id = intval($_GET['archive_ticket_reply']); - - $ticket_id = intval(getFieldById('ticket_replies', $ticket_reply_id, 'ticket_reply_ticket_id')); - $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply_archived_at = NOW() WHERE ticket_reply_id = $ticket_reply_id"); - - logAudit("Ticket Reply", "Archive", "$session_name archived ticket_reply", $client_id, $ticket_reply_id); - - flashAlert("Ticket reply archived", 'error'); - - redirect(); - -} - -if (isset($_POST['merge_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); // Child ticket ID to be closed - $merge_into_ticket_id = intval($_POST['merge_into_ticket_id']); // Parent ticket id - $merge_comment = escapeSql($_POST['merge_comment']); // Merge comment - $move_replies = intval($_POST['merge_move_replies']); // Whether to move replies to the new parent ticket - $ticket_reply_type = 'Internal'; // Default all replies to internal - - // Get current ticket details - $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, ticket_details FROM tickets WHERE ticket_id = $ticket_id"); - if (mysqli_num_rows($sql) == 0) { - flashAlert("No ticket with that ID found.", 'error'); - redirect(); - } - // CURRENT ticket details - $row = mysqli_fetch_assoc($sql); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); - $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); - - // NEW PARENT ticket details - // Get merge into ticket id (as it may differ from the number) - $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_number, ticket_client_id FROM tickets WHERE ticket_id = $merge_into_ticket_id"); - if (mysqli_num_rows($sql) == 0) { - flashAlert("Cannot merge into that ticket.", 'error'); - redirect(); - } - $merge_row = mysqli_fetch_assoc($sql); - $client_id = intval($merge_row['ticket_client_id']); - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - $merge_into_ticket_number = intval($merge_row['ticket_number']); - if ($client_id) { - $has_client = "&client_id=$client_id"; - } else { - $has_client = ""; - } - // Sanity check - if ($ticket_id == $merge_into_ticket_id) { - flashAlert("Cannot merge into the same ticket.", 'error'); - redirect(); - } - - // Move ticket replies from child > parent - if ($move_replies) { - mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply_ticket_id = $merge_into_ticket_id WHERE ticket_reply_ticket_id = $ticket_id"); - } - - // Update current ticket - if (empty($ticket_first_response_at)) { - mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); - } - - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket $ticket_prefix$ticket_number merged into $ticket_prefix$merge_into_ticket_number. Comment: $merge_comment', ticket_reply_time_worked = '00:01:00', ticket_reply_type = '$ticket_reply_type', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - mysqli_query($mysqli, "UPDATE tickets SET ticket_status = '5', ticket_resolved_at = NOW(), ticket_closed_at = NOW(), ticket_closed_by = $session_user_id WHERE ticket_id = $ticket_id") or die(mysqli_error($mysqli)); - - //Update new parent ticket - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket $ticket_prefix$ticket_number was merged into this ticket with comment: $merge_comment.

$ticket_subject
$ticket_details', ticket_reply_time_worked = '00:01:00', ticket_reply_type = '$ticket_reply_type', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $merge_into_ticket_id"); - - mysqli_query($mysqli, "UPDATE tickets SET ticket_updated_at = NOW() WHERE ticket_id = $merge_into_ticket_id"); - - logAudit("Ticket", "Merged", "$session_name Merged ticket $ticket_prefix$ticket_number into $ticket_prefix$merge_into_ticket_number"); - - triggerCustomAction('ticket_merge', $ticket_id); - - flashAlert("Ticket merged into $ticket_prefix$merge_into_ticket_number"); - - redirect("ticket.php?ticket_id=$merge_into_ticket_id$has_client"); - -} - -if (isset($_POST['change_client_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); - $client_id = intval($_POST['new_client_id']); - $contact_id = intval($_POST['new_contact_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - // Set any/all existing replies to internal - mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply_type = 'Internal' WHERE ticket_reply_ticket_id = $ticket_id"); - - // Update ticket client & contact - mysqli_query($mysqli, "UPDATE tickets SET ticket_client_id = $client_id, ticket_contact_id = $contact_id WHERE ticket_id = $ticket_id LIMIT 1"); - - logAudit("Ticket", "Change", "$session_name changed ticket client", $client_id, $ticket_id); - - triggerCustomAction('ticket_update', $ticket_id); - - flashAlert("Ticket client updated"); - - redirect(); - -} - -if (isset($_GET['resolve_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_GET['resolve_ticket']); - - $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - // Mark FR - if (empty($ticket_first_response_at)) { - mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); - } - - // Resolve - mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 4, ticket_resolved_at = NOW() WHERE ticket_id = $ticket_id"); - - logAudit("Ticket", "Resolved", "$session_name resolved ticket $ticket_prefix$ticket_number (ID: $ticket_id)", $client_id, $ticket_id); - - triggerCustomAction('ticket_resolve', $ticket_id); - - // Client notification email - if ((!empty($config_smtp_provider)) && $config_ticket_client_general_notifications == 1) { - - // Get details - $ticket_sql = mysqli_query($mysqli, "SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_subject, ticket_status_name, ticket_assigned_to, ticket_url_key FROM tickets - LEFT JOIN clients ON ticket_client_id = client_id - LEFT JOIN contacts ON ticket_contact_id = contact_id - LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id - WHERE ticket_id = $ticket_id - "); - $row = mysqli_fetch_assoc($ticket_sql); - - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $ticket_assigned_to = intval($row['ticket_assigned_to']); - $ticket_status = escapeSql($row['ticket_status_name']); - $url_key = escapeSql($row['ticket_url_key']); - - // Sanitize Config vars from get_settings.php - $config_ticket_from_name = escapeSql($config_ticket_from_name); - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $config_base_url = escapeSql($config_base_url); - - // Get Company Info - $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - // EMAIL - $subject = "Ticket resolved - [$ticket_prefix$ticket_number] - $ticket_subject | (pending closure)"; - $body = "##- Please type your reply above this line -##

Hello $contact_name,

Your ticket regarding $ticket_subject has been marked as solved and is pending closure.

If your request/issue is resolved, you can simply ignore this email. If you need further assistance, please reply or re-open to let us know!

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - - // Check email valid - if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { - - $data = []; - - // Email Ticket Contact - // Queue Mail - - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - } - - // Also Email all the watchers - $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); - $body .= "

----------------------------------------
YOU ARE A COLLABORATOR ON THIS TICKET"; - while ($row = mysqli_fetch_assoc($sql_watchers)) { - $watcher_email = escapeSql($row['watcher_email']); - - // Queue Mail - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $watcher_email, - 'recipient_name' => $watcher_email, - 'subject' => $subject, - 'body' => $body - ]; - } - addToMailQueue($data); - } - //End Mail IF - - flashAlert("Ticket resolved"); - - redirect(); - -} - -if (isset($_GET['close_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_GET['close_ticket']); - $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 5, ticket_closed_at = NOW(), ticket_closed_by = $session_user_id WHERE ticket_id = $ticket_id") or die(mysqli_error($mysqli)); - - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket closed.', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - logAudit("Ticket", "Closed", "$session_name closed ticket ID $ticket_id", $client_id, $ticket_id); - - triggerCustomAction('ticket_close', $ticket_id); - - // Client notification email - if ((!empty($config_smtp_provider)) && $config_ticket_client_general_notifications == 1) { - - // Get details - $ticket_sql = mysqli_query($mysqli, "SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_subject, ticket_url_key FROM tickets - LEFT JOIN clients ON ticket_client_id = client_id - LEFT JOIN contacts ON ticket_contact_id = contact_id - WHERE ticket_id = $ticket_id - "); - $row = mysqli_fetch_assoc($ticket_sql); - - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $url_key = escapeSql($row['ticket_url_key']); - - // Sanitize Config vars from get_settings.php - $config_ticket_from_name = escapeSql($config_ticket_from_name); - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $config_base_url = escapeSql($config_base_url); - - // Get Company Info - $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); - $row = mysqli_fetch_assoc($sql); - $company_name = escapeSql($row['company_name']); - $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); - - // EMAIL - $subject = "Ticket closed - [$ticket_prefix$ticket_number] - $ticket_subject | (do not reply)"; - $body = "Hello $contact_name,

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

We hope the request/issue was resolved to your satisfaction, please provide your feedback here.
If you need further assistance, please raise a new ticket using the below details. Please do not reply to this email.

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Portal: https://$config_base_url/client/ticket.php?id=$ticket_id

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - - // Check email valid - if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { - - $data = []; - - // Email Ticket Contact - // Queue Mail - - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ]; - } - - // Also Email all the watchers - $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); - $body .= "

----------------------------------------
YOU ARE A COLLABORATOR ON THIS TICKET"; - while ($row = mysqli_fetch_assoc($sql_watchers)) { - $watcher_email = escapeSql($row['watcher_email']); - - // Queue Mail - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $watcher_email, - 'recipient_name' => $watcher_email, - 'subject' => $subject, - 'body' => $body - ]; - } - addToMailQueue($data); - } - //End Mail IF - - flashAlert("Ticket Closed, this cannot not be reopened but you may start another one"); - - redirect(); - -} - -if (isset($_GET['reopen_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_GET['reopen_ticket']); - - $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 2, ticket_resolved_at = NULL WHERE ticket_id = $ticket_id"); - - logAudit("Ticket", "Reopened", "$session_name reopened ticket ID $ticket_id", $client_id, $ticket_id); - - triggerCustomAction('ticket_update', $ticket_id); - - flashAlert("Ticket re-opened"); - - redirect(); - -} - -if (isset($_POST['add_invoice_from_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - enforceUserPermission('module_sales', 2); - - $invoice_id = intval($_POST['invoice_id']); - $ticket_id = intval($_POST['ticket_id']); - $date = escapeSql($_POST['date']); - $category = intval($_POST['category']); - $scope = escapeSql($_POST['scope']); - - $sql = mysqli_query( - $mysqli, - "SELECT * FROM tickets - LEFT JOIN clients ON ticket_client_id = client_id - LEFT JOIN contacts ON ticket_contact_id = contact_id - LEFT JOIN assets ON ticket_asset_id = asset_id - LEFT JOIN locations ON ticket_location_id = location_id - WHERE ticket_id = $ticket_id" - ); - - $row = mysqli_fetch_assoc($sql); - $client_id = intval($row['client_id']); - $client_net_terms = intval($row['client_net_terms']); - if ($client_net_terms == 0) { - $client_net_terms = $config_default_net_terms; - } - - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_category = escapeSql($row['ticket_category']); - $ticket_subject = escapeSql($row['ticket_subject']); - $ticket_created_at = escapeSql($row['ticket_created_at']); - $ticket_updated_at = escapeSql($row['ticket_updated_at']); - $ticket_closed_at = escapeSql($row['ticket_closed_at']); - - $contact_id = intval($row['contact_id']); - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - - $asset_id = intval($row['asset_id']); - - $location_name = escapeSql($row['location_name']); - - enforceClientAccess(); - - if ($invoice_id == 0) { - - $invoice_prefix = escapeSql($config_invoice_prefix); - - // Atomically increment and get the new invoice number - mysqli_query($mysqli, " - UPDATE settings - SET - config_invoice_next_number = LAST_INSERT_ID(config_invoice_next_number), - config_invoice_next_number = config_invoice_next_number + 1 - WHERE company_id = 1 - "); - - $invoice_number = mysqli_insert_id($mysqli); - - //Generate a unique URL key for clients to access - $url_key = randomString(32); - - mysqli_query($mysqli, "INSERT INTO invoices SET invoice_prefix = '$config_invoice_prefix', invoice_number = $invoice_number, invoice_scope = '$scope', invoice_date = '$date', invoice_due = DATE_ADD('$date', INTERVAL $client_net_terms day), invoice_currency_code = '$session_company_currency', invoice_category_id = $category, invoice_status = 'Draft', invoice_url_key = '$url_key', invoice_client_id = $client_id"); - $invoice_id = mysqli_insert_id($mysqli); - } else { - $sql_invoice = mysqli_query($mysqli, "SELECT invoice_prefix, invoice_number FROM invoices WHERE invoice_id = $invoice_id"); - $row = mysqli_fetch_assoc($sql_invoice); - $invoice_prefix = escapeSql($row['invoice_prefix']); - $invoice_number = intval($row['invoice_number']); - } - - //Add Item - $item_name = escapeSql($_POST['item_name']); - $item_description = escapeSql($_POST['item_description']); - $qty = floatval($_POST['qty']); - $price = floatval($_POST['price']); - $tax_id = intval($_POST['tax_id']); - - $subtotal = $price * $qty; - - if ($tax_id > 0) { - $sql = mysqli_query($mysqli, "SELECT * FROM taxes WHERE tax_id = $tax_id"); - $row = mysqli_fetch_assoc($sql); - $tax_percent = floatval($row['tax_percent']); - $tax_amount = $subtotal * $tax_percent / 100; - } else { - $tax_amount = 0; - } - - $total = $subtotal + $tax_amount; - - mysqli_query($mysqli, "INSERT INTO invoice_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_order = 1, item_tax_id = $tax_id, item_invoice_id = $invoice_id"); - - //Update Invoice Balances - - $sql = mysqli_query($mysqli, "SELECT * FROM invoices WHERE invoice_id = $invoice_id"); - $row = mysqli_fetch_assoc($sql); - - $new_invoice_amount = floatval($row['invoice_amount']) + $total; - - mysqli_query($mysqli, "UPDATE invoices SET invoice_amount = $new_invoice_amount WHERE invoice_id = $invoice_id"); - - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Draft', history_description = 'Invoice created from Ticket $ticket_prefix$ticket_number', history_invoice_id = $invoice_id"); - - // Add internal note to ticket, and link to invoice in database - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Created invoice $config_invoice_prefix$invoice_number for this ticket.', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - mysqli_query($mysqli, "UPDATE tickets SET ticket_invoice_id = $invoice_id WHERE ticket_id = $ticket_id"); - - logAudit("Invoice", "Create", "$session_name created invoice $invoice_prefix$invoice_number from Ticket $ticket_prefix$ticket_number", $client_id, $invoice_id); - - flashAlert("Invoice $invoice_prefix$invoice_number created from ticket"); - - redirect("invoice.php?invoice_id=$invoice_id"); - -} - -if (isset($_POST['add_quote_from_ticket'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - enforceUserPermission('module_sales', 2); - - require_once 'quote_model.php'; - - $ticket_id = intval($_POST['ticket_id']); - $item_name = escapeSql($_POST['item_name']); - $item_description = escapeSql($_POST['item_description']); - $qty = floatval($_POST['qty']); - $price = floatval($_POST['price']); - $tax_id = intval($_POST['tax_id']); - - // Totals - $subtotal = $price * $qty; - $tax_amount = 0; - if ($tax_id > 0) { - $sql = mysqli_query($mysqli, "SELECT * FROM taxes WHERE tax_id = $tax_id"); - $row = mysqli_fetch_assoc($sql); - $tax_percent = floatval($row['tax_percent']); - $tax_amount = $subtotal * $tax_percent / 100; - } - $total = floatval($subtotal + $tax_amount); - - // Ticket info - $sql = mysqli_query( - $mysqli, - "SELECT ticket_prefix, ticket_number, ticket_client_id FROM tickets WHERE ticket_id = $ticket_id LIMIT 1" - ); - $row = mysqli_fetch_assoc($sql); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $client_id = intval($row['ticket_client_id']); - - enforceClientAccess(); - - // Atomically increment and get the new quote number - mysqli_query($mysqli, " - UPDATE settings - SET - config_quote_next_number = LAST_INSERT_ID(config_quote_next_number), - config_quote_next_number = config_quote_next_number + 1 - WHERE company_id = 1 - "); - - $quote_number = mysqli_insert_id($mysqli); - - //Generate a unique URL key for clients to access - $quote_url_key = randomString(32); - - mysqli_query($mysqli,"INSERT INTO quotes SET quote_prefix = '$config_quote_prefix', quote_number = $quote_number, quote_scope = '$scope', quote_date = '$date', quote_expire = '$expire', quote_amount = $total, quote_currency_code = '$session_company_currency', quote_category_id = $category, quote_status = 'Draft', quote_url_key = '$quote_url_key', quote_client_id = $client_id"); - - $quote_id = mysqli_insert_id($mysqli); - - // Add line item - mysqli_query($mysqli, "INSERT INTO quote_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_order = 1, item_tax_id = $tax_id, item_quote_id = $quote_id"); - - // Add internal note to ticket, and link to invoice in database - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Created quote $config_quote_prefix$quote_number for this ticket.', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - mysqli_query($mysqli, "UPDATE tickets SET ticket_quote_id = $quote_id WHERE ticket_id = $ticket_id LIMIT 1"); - - // Logging + redirects - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Draft', history_description = 'Quote created from Ticket $ticket_prefix$ticket_number!', history_quote_id = $quote_id"); - logAudit("Quote", "Create", "$session_name created quote $config_quote_prefix$quote_number from ticket $ticket_prefix$ticket_number", $client_id, $quote_id); - - triggerCustomAction('quote_create', $quote_id); - - flashAlert("Quote $config_quote_prefix$quote_number created"); - redirect("quote.php?quote_id=$quote_id"); - -} - -if (isset($_POST['export_tickets_csv'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - if ($_POST['client_id']) { - $client_id = intval($_POST['client_id']); - $client_query = "WHERE ticket_client_id = $client_id"; - $client_name = getFieldById('clients', $client_id, 'client_name'); - $file_name_prepend = "$client_name-"; - } else { - $client_query = ''; - $client_name = ''; - $file_name_prepend = "$session_company_name-"; - } - - $sql = mysqli_query( - $mysqli, - "SELECT * FROM tickets - LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id - $client_query ORDER BY ticket_number ASC" - ); - - if ($sql->num_rows > 0) { - $delimiter = ","; - $enclosure = '"'; - $escape = '\\'; // backslash - $filename = sanitizeFilename($file_name_prepend . "Tickets-" . date('Y-m-d_H-i-s') . ".csv"); - - //create a file pointer - $f = fopen('php://memory', 'w'); - - //set column headers - $fields = array('Ticket Number', 'Priority', 'Status', 'Subject', 'Date Opened', 'Date Resolved', 'Date Closed'); - fputcsv($f, $fields, $delimiter, $enclosure, $escape); - - //output each row of the data, format line as csv and write to file pointer - while ($row = $sql->fetch_assoc()) { - $lineData = array($config_ticket_prefix . $row['ticket_number'], $row['ticket_priority'], $row['ticket_status_name'], $row['ticket_subject'], $row['ticket_created_at'], $row['ticket_resolved_at'], $row['ticket_closed_at']); - fputcsv($f, array_map('escapeCsvFormula', $lineData), $delimiter, $enclosure, $escape); - } - - //move back to beginning of file - fseek($f, 0); - - //set headers to download file rather than displayed - header('Content-Type: text/csv'); - header('Content-Disposition: attachment; filename="' . $filename . '";'); - - //output all remaining data on a file pointer - fpassthru($f); - } - exit; - -} - -if (isset($_POST['edit_ticket_billable_status'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - enforceUserPermission('module_sales', 2); - - $ticket_id = intval($_POST['ticket_id']); - $billable_status = intval($_POST['billable_status']); - if ($billable_status == 0 ) { - $billable_wording = "Not"; - } - - // Get ticket details for logging - $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_client_id FROM tickets WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $client_id = intval($row['ticket_client_id']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli,"UPDATE tickets SET ticket_billable = $billable_status WHERE ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name marked ticket $ticket_prefix$ticket_number as $billable_wording Billable", $client_id, $ticket_id); - - flashAlert("Ticket marked $billable_wording Billable"); - - redirect(); - -} - -if (isset($_POST['edit_ticket_schedule'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_POST['ticket_id']); - $onsite = intval($_POST['onsite']); - $schedule = escapeSql($_POST['scheduled_date_time']); - $ticket_link = "client/ticket.php?id=$ticket_id"; - $full_ticket_url = "https://$config_base_url/client/ticket.php?id=$ticket_id"; - $ticket_link_html = "$ticket_link"; - - $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - mysqli_query($mysqli,"UPDATE tickets - SET ticket_schedule = '$schedule', ticket_onsite = $onsite - WHERE ticket_id = $ticket_id" - ); - - // Check for other conflicting scheduled items based on 2 hr window - //TODO make this configurable - $start = date('Y-m-d H:i:s', strtotime($schedule) - 7200); - $end = date('Y-m-d H:i:s', strtotime($schedule) + 7200); - $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_schedule BETWEEN '$start' AND '$end' AND ticket_id != $ticket_id"); - if (mysqli_num_rows($sql) > 0) { - $conflicting_tickets = []; - while ($row = mysqli_fetch_assoc($sql)) { - $conflicting_tickets[] = $row['ticket_id'] . " - " . $row['ticket_subject'] . " @ " . $row['ticket_schedule']; - } - } - $sql = mysqli_query($mysqli, "SELECT * FROM tickets - LEFT JOIN clients ON ticket_client_id = client_id - LEFT JOIN contacts ON ticket_contact_id = contact_id - LEFT JOIN locations on contact_location_id = location_id - LEFT JOIN users ON ticket_assigned_to = user_id - WHERE ticket_id = $ticket_id - "); - - $row = mysqli_fetch_assoc($sql); - - $client_name = escapeSql($row['client_name']); - $ticket_details = escapeSql($row['ticket_details']); - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $user_name = escapeSql($row['user_name']); - $user_email = escapeSql($row['user_email']); - $cal_subject = $ticket_number . ": " . $client_name . " - " . $ticket_subject; - $ticket_details_truncated = substr($ticket_details, 0, 100); - $cal_description = $ticket_details_truncated . " - " . $full_ticket_url; - $cal_location = escapeSql($row["location_address"]); - $email_datetime = date('l, F j, Y \a\t g:ia', strtotime($schedule)); - - if ($client_id) { - $client_uri = "&client_id=$client_id"; - } else { - $client_uri = ''; - } - - // Sanitize Config Vars - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $config_ticket_from_name = escapeSql($config_ticket_from_name); - $session_company_name = escapeSql($session_company_name); - - - /// Create iCal event - $cal_str = createiCalStr($schedule, $cal_subject, $cal_description, $cal_location); - - // Notify the agent of the scheduled work - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $user_email, - 'recipient_name' => $user_name, - 'subject' => "Ticket Scheduled - [$ticket_prefix$ticket_number] - $ticket_subject", - 'body' => "Hello, " . $user_name . "

The ticket regarding $ticket_subject has been scheduled for $email_datetime.

--------------------------------
$ticket_link
--------------------------------

Please do not reply to this email.

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Portal: https://$config_base_url/agent/ticket.php?ticket_id=$ticket_id$client_uri

~
$session_company_name
Support Department
$config_ticket_from_email", - 'cal_str' => $cal_str - ]; - - if ($config_ticket_client_general_notifications) { - // Notify the ticket contact of the scheduled work - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => "Ticket Scheduled - [$ticket_prefix$ticket_number] - $ticket_subject", - 'body' => mysqli_escape_string($mysqli, "
- Hello, $contact_name -
- Your ticket regarding $ticket_subject has been scheduled for $email_datetime. -

- Access your ticket here -

- Please do not reply to this email. -

- Ticket: $ticket_prefix$ticket_number
- Subject: $ticket_subject
-

- -
- This is an automated message. Please do not reply directly to this email. -
"), - 'cal_str' => $cal_str - ]; - - // Notify the watchers of the scheduled work - $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); - - while ($row = mysqli_fetch_assoc($sql_watchers)) { - $watcher_email = escapeSql($row['watcher_email']); - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $watcher_email, - 'recipient_name' => $watcher_email, - 'subject' => "Ticket Scheduled - [$ticket_prefix$ticket_number] - $ticket_subject", - 'body' => mysqli_escape_string($mysqli, escapeHtml("
- Hello, -
- The ticket regarding $ticket_subject has been scheduled for $email_datetime. -

- $ticket_link -

- Please do not reply to this email. -

- Ticket: $ticket_prefix$ticket_number
- Subject: $ticket_subject
- Portal: Access the ticket here -

- -
- This is an automated message. Please do not reply directly to this email. -
")), - 'cal_str' => $cal_str - ]; - } - } - - // Send - $response = addToMailQueue($data); - - // Update ticket reply - $ticket_reply_note = "Ticket scheduled for $email_datetime " . (boolval($onsite) ? '(onsite).' : '(remote).'); - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply_note', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name edited ticket schedule", $client_id, $ticket_id); - - triggerCustomAction('ticket_schedule', $ticket_id); - - if (empty($conflicting_tickets)) { - flashAlert("Ticket scheduled for $email_datetime"); - redirect(); - } else { - $_SESSION['alert_type'] = "error"; - flashAlert("Ticket scheduled for $email_datetime. Yet there are conflicting tickets scheduled for the same time:
" . implode(",
", $conflicting_tickets), 'error'); - redirect("calendar.php"); - } - -} - -if (isset($_GET['cancel_ticket_schedule'])) { - - validateCSRFToken(); - - enforceUserPermission('module_support', 2); - - $ticket_id = intval($_GET['cancel_ticket_schedule']); - - $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); - $row = mysqli_fetch_assoc($sql); - - $client_id = intval($row['ticket_client_id']); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $ticket_schedule = escapeSql($row['ticket_schedule']); - $ticket_cal_str = escapeSql($row['ticket_cal_str']); - - // Don't Enforce Client Access if Ticket doesn't have an assigned client - if ($client_id) { - enforceClientAccess(); - } - - if ($client_id) { - $client_uri = "&client_id=$client_id"; - } else { - $client_uri = ''; - } - - mysqli_query($mysqli, "UPDATE tickets SET ticket_schedule = NULL WHERE ticket_id = $ticket_id"); - - // Sanitize Config Vars - $config_ticket_from_email = escapeSql($config_ticket_from_email); - $config_ticket_from_name = escapeSql($config_ticket_from_name); - $session_company_name = escapeSql($session_company_name); - - //Create iCal event - $cal_str = createiCalStrCancel($ticket_cal_str); - - //Send emails - - $sql = mysqli_query($mysqli, "SELECT * FROM tickets - LEFT JOIN clients ON ticket_client_id = client_id - LEFT JOIN contacts ON ticket_contact_id = contact_id - LEFT JOIN locations on contact_location_id = location_id - LEFT JOIN users ON ticket_assigned_to = user_id - WHERE ticket_id = $ticket_id - "); - $row = mysqli_fetch_assoc($sql); - - $client_id = intval($row['ticket_client_id']); - $client_name = escapeSql($row['client_name']); - $ticket_details = escapeSql($row['ticket_details']); - $contact_name = escapeSql($row['contact_name']); - $contact_email = escapeSql($row['contact_email']); - $ticket_prefix = escapeSql($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = escapeSql($row['ticket_subject']); - $user_name = escapeSql($row['user_name']); - $user_email = escapeSql($row['user_email']); - - // Notify the agent of the cancellation - $data[] = [ - // User Email - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $user_email, - 'recipient_name' => $user_name, - 'subject' => "Ticket Schedule Cancelled - [$ticket_prefix$ticket_number] - $ticket_subject", - 'body' => "Hello, " . $user_name . "

Scheduled work for the ticket regarding $ticket_subject has been cancelled.

--------------------------------
$ticket_link
--------------------------------

Please do not reply to this email.

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Portal: https://$config_base_url/agent/ticket.php?id=$ticket_id&client_id=$client_id

~
$session_company_name
Support Department
$config_ticket_from_email", - 'cal_str' => $cal_str - ]; - - if ($config_ticket_client_general_notifications) { - // Notify the ticket contact of the cancellation - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => "Ticket Schedule Cancelled - [$ticket_prefix$ticket_number] - $ticket_subject", - 'body' => mysqli_escape_string($mysqli, "
- Hello, $contact_name -
- Scheduled work for your ticket regarding $ticket_subject has been cancelled. -

- Access your ticket here -

- Please do not reply to this email. -

- Ticket: $ticket_prefix$ticket_number
- Subject: $ticket_subject
-

- -
- This is an automated message. Please do not reply directly to this email. -
"), - 'cal_str' => $cal_str - ]; - - // Notify the watchers of the cancellation - $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); - while ($row = mysqli_fetch_assoc($sql_watchers)) { - $watcher_email = escapeSql($row['watcher_email']); - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $watcher_email, - 'recipient_name' => $watcher_email, - 'subject' => "Ticket Schedule Cancelled - [$ticket_prefix$ticket_number] - $ticket_subject", - 'body' => mysqli_escape_string($mysqli, escapeHtml("
- Hello, -
- Scheduled work for the ticket regarding $ticket_subject has been cancelled. -

- $ticket_link -

- Please do not reply to this email. -

- Ticket: $ticket_prefix$ticket_number
- Subject: $ticket_subject
- Portal: Access the ticket here -

- -
- This is an automated message. Please do not reply directly to this email. -
")), - 'cal_str' => $cal_str - ]; - } - } - - // Send email(s) - addToMailQueue($data); - - // Update ticket reply - $ticket_reply_note = "Ticket schedule cancelled."; - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply_note', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); - - logAudit("Ticket", "Edit", "$session_name cancelled ticket schedule", $client_id, $ticket_id); - - triggerCustomAction('ticket_unschedule', $ticket_id); - - flashAlert("Ticket schedule cancelled", 'error'); - - redirect(); - -} + + if ($d !== false) { + $due = "'" . $d->format('Y-m-d H:i:s') . "'"; // wrap in quotes for SQL + } else { + $due = 'NULL'; // fallback if invalid + } + } + + enforceClientAccess(); + + // 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"); + $row = mysqli_fetch_assoc($sql); + $contact_id = intval($row['contact_id']); + } + + // Atomically increment and get the new ticket number + mysqli_query($mysqli, " + UPDATE settings + SET + config_ticket_next_number = LAST_INSERT_ID(config_ticket_next_number), + config_ticket_next_number = config_ticket_next_number + 1 + WHERE company_id = 1 + "); + + $ticket_number = mysqli_insert_id($mysqli); + + // Sanitize Config Vars from get_settings.php and Session Vars from check_login.php + $config_ticket_prefix = escapeSql($config_ticket_prefix); + $config_ticket_from_name = escapeSql($config_ticket_from_name); + $config_ticket_from_email = escapeSql($config_ticket_from_email); + $config_base_url = escapeSql($config_base_url); + + //Generate a unique URL key for clients to access + $url_key = randomString(32); + + mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$config_ticket_prefix', ticket_number = $ticket_number, ticket_source = 'Agent', ticket_category = $category_id, ticket_subject = '$subject', ticket_details = '$details', ticket_priority = '$priority', ticket_billable = '$billable', ticket_status = '$ticket_status', ticket_vendor_ticket_number = '$vendor_ticket_number', ticket_vendor_id = $vendor_id, ticket_location_id = $location_id, ticket_asset_id = $asset_id, ticket_created_by = $session_user_id, ticket_assigned_to = $assigned_to, ticket_contact_id = $contact_id, ticket_url_key = '$url_key', ticket_due_at = $due, ticket_client_id = $client_id, ticket_invoice_id = 0, ticket_project_id = $project_id"); + + $ticket_id = mysqli_insert_id($mysqli); + + // 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_assoc($sql_task_templates)) { + $task_order = intval($row['task_template_order']); + $task_name = escapeSql($row['task_template_name']); + $task_completion_estimate = intval($row['task_template_completion_estimate']); + + mysqli_query($mysqli,"INSERT INTO tasks SET task_name = '$task_name', task_order = $task_order, task_completion_estimate = $task_completion_estimate, task_ticket_id = $ticket_id"); + } + } + } + + // Add Watchers + if (isset($_POST['watchers'])) { + foreach ($_POST['watchers'] as $watcher) { + $watcher_email = escapeSql($watcher); + mysqli_query($mysqli, "INSERT INTO ticket_watchers SET watcher_email = '$watcher_email', watcher_ticket_id = $ticket_id"); + } + } + + // Add Additional Assets + if (isset($_POST['additional_assets'])) { + foreach ($_POST['additional_assets'] as $additional_asset) { + $additional_asset_id = intval($additional_asset); + mysqli_query($mysqli, "INSERT INTO ticket_assets SET ticket_id = $ticket_id, asset_id = $additional_asset_id"); + } + } + + // E-mail client + if ((!empty($config_smtp_provider) || !empty($config_smtp_provider)) && $config_ticket_client_general_notifications == 1) { + + // Get contact/ticket details + $sql = mysqli_query($mysqli, "SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_category, ticket_subject, ticket_details, ticket_priority, ticket_status, ticket_created_by, ticket_assigned_to, ticket_client_id FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + + $contact_name = escapeSql($row['contact_name']); + $contact_email = escapeSql($row['contact_email']); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_category = escapeSql($row['ticket_category']); + $ticket_subject = escapeSql($row['ticket_subject']); + $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); + $ticket_priority = escapeSql($row['ticket_priority']); + $ticket_status = escapeSql($row['ticket_status']); + $ticket_status_name = escapeSql(getTicketStatusName($row['ticket_status'])); + $client_id = intval($row['ticket_client_id']); + $ticket_created_by = intval($row['ticket_created_by']); + $ticket_assigned_to = intval($row['ticket_assigned_to']); + + // Get Company Phone Number + $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); + $row = mysqli_fetch_assoc($sql); + $company_name = escapeSql($row['company_name']); + $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); + + // EMAILING + + $subject = "Ticket Created [$ticket_prefix$ticket_number] - $ticket_subject"; + $body = "##- Please type your reply above this line -##

Hello $contact_name,

A ticket regarding \"$ticket_subject\" has been created for you.

--------------------------------
$ticket_details--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: Open
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + + // Verify contact email is valid + if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { + + + // Email Ticket Contact + // Queue Mail + $data = []; + + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body + ]; + } + + // Also Email all the watchers + $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); + $body .= "

----------------------------------------
YOU HAVE BEEN ADDED AS A COLLABORATOR FOR THIS TICKET"; + while ($row = mysqli_fetch_assoc($sql_watchers)) { + $watcher_email = escapeSql($row['watcher_email']); + + // Queue Mail + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $watcher_email, + 'recipient_name' => $watcher_email, + 'subject' => $subject, + 'body' => $body + ]; + } + addToMailQueue($data); + + // END EMAILING + + } + + // Custom action/notif handler + triggerCustomAction('ticket_create', $ticket_id); + + logAudit("Ticket", "Create", "$session_name created ticket $config_ticket_prefix$ticket_number - $ticket_subject", $client_id, $ticket_id); + + flashAlert("Ticket $config_ticket_prefix$ticket_number created"); + + redirect("ticket.php?client_id=$client_id&ticket_id=$ticket_id"); + +} + +if (isset($_POST['edit_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); + $contact_id = intval($_POST['contact_id']); + $assigned_to = intval($_POST['assigned_to']); + $notify = intval($_POST['contact_notify'] ?? 0); + $category_id = intval($_POST['category_id']); + $ticket_subject = escapeSql($_POST['subject']); + $billable = intval($_POST['billable'] ?? 0); + $ticket_priority = escapeSql($_POST['priority']); + $details = mysqli_real_escape_string($mysqli, $_POST['details']); + $vendor_ticket_number = escapeSql($_POST['vendor_ticket_number']); + $vendor_id = intval($_POST['vendor_id']); + $asset_id = intval($_POST['asset_id']); + $location_id = intval($_POST['location_id']); + $project_id = intval($_POST['project_id']); + // Validate/clean due field + $dueInput = $_POST['due'] ?? null; + if ($dueInput === null || trim($dueInput) === '') { + $due = 'NULL'; // prepare as SQL-safe string + } else { + $d = DateTime::createFromFormat('Y-m-d\TH:i', $dueInput); // for + if ($d !== false) { + $due = "'" . $d->format('Y-m-d H:i:s') . "'"; // wrap in quotes for SQL + } else { + $due = 'NULL'; // fallback if invalid + } + } + + $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "UPDATE tickets SET ticket_category = $category_id, ticket_subject = '$ticket_subject', ticket_priority = '$ticket_priority', ticket_billable = $billable, ticket_details = '$details', ticket_due_at = $due, ticket_vendor_ticket_number = '$vendor_ticket_number', ticket_contact_id = $contact_id, ticket_assigned_to = $assigned_to, ticket_vendor_id = $vendor_id, ticket_location_id = $location_id, ticket_asset_id = $asset_id, ticket_project_id = $project_id WHERE ticket_id = $ticket_id"); + + // Add Additional Assets + if (isset($_POST['additional_assets'])) { + mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id"); + foreach ($_POST['additional_assets'] as $additional_asset) { + $additional_asset_id = intval($additional_asset); + mysqli_query($mysqli, "INSERT INTO ticket_assets SET ticket_id = $ticket_id, asset_id = $additional_asset_id"); + } + } else { + // If no additional assets are provided, delete them all + // This handles cases where the assets input might be cleared or not set at all. + mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id"); + } + + // Get contact/ticket details after update for logging / email purposes + $sql = mysqli_query($mysqli, "SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_category, ticket_details, ticket_status_name, ticket_created_by, ticket_assigned_to, ticket_url_key, ticket_client_id FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + WHERE ticket_id = $ticket_id + AND ticket_closed_at IS NULL"); + $row = mysqli_fetch_assoc($sql); + + $contact_name = escapeSql($row['contact_name']); + $contact_email = escapeSql($row['contact_email']); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_category = escapeSql($row['ticket_category']); + $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); + $ticket_status = escapeSql($row['ticket_status_name']); + $ticket_created_by = intval($row['ticket_created_by']); + $ticket_assigned_to = intval($row['ticket_assigned_to']); + $url_key = escapeSql($row['ticket_url_key']); + $client_id = intval($row['ticket_client_id']); + + // Notify new contact if selected + if ($notify && (!empty($config_smtp_provider) || !empty($config_smtp_provider))) { + + // Get Company Name Phone Number and Sanitize for Email Sending + $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); + $row = mysqli_fetch_assoc($sql); + $company_name = escapeSql($row['company_name']); + $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); + + // Email content + $data = []; // Queue array + + $subject = "Ticket Created - [$ticket_prefix$ticket_number] - $ticket_subject"; + $body = "##- Please type your reply above this line -##

Hello $contact_name,

A ticket regarding \"$ticket_subject\" has been created for you.

--------------------------------
$ticket_details--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + + + // Only add contact to email queue if email is valid + if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body + ]; + } + + addToMailQueue($data); + } + + // Custom action/notif handler + triggerCustomAction('ticket_update', $ticket_id); + + logAudit("Ticket", "Edit", "$session_name edited ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); + + flashAlert("Ticket $ticket_prefix$ticket_number updated"); + + redirect(); + +} + +if (isset($_POST['edit_ticket_priority'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); + $priority = escapeSql($_POST['priority']); + + // Get ticket details before updating + $sql = mysqli_query($mysqli, "SELECT + ticket_prefix, ticket_number, ticket_priority, ticket_status_name, ticket_client_id + FROM tickets + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + WHERE ticket_id = $ticket_id" + ); + $row = mysqli_fetch_assoc($sql); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $original_priority = escapeSql($row['ticket_priority']); + $ticket_status = escapeSql($row['ticket_status_name']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "UPDATE tickets SET ticket_priority = '$priority' WHERE ticket_id = $ticket_id"); + + // Update Ticket History + mysqli_query($mysqli, "INSERT INTO ticket_history SET ticket_history_status = '$ticket_status', ticket_history_description = '$session_name changed priority from $original_priority to $priority', ticket_history_ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name changed priority from $original_priority to $priority for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); + + triggerCustomAction('ticket_update', $ticket_id); + + flashAlert("Priority updated from $original_priority to $priority"); + + redirect(); + +} + +if (isset($_POST['edit_ticket_contact'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); + $contact_id = intval($_POST['contact']); + $notify = intval($_POST['contact_notify']) ?? 0; + + // Get Original contact, and ticket details + $sql = mysqli_query($mysqli, "SELECT + contact_name, ticket_prefix, ticket_number, ticket_status_name, ticket_subject, ticket_details, ticket_url_key, ticket_client_id + FROM tickets + LEFT JOIN contacts ON ticket_contact_id = contact_id + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + WHERE ticket_id = $ticket_id" + ); + $row = mysqli_fetch_assoc($sql); + + // Original contact + $original_contact_name = !empty($row['contact_name']) ? escapeSql($row['contact_name']) : 'No one'; + + // Ticket details + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_status = escapeSql($row['ticket_status_name']); + $ticket_subject = escapeSql($row['ticket_subject']); + $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); + $url_key = escapeSql($row['ticket_url_key']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + // Update the contact + mysqli_query($mysqli, "UPDATE tickets SET ticket_contact_id = $contact_id WHERE ticket_id = $ticket_id"); + + // Get New contact details + $sql = mysqli_query($mysqli, "SELECT contact_name, contact_email FROM contacts WHERE contact_id = $contact_id"); + $row = mysqli_fetch_assoc($sql); + + $contact_name = !empty($row['contact_name']) ? escapeSql($row['contact_name']) : 'No one'; + $contact_email = escapeSql($row['contact_email']); + + // Notify new contact (if selected, valid & configured) + if ($notify && filter_var($contact_email, FILTER_VALIDATE_EMAIL) && (!empty($config_smtp_provider) || !empty($config_smtp_provider))) { + + // Get Company Phone Number + $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); + $row = mysqli_fetch_assoc($sql); + $company_name = escapeSql($row['company_name']); + $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); + + $config_ticket_from_email = escapeSql($config_ticket_from_email); + $config_ticket_from_name = escapeSql($config_ticket_from_name); + + // Email content + $data = []; // Queue array + + $subject = "Ticket Created - [$ticket_prefix$ticket_number] - $ticket_subject"; + $body = "##- Please type your reply above this line -##

Hello $contact_name,

A ticket regarding \"$ticket_subject\" has been created for you.

--------------------------------
$ticket_details--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body + ]; + + addToMailQueue($data); + } + + // Custom action/notif handler + triggerCustomAction('ticket_update', $ticket_id); + + // Update Ticket History + mysqli_query($mysqli, "INSERT INTO ticket_history SET ticket_history_status = '$ticket_status', ticket_history_description = '$session_name changed the contact from $original_contact_name to $contact_name', ticket_history_ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name changed the contact from $original_contact_name to $contact_name for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); + + flashAlert("Contact changed from $original_contact_name to $contact_name"); + + redirect(); + +} + +if (isset($_POST['edit_ticket_project'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); + $project_id = intval($_POST['project']); + + $project_name = escapeSql(getFieldById('projects', $project_id, 'project_name')); + $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); + $ticket_prefix = escapeSql(getFieldById('tickets', $ticket_id, 'ticket_prefix')); + $ticket_number = escapeSql(getFieldById('tickets', $ticket_id, 'ticket_number')); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "UPDATE tickets SET ticket_project_id = $project_id WHERE ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name set ticket $ticket_prefix$ticket_number project to $project_name", $client_id, $ticket_id); + + flashAlert("Project changed to $project_name for Ticket $ticket_prefix$ticket_number"); + + redirect(); + +} + +if (isset($_POST['add_ticket_watcher'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); + $watcher_emails = preg_split("/,| |;/", $_POST['watcher_email']); // Split on comma, semicolon or space, we sanitize later + $notify = intval($_POST['watcher_notify'] ?? 0); + + // Get contact/ticket details + $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_category, ticket_subject, ticket_details, ticket_priority, ticket_status_name, ticket_url_key, ticket_created_by, ticket_assigned_to, ticket_client_id FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + WHERE ticket_id = $ticket_id + AND ticket_closed_at IS NULL"); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_category = escapeSql($row['ticket_category']); + $ticket_subject = escapeSql($row['ticket_subject']); + $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); + $ticket_priority = escapeSql($row['ticket_priority']); + $ticket_status = escapeSql($row['ticket_status_name']); + $url_key = escapeSql($row['ticket_url_key']); + $client_id = intval($row['ticket_client_id']); + $ticket_created_by = intval($row['ticket_created_by']); + $ticket_assigned_to = intval($row['ticket_assigned_to']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + // Get Company Phone Number + $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); + $row = mysqli_fetch_assoc($sql); + $company_name = escapeSql($row['company_name']); + $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); + + // Process each watcher in list + foreach ($watcher_emails as $watcher_email) { + + if (filter_var($watcher_email, FILTER_VALIDATE_EMAIL)) { + + $watcher_email = escapeSql($watcher_email); + + mysqli_query($mysqli, "INSERT INTO ticket_watchers SET watcher_email = '$watcher_email', watcher_ticket_id = $ticket_id"); + + // Notify watcher + if ($notify && (!empty($config_smtp_provider))) { + + + + // Email content + $data = []; // Queue array + + $subject = "Ticket Notification - [$ticket_prefix$ticket_number] - $ticket_subject"; + $body = "##- Please type your reply above this line -##

Hello,

You have been added as a collaborator on this ticket regarding \"$ticket_subject\".

--------------------------------
$ticket_details--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status
Guest link: https://$config_base_url/guest/guest_view_ticket.php?ticket_id=$ticket_id&url_key=$url_key

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $watcher_email, + 'recipient_name' => $watcher_email, + 'subject' => $subject, + 'body' => $body + ]; + + addToMailQueue($data); + } + + logAudit("Ticket", "Edit", "$session_name added $watcher_email as a watcher for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); + } + + } + + flashAlert("Added watcher(s)"); + + redirect(); + +} + +if (isset($_GET['delete_ticket_watcher'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $watcher_id = intval($_GET['delete_ticket_watcher']); + + // Get ticket / watcher details for logging + $sql = mysqli_query($mysqli, "SELECT watcher_email, ticket_prefix, ticket_number, ticket_status_name, ticket_client_id, ticket_id FROM ticket_watchers + LEFT JOIN tickets ON watcher_ticket_id = ticket_id + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + WHERE watcher_id = $watcher_id" + ); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_status_name = escapeSql($row['ticket_status_name']); + $watcher_email = escapeSql($row['watcher_email']); + $client_id = intval($row['ticket_client_id']); + $ticket_id = intval($row['ticket_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "DELETE FROM ticket_watchers WHERE watcher_id = $watcher_id"); + + // History + mysqli_query($mysqli, "INSERT INTO ticket_history SET ticket_history_status = '$ticket_status_name', ticket_history_description = '$session_name removed ticket $watcher_email as a watcher', ticket_history_ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name removed $watcher_email as a watcher for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); + + flashAlert("Removed ticket watcher $watcher_email", 'error'); + + redirect(); + +} + +if (isset($_GET['delete_ticket_additional_asset'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $asset_id = intval($_GET['delete_ticket_additional_asset']); + $ticket_id = intval($_GET['ticket_id']); + + // Get ticket / asset details for logging + $sql = mysqli_query($mysqli, "SELECT asset_name, ticket_prefix, ticket_number, ticket_status_name, ticket_client_id FROM assets + JOIN tickets ON ticket_id = $ticket_id + JOIN ticket_statuses ON ticket_status = ticket_status_id + WHERE asset_id = $asset_id" + ); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_status_name = escapeSql($row['ticket_status_name']); + $asset_name = escapeSql($row['asset_name']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id AND asset_id = $asset_id"); + + // History + mysqli_query($mysqli, "INSERT INTO ticket_history SET ticket_history_status = '$ticket_status_name', ticket_history_description = '$session_name removed additional asset $asset_name', ticket_history_ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name removed asset $asset_name from ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); + + flashAlert("Removed asset $asset_name from ticket.", 'error'); + + redirect(); + +} + +if (isset($_POST['edit_ticket_asset'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); + $asset_id = intval($_POST['asset']); + + $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "UPDATE tickets SET ticket_asset_id = $asset_id WHERE ticket_id = $ticket_id"); + + // Add Additional Assets + if (isset($_POST['additional_assets'])) { + mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id"); + foreach ($_POST['additional_assets'] as $additional_asset) { + $additional_asset_id = intval($additional_asset); + mysqli_query($mysqli, "INSERT INTO ticket_assets SET ticket_id = $ticket_id, asset_id = $additional_asset_id"); + } + } else { + // If no additional assets are provided, delete them all + // This handles cases where the assets input might be cleared or not set at all. + mysqli_query($mysqli, "DELETE FROM ticket_assets WHERE ticket_id = $ticket_id"); + } + + // Get ticket / asset details for logging + $sql = mysqli_query($mysqli, "SELECT asset_name, ticket_prefix, ticket_number, ticket_status_name, ticket_client_id FROM assets + LEFT JOIN tickets ON ticket_asset_id = asset_id + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + WHERE ticket_id = $ticket_id" + ); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_status_name = escapeSql($row['ticket_status_name']); + $asset_name = escapeSql($row['asset_name']); + $client_id = intval($row['ticket_client_id']); + + logAudit("Ticket", "Edit", "$session_name changed asset to $asset_name for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); + + flashAlert("Ticket $ticket_prefix$ticket_number asset updated to $asset_name"); + + redirect(); + +} + +if (isset($_POST['edit_ticket_vendor'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); + $vendor_id = intval($_POST['vendor']); + + $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "UPDATE tickets SET ticket_vendor_id = $vendor_id WHERE ticket_id = $ticket_id"); + + // Get ticket / vendor details for logging + $sql = mysqli_query($mysqli, "SELECT vendor_name, ticket_prefix, ticket_number, ticket_status_name, ticket_client_id FROM vendors + LEFT JOIN tickets ON ticket_vendor_id = $vendor_id + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + WHERE ticket_id = $ticket_id" + ); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_status_name = escapeSql($row['ticket_status_name']); + $vendor_name = escapeSql($row['vendor_name']); + $client_id = intval($row['ticket_client_id']); + + logAudit("Ticket", "Edit", "$session_name set vendor to $vendor_name for ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); + + flashAlert("Set vendor to $vendor_name for ticket $ticket_prefix$ticket_number"); + + redirect(); + +} + +if (isset($_POST['assign_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + // POST variables + $ticket_id = intval($_POST['ticket_id']); + $assigned_to = intval($_POST['assigned_to']); + $ticket_status = intval($_POST['ticket_status']); + + // New > Open as assigned + if ($ticket_status == 1 && $assigned_to !== 0) { + $ticket_status = 2; + } + + // Allow for un-assigning tickets + if ($assigned_to == 0) { + $ticket_reply = "Ticket unassigned."; + $agent_name = "No One"; + } else { + // Get & verify assigned agent details + $agent_details_sql = mysqli_query($mysqli, "SELECT user_name, user_email FROM users WHERE users.user_id = $assigned_to"); + $agent_details = mysqli_fetch_assoc($agent_details_sql); + + $agent_name = escapeSql($agent_details['user_name']); + $agent_email = escapeSql($agent_details['user_email']); + $ticket_reply = "Ticket re-assigned to $agent_name."; + + if (!$agent_name) { + flashAlert("Invalid agent!", 'error'); + redirect(); + } + } + + // Get & verify ticket details + $ticket_details_sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, ticket_client_id, client_name FROM tickets LEFT JOIN clients ON ticket_client_id = client_id WHERE ticket_id = '$ticket_id' AND ticket_status != 5"); + $ticket_details = mysqli_fetch_assoc($ticket_details_sql); + + $ticket_prefix = escapeSql($ticket_details['ticket_prefix']); + $ticket_number = intval($ticket_details['ticket_number']); + $ticket_subject = escapeSql($ticket_details['ticket_subject']); + $client_id = intval($ticket_details['ticket_client_id']); + $client_name = escapeSql($ticket_details['client_name']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + if (!$ticket_subject) { + flashAlert("Invalid ticket!", 'error'); + redirect(); + } + + if ($client_id) { + $client_uri = "&client_id=$client_id"; + } else { + $client_uri = ''; + } + + // Update ticket & insert reply + mysqli_query($mysqli, "UPDATE tickets SET ticket_assigned_to = $assigned_to, ticket_status = '$ticket_status' WHERE ticket_id = $ticket_id"); + + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name reassigned $ticket_prefix$ticket_number to $agent_name", $client_id, $ticket_id); + + // Notification + if ($session_user_id != $assigned_to && $assigned_to != 0) { + + // App Notification + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = 'Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject has been assigned to you by $session_name', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $assigned_to"); + + // Email Notification + if (!empty($config_smtp_provider)) { + + // Sanitize Config vars from get_settings.php + $config_ticket_from_name = escapeSql($config_ticket_from_name); + $config_ticket_from_email = escapeSql($config_ticket_from_email); + $company_name = escapeSql($session_company_name); + + $subject = "$config_app_name - Ticket $ticket_prefix$ticket_number assigned to you - $ticket_subject"; + $body = "Hi $agent_name,

A ticket has been assigned to you!

Client: $client_name
Ticket Number: $ticket_prefix$ticket_number
Subject: $ticket_subject

https://$config_base_url/agent/ticket.php?ticket_id=$ticket_id$client_uri

Thanks,
$session_name
$company_name"; + + // Email Ticket Agent + // Queue Mail + $data = [ + [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $agent_email, + 'recipient_name' => $agent_name, + 'subject' => $subject, + 'body' => $body, + ] + ]; + addToMailQueue($data); + } + } + + triggerCustomAction('ticket_assign', $ticket_id); + + flashAlert("Ticket $ticket_prefix$ticket_number assigned to $agent_name"); + + redirect(); + +} + +if (isset($_GET['delete_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 3); + + $ticket_id = intval($_GET['delete_ticket']); + + // Get Ticket and Client ID for logging and alert message + $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_closed_at, ticket_client_id FROM tickets WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = escapeSql($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $ticket_status = escapeSql($row['ticket_status']); + $ticket_closed_at = escapeSql($row['ticket_closed_at']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + if (empty($ticket_closed_at)) { + mysqli_query($mysqli, "DELETE FROM tickets WHERE ticket_id = $ticket_id"); + + // Delete all ticket replies + mysqli_query($mysqli, "DELETE FROM ticket_replies WHERE ticket_reply_ticket_id = $ticket_id"); + + // Delete all ticket views + mysqli_query($mysqli, "DELETE FROM ticket_views WHERE view_ticket_id = $ticket_id"); + + // Delete ticket watchers + mysqli_query($mysqli, "DELETE FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); + + // Delete Ticket Attachements + mysqli_query($mysqli, "DELETE FROM ticket_attachments WHERE ticket_attachment_ticket_id = $ticket_id"); + removeDirectory("../uploads/tickets/$ticket_id"); + + // No Need to delete ticket assets as this is cascadely deleted via the database. + + logAudit("Ticket", "Delete", "$session_name deleted $ticket_prefix$ticket_number along with all replies", $client_id); + + flashAlert("Ticket $ticket_prefix$ticket_number along with all replies deleted", 'error'); + + triggerCustomAction('ticket_delete', $ticket_id); + + redirect("tickets.php"); + } + +} + +if (isset($_POST['bulk_delete_tickets'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 3); + + if (isset($_POST['ticket_ids'])) { + + $count = count($_POST['ticket_ids']); + + // Cycle through array and delete each recurring scheduled ticket + foreach ($_POST['ticket_ids'] as $ticket_id) { + + $ticket_id = intval($ticket_id); + + $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "DELETE FROM tickets WHERE ticket_id = $ticket_id"); + + // Delete all ticket replies + mysqli_query($mysqli, "DELETE FROM ticket_replies WHERE ticket_reply_ticket_id = $ticket_id"); + + // Delete all ticket views + mysqli_query($mysqli, "DELETE FROM ticket_views WHERE view_ticket_id = $ticket_id"); + + // Delete ticket watchers + mysqli_query($mysqli, "DELETE FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); + + // Delete Ticket Attachements + mysqli_query($mysqli, "DELETE FROM ticket_attachments WHERE ticket_attachment_ticket_id = $ticket_id"); + removeDirectory("../uploads/tickets/$ticket_id"); + + // No Need to delete ticket assets as this is cascadely deleted via the database. + + logAudit("Ticket", "Delete", "$session_name deleted ticket", 0, $ticket_id); + + } + + logAudit("Ticket", "Bulk Delete", "$session_name deleted $count ticket(s)"); + + flashAlert("Deleted $count ticket(s)", 'error'); + } + + redirect(); + +} + +if (isset($_POST['bulk_assign_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + // POST variables + $assign_to = intval($_POST['assign_to']); + + // Get a Ticket Count + $ticket_count = count($_POST['ticket_ids']); + + // Assign Tech to Selected Tickets + if (!empty($_POST['ticket_ids'])) { + foreach ($_POST['ticket_ids'] as $ticket_id) { + $ticket_id = intval($ticket_id); + + $sql = mysqli_query($mysqli, "SELECT * FROM tickets LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_status = intval($row['ticket_status']); + $ticket_name = escapeSql($row['ticket_name']); + $ticket_subject = escapeSql($row['ticket_subject']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + if ($ticket_status == 1 && $assigned_to !== 0) { + $ticket_status = 2; + } + + // Allow for un-assigning tickets + if ($assign_to == 0) { + $ticket_reply = "Ticket unassigned, pending re-assignment."; + $agent_name = "No One"; + } else { + // Get & verify assigned agent details + $agent_details_sql = mysqli_query($mysqli, "SELECT user_name, user_email FROM users LEFT JOIN user_settings ON users.user_id = user_settings.user_id WHERE users.user_id = $assign_to"); + $agent_details = mysqli_fetch_assoc($agent_details_sql); + + $agent_name = escapeSql($agent_details['user_name']); + $agent_email = escapeSql($agent_details['user_email']); + $ticket_reply = "Ticket re-assigned to $agent_name."; + + if (!$agent_name) { + flashAlert("Invalid agent!", 'error'); + redirect(); + } + } + + // Update ticket & insert reply + mysqli_query($mysqli, "UPDATE tickets SET ticket_assigned_to = $assign_to, ticket_status = $ticket_status WHERE ticket_id = $ticket_id"); + + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name reassigned ticket $ticket_prefix$ticket_number to $agent_name", $client_id, $ticket_id); + + triggerCustomAction('ticket_assign', $ticket_id); + + $tickets_assigned_body .= "$ticket_prefix$ticket_number - $ticket_subject
"; + } // End For Each Ticket ID Loop + + // Notification + if ($session_user_id != $assign_to && $assign_to != 0) { + + // App Notification + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$ticket_count Tickets have been assigned to you by $session_name', notification_action = 'tickets.php?status=Open&assigned=$assign_to', notification_client_id = $client_id, notification_user_id = $assign_to"); + + // Agent Email Notification + if (!empty($config_smtp_provider)) { + + // Sanitize Config vars from get_settings.php + $config_ticket_from_name = escapeSql($config_ticket_from_name); + $config_ticket_from_email = escapeSql($config_ticket_from_email); + $company_name = escapeSql($session_company_name); + + $subject = "$config_app_name - $ticket_count tickets have been assigned to you"; + $body = "Hi $agent_name,

$session_name assigned $ticket_count tickets to you!

$tickets_assigned_body
Thanks,
$session_name
$company_name"; + + // Email Ticket Agent + // Queue Mail + $data = [ + [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $agent_email, + 'recipient_name' => $agent_name, + 'subject' => $subject, + 'body' => $body, + ] + ]; + addToMailQueue($data); + } + } + } + + flashAlert("You assigned $ticket_count Tickets to $agent_name"); + + redirect(); + +} + +if (isset($_POST['bulk_edit_ticket_priority'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + // POST variables + $priority = escapeSql($_POST['bulk_priority']); + + // Assign Tech to Selected Tickets + if (isset($_POST['ticket_ids'])) { + + // Get a Ticket Count + $ticket_count = count($_POST['ticket_ids']); + + foreach ($_POST['ticket_ids'] as $ticket_id) { + $ticket_id = intval($ticket_id); + + $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $original_ticket_priority = escapeSql($row['ticket_priority']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + // Update ticket & insert reply + mysqli_query($mysqli, "UPDATE tickets SET ticket_priority = '$priority' WHERE ticket_id = $ticket_id"); + + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$session_name updated the priority from $current_ticket_priority to $priority', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name updated the priority on ticket $ticket_prefix$ticket_number - $ticket_subject from $original_ticket_priority to $priority", $client_id, $ticket_id); + + triggerCustomAction('ticket_update', $ticket_id); + } // End For Each Ticket ID Loop + + logAudit("Ticket", " Bulk Edit", "$session_name updated the priority on $ticket_count"); + + flashAlert("You updated the priority for $ticket_count Tickets to $priority"); + } + + redirect(); + +} + +if (isset($_POST['bulk_edit_ticket_category'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + // POST variables + $category_id = intval($_POST['bulk_category']); + + // Assign Tech to Selected Tickets + if (isset($_POST['ticket_ids'])) { + + // Get a Ticket Count + $ticket_count = count($_POST['ticket_ids']); + + foreach ($_POST['ticket_ids'] as $ticket_id) { + $ticket_id = intval($ticket_id); + + $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, category_name, ticket_client_id FROM tickets LEFT JOIN categories ON ticket_category = category_id WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $previous_ticket_category_name = escapeSql($row['category_name']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + // Get Category Name + $category_name = escapeSql(getFieldById('categories', $category_id, 'category_name')); + + // Update ticket + mysqli_query($mysqli, "UPDATE tickets SET ticket_category = '$category_id' WHERE ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name updated the category on ticket $ticket_prefix$ticket_number - $ticket_subject from $previous_category_name to $category_name", $client_id, $ticket_id); + + triggerCustomAction('ticket_update', $ticket_id); + } // End For Each Ticket ID Loop + + logAudit("Ticket", " Bulk Edit", "$session_name updated the category to $category_name on $ticket_count"); + + flashAlert("Category set to $category_name for $ticket_count Tickets"); + } + + redirect(); + +} + +if (isset($_POST['bulk_merge_tickets'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $merge_into_ticket_id = intval($_POST['merge_into_ticket_id']); // Parent ticket id + $merge_comment = escapeSql($_POST['merge_comment']); // Merge comment + $ticket_reply_type = 'Internal'; // Default all replies to internal + + // NEW PARENT ticket details + // Get merge into ticket id (as it may differ from the number) + $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_number FROM tickets WHERE ticket_id = $merge_into_ticket_id"); + if (mysqli_num_rows($sql) == 0) { + flashAlert("Cannot merge into that ticket.", 'error'); + redirect(); + } + $merge_row = mysqli_fetch_assoc($sql); + $merge_into_ticket_number = intval($merge_row['ticket_number']); // Parent ticket Number + + // Update & Close the selected tickets + if (isset($_POST['ticket_ids'])) { + + $ticket_count = count($_POST['ticket_ids']); // Get a ticket count + + foreach ($_POST['ticket_ids'] as $ticket_id) { + $ticket_id = intval($ticket_id); + + if ($ticket_id !== $merge_into_ticket_id) { + + $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); + $current_ticket_priority = escapeSql($row['ticket_priority']); + $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + // Update current ticket + if (empty($ticket_first_response_at)) { + mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); + } + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket $ticket_prefix$ticket_number bulk merged into $ticket_prefix$merge_into_ticket_number. Comment: $merge_comment', ticket_reply_time_worked = '00:01:00', ticket_reply_type = '$ticket_reply_type', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = '5', ticket_resolved_at = NOW(), ticket_closed_at = NOW(), ticket_closed_by = $session_user_id WHERE ticket_id = $ticket_id") or die(mysqli_error($mysqli)); + + // Update new parent ticket + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket $ticket_prefix$ticket_number was bulk merged into this ticket with comment: $merge_comment.

$ticket_subject
$ticket_details', ticket_reply_time_worked = '00:01:00', ticket_reply_type = 'Internal', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $merge_into_ticket_id"); + + logAudit("Ticket", "Merged", "$session_name Merged ticket $ticket_prefix$ticket_number into $ticket_prefix$merge_into_ticket_number", $client_id, $ticket_id); + + // Custom action/notif handler + triggerCustomAction('ticket_merge', $ticket_id); + + } + } // End For Each Ticket ID Loop + + mysqli_query($mysqli, "UPDATE tickets SET ticket_updated_at = NOW() WHERE ticket_id = $merge_into_ticket_id"); + + flashAlert("$ticket_count tickets merged into $ticket_prefix$merge_into_ticket_number"); + + } + + redirect(); + +} + +if (isset($_POST['bulk_resolve_tickets'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + // POST variables + $details = mysqli_escape_string($mysqli, $_POST['bulk_details']); + $ticket_reply_time_worked = escapeSql($_POST['time']); + $private_note = intval($_POST['bulk_private_note']); + if ($private_note == 1) { + $ticket_reply_type = 'Internal'; + } else { + $ticket_reply_type = 'Public'; + } + + // Resolve Selected Tickets + if (isset($_POST['ticket_ids'])) { + + // Intitialze the counts before the loop + $ticket_count = 0; + $skipped_count = 0; + + foreach ($_POST['ticket_ids'] as $ticket_id) { + $ticket_id = intval($ticket_id); + + // Check to make sure Tasks are complete before resolving + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('task_id') AS num FROM tasks WHERE task_completed_at IS NULL AND task_ticket_id = $ticket_id")); + $num_of_open_tasks = $row['num']; + + if ($num_of_open_tasks == 0) { + // Count the Ticket Loop + $ticket_count++; + + $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $current_ticket_priority = escapeSql($row['ticket_priority']); + $url_key = escapeSql($row['ticket_url_key']); + $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + // Mark FR time if required + if (empty($ticket_first_response_at)) { + mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); + } + + // Update ticket & insert reply + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 4, ticket_resolved_at = NOW() WHERE ticket_id = $ticket_id"); + + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$details', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '$ticket_reply_time_worked', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + logAudit("Ticket", "Resolve", "$session_name resolved $ticket_prefix$ticket_number - $ticket_subject", $client_id, $ticket_id); + + triggerCustomAction('ticket_resolve', $ticket_id); + + // Client notification email + if ((!empty($config_smtp_provider)) && $config_ticket_client_general_notifications == 1 && $private_note == 0) { + + // Get Contact details + $ticket_sql = mysqli_query($mysqli, "SELECT contact_name, contact_email FROM tickets + LEFT JOIN contacts ON ticket_contact_id = contact_id + WHERE ticket_id = $ticket_id + "); + $row = mysqli_fetch_assoc($ticket_sql); + + $contact_name = escapeSql($row['contact_name']); + $contact_email = escapeSql($row['contact_email']); + + // Sanitize Config vars from get_settings.php + $from_name = escapeSql($config_ticket_from_name); + $from_email = escapeSql($config_ticket_from_email); + $base_url = escapeSql($config_base_url); + + // Get Company Info + $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); + $row = mysqli_fetch_assoc($sql); + $company_name = escapeSql($row['company_name']); + $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); + + // EMAIL + $subject = "Ticket resolved - [$ticket_prefix$ticket_number] - $ticket_subject | (pending closure)"; + $body = "##- Please type your reply above this line -##

Hello $contact_name,

Your ticket regarding \"$ticket_subject\" has been marked as solved and is pending closure.

$details

If your request/issue is resolved, you can simply ignore this email. If you need further assistance, please reply or re-open to let us know!

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Portal: https://$base_url/client/ticket.php?id=$ticket_id

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + + // Check email valid + if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { + + $data = []; + + // Email Ticket Contact + // Queue Mail + + $data[] = [ + 'from' => $from_email, + 'from_name' => $from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body + ]; + } + + // Also Email all the watchers + $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); + $body .= "

----------------------------------------
YOU ARE A COLLABORATOR ON THIS TICKET"; + while ($row = mysqli_fetch_assoc($sql_watchers)) { + $watcher_email = escapeSql($row['watcher_email']); + + // Queue Mail + $data[] = [ + 'from' => $from_email, + 'from_name' => $from_name, + 'recipient' => $watcher_email, + 'recipient_name' => $watcher_email, + 'subject' => $subject, + 'body' => $body + ]; + } + addToMailQueue($data); + } // End Mail IF + } else { + $skipped_count++; + } // End Task Check + } // End Loop + } // End Array Empty Check + + flashAlert("Resolved $ticket_count Tickets"); + + if ($skipped_count > 0) { + flashAlert("Resolved $ticket_count Tickets $skipped_count ticket(s) could not be resolved because they have open tasks.", 'info'); + } + + redirect(); + +} + +if (isset($_POST['bulk_ticket_reply'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + // POST variables + $ticket_reply = mysqli_escape_string($mysqli, $_POST['bulk_reply_details']); + $ticket_status = intval($_POST['bulk_status']); + $ticket_reply_time_worked = escapeSql($_POST['time']); + $private_note = intval($_POST['bulk_private_reply']); + if ($private_note == 1) { + $ticket_reply_type = 'Internal'; + } else { + $ticket_reply_type = 'Public'; + } + + // Loop Through Tickets and Add Reply along with Email notifications + if (isset($_POST['ticket_ids'])) { + + // Get a Ticket Count + $ticket_count = count($_POST['ticket_ids']); + + foreach ($_POST['ticket_ids'] as $ticket_id) { + $ticket_id = intval($ticket_id); + + $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $current_ticket_priority = escapeSql($row['ticket_priority']); + $url_key = escapeSql($row['ticket_url_key']); + $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + if ($client_id) { + $client_uri = "&client_id=$client_id"; + } else { + $client_uri = ''; + } + + // Mark FR time if required + if (empty($ticket_first_response_at)) { + mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); + } + + // Add reply + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_time_worked = '$ticket_reply_time_worked', ticket_reply_type = '$ticket_reply_type', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + $ticket_reply_id = mysqli_insert_id($mysqli); + + // Update Ticket Status + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = '$ticket_status' WHERE ticket_id = $ticket_id"); + + logAudit("Ticket", "Reply", "$session_name replied to ticket $ticket_prefix$ticket_number - $ticket_subject and was a $ticket_reply_type reply", $client_id, $ticket_id); + + // Custom action/notif handler + if ($ticket_reply_type == 'Internal') { + triggerCustomAction('ticket_reply_agent_internal', $ticket_id); + } else { + triggerCustomAction('reply_reply_agent_public', $ticket_id); + } + + // Resolve the ticket, if set + if ($ticket_status == 4) { + mysqli_query($mysqli, "UPDATE tickets SET ticket_resolved_at = NOW() WHERE ticket_id = $ticket_id"); + + // Logging + logAudit("Ticket", "Resolved", "$session_name resolved Ticket $ticket_prefix$ticket_number", $client_id, $ticket_id); + + triggerCustomAction('ticket_resolve', $ticket_id); + } + + // Get Contact Details + $sql = mysqli_query( + $mysqli, + "SELECT contact_name, contact_email, ticket_created_by, ticket_assigned_to + FROM tickets + LEFT JOIN contacts ON ticket_contact_id = contact_id + WHERE ticket_id = $ticket_id" + ); + + $row = mysqli_fetch_assoc($sql); + + $contact_name = escapeSql($row['contact_name']); + $contact_email = escapeSql($row['contact_email']); + $ticket_created_by = intval($row['ticket_created_by']); + $ticket_assigned_to = intval($row['ticket_assigned_to']); + + // Sanitize Config vars from get_settings.php + $from_name = escapeSql($config_ticket_from_name); + $from_email = escapeSql($config_ticket_from_email); + $base_url = escapeSql($config_base_url); + + $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); + $row = mysqli_fetch_assoc($sql); + $company_name = escapeSql($row['company_name']); + $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); + + // Send e-mail to client if public update & email is set up + if ($private_note == 0 && (!empty($config_smtp_provider))) { + + $subject = "Ticket update - [$ticket_prefix$ticket_number] - $ticket_subject"; + $body = "##- Please type your reply above this line -##

Hello $contact_name,

Your ticket regarding $ticket_subject has been updated.

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

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status_name
Portal: View ticket

--
$company_name - Support
$from_email
$company_phone"; + + if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { + + $data = []; + + // Email Ticket Contact + // Queue Mail + $data[] = [ + 'from' => $from_email, + 'from_name' => $from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body + ]; + + } + + // Also Email all the watchers + $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); + $body .= "

----------------------------------------
YOU ARE A COLLABORATOR ON THIS TICKET"; + while ($row = mysqli_fetch_assoc($sql_watchers)) { + $watcher_email = escapeSql($row['watcher_email']); + + // Queue Mail + $data[] = [ + 'from' => $from_email, + 'from_name' => $from_name, + 'recipient' => $watcher_email, + 'recipient_name' => $watcher_email, + 'subject' => $subject, + 'body' => $body + ]; + } + addToMailQueue($data); + } //End Mail IF + + // Notification for assigned ticket user + if ($session_user_id != $ticket_assigned_to && $ticket_assigned_to != 0) { + + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$session_name updated Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject that is assigned to you', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $ticket_assigned_to"); + } + + // Notification for user that opened the ticket + if ($session_user_id != $ticket_created_by && $ticket_created_by != 0) { + + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$session_name updated Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject that you opened', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $ticket_created_by"); + } + } // End Ticket Lopp + + } + + flashAlert("Updated $ticket_count tickets"); + + redirect(); + +} + + +// Currently not UI Frontend for this +if (isset($_POST['bulk_add_ticket_project'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + // POST variables + $project_id = intval($_POST['project_id']); + + // Get Project Name + $sql = mysqli_query($mysqli, "SELECT project_name FROM projects WHERE project_id = $project_id"); + $row = mysqli_fetch_assoc($sql); + $project_name = escapeSql($row['project_name']); + + // Assign Project to Selected Tickets + if (isset($_POST['ticket_ids'])) { + + // Get a Ticket Count + $ticket_count = count($_POST['ticket_ids']); + + foreach ($_POST['ticket_ids'] as $ticket_id) { + $ticket_id = intval($ticket_id); + + $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $current_ticket_priority = escapeSql($row['ticket_priority']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + // Update ticket & insert reply + mysqli_query($mysqli, "UPDATE tickets SET ticket_project_id = $project_id WHERE ticket_id = $ticket_id"); + + logAudit("Ticket", "Reply", "$session_name added ticket $ticket_prefix$ticket_number - $ticket_subject to project $project_name", $client_id, $ticket_id); + + + } // End For Each Ticket ID Loop + + flashAlert("$ticket_count Tickets added to Project $project_name"); + + } + + redirect(); + +} + +if (isset($_POST['bulk_add_asset_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $assigned_to = intval($_POST['bulk_assigned_to']); + if ($assigned_to == 0) { + $ticket_status = 1; + } else { + $ticket_status = 2; + } + $subject = escapeSql($_POST['bulk_subject']); + $priority = escapeSql($_POST['bulk_priority']); + $category_id = intval($_POST['bulk_category']); + $details = mysqli_real_escape_string($mysqli, $_POST['bulk_details']); + $project_id = intval($_POST['bulk_project']); + $use_primary_contact = intval($_POST['use_primary_contact']); + $ticket_template_id = intval($_POST['bulk_ticket_template_id']); + $billable = intval($_POST['bulk_billable'] ?? 0); + + // 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_assoc($sql); + + // Override Template Subject + if(empty($subject)) { + $subject = escapeSql($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"); + + } + + // Create ticket for each selected asset + if (isset($_POST['asset_ids'])) { + + // Get a Asset Count + $asset_count = count($_POST['asset_ids']); + + foreach ($_POST['asset_ids'] as $asset_id) { + $asset_id = intval($asset_id); + + $sql = mysqli_query($mysqli, "SELECT * FROM assets WHERE asset_id = $asset_id"); + $row = mysqli_fetch_assoc($sql); + + $asset_name = escapeSql($row['asset_name']); + $client_id = intval($row['asset_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + $subject_asset_prepended = "$asset_name - $subject"; + + // Atomically increment and get the new ticket number + mysqli_query($mysqli, " + UPDATE settings + SET + config_ticket_next_number = LAST_INSERT_ID(config_ticket_next_number), + config_ticket_next_number = config_ticket_next_number + 1 + WHERE company_id = 1 + "); + + $ticket_number = mysqli_insert_id($mysqli); + + // Sanitize Config Vars from get_settings.php and Session Vars from check_login.php + $config_ticket_prefix = escapeSql($config_ticket_prefix); + $config_ticket_from_name = escapeSql($config_ticket_from_name); + $config_ticket_from_email = escapeSql($config_ticket_from_email); + $config_base_url = escapeSql($config_base_url); + + //Generate a unique URL key for clients to access + $url_key = randomString(32); + + mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$config_ticket_prefix', ticket_number = $ticket_number, ticket_category = $category_id, ticket_subject = '$subject_asset_prepended', ticket_details = '$details', ticket_priority = '$priority', ticket_billable = $billable, ticket_status = $ticket_status, ticket_asset_id = $asset_id, ticket_created_by = $session_user_id, ticket_assigned_to = $assigned_to, ticket_url_key = '$url_key', ticket_client_id = $client_id, ticket_project_id = $project_id"); + + $ticket_id = mysqli_insert_id($mysqli); + + // Add Tasks + if (!empty($_POST['tasks'])) { + foreach ($_POST['tasks'] as $task) { + $task_name = escapeSql($task); + // Check that task_name is not-empty (For some reason the !empty on the array doesnt work here like in watchers) + if (!empty($task_name)) { + mysqli_query($mysqli,"INSERT INTO tasks SET task_name = '$task_name', task_ticket_id = $ticket_id"); + } + } + } + + // Add Tasks from Template if Template was selected + if($ticket_template_id) { + if (mysqli_num_rows($sql_task_templates) > 0) { + while ($row = mysqli_fetch_assoc($sql_task_templates)) { + $task_order = intval($row['task_template_order']); + $task_name = escapeSql($row['task_template_name']); + + mysqli_query($mysqli,"INSERT INTO tasks SET task_name = '$task_name', task_order = $task_order, task_ticket_id = $ticket_id"); + } + } + } + + // Custom action/notif handler + triggerCustomAction('ticket_create', $ticket_id); + } + + logAudit("Ticket", "Bulk Create", "$session_name created $asset_count tickets for $asset_count"); + + flashAlert("You created $asset_count tickets for the selected assets"); + + } + + redirect(); + +} + +if (isset($_POST['add_ticket_reply'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); + $ticket_reply = $_POST['ticket_reply']; // Reply is SQL escaped below + $ticket_status = intval($_POST['status']); + + $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + // Time tracking, inputs & combine into string + $hours = intval($_POST['hours']); + $minutes = intval($_POST['minutes']); + $seconds = intval($_POST['seconds']); + $ticket_reply_time_worked = escapeSql(sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds)); + + // Defaults + $send_email = 0; + $ticket_reply_id = 0; + if ($_POST['public_reply_type'] == 1 ){ + $ticket_reply_type = 'Public'; + } elseif ($_POST['public_reply_type'] == 2 ) { + $ticket_reply_type = 'Public'; + $send_email = 1; + } else { + $ticket_reply_type = 'Internal'; + } + // Add Signature to the end of the ticket reply if not Internal and if there is reply + if ($ticket_reply !== '' && $ticket_reply_type !== 'Internal' && $send_email == 1) { + $ticket_reply .= getFieldById('user_settings',$session_user_id,'user_config_signature', 'raw'); + } + + $ticket_reply = mysqli_escape_string($mysqli, $ticket_reply); // SQL Escape Ticket Reply + + // Update Ticket Status & updated at (in case status didn't change) + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = $ticket_status, ticket_updated_at = NOW() WHERE ticket_id = $ticket_id"); + + // Resolve the ticket, if set + if ($ticket_status == 4) { + mysqli_query($mysqli, "UPDATE tickets SET ticket_resolved_at = NOW() WHERE ticket_id = $ticket_id"); + + logAudit("Ticket", "Resolved", "$session_name resolved Ticket ticket ID $ticket_id", $client_id, $ticket_id); + } + + // Process reply actions, if we have a reply to work with (e.g. we're not just editing the status) + if (!empty($ticket_reply)) { + + // Add reply + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_time_worked = '$ticket_reply_time_worked', ticket_reply_type = '$ticket_reply_type', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + $ticket_reply_id = mysqli_insert_id($mysqli); + + // Get Ticket Details + $ticket_sql = mysqli_query($mysqli, "SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_subject, ticket_status, ticket_status_name, ticket_url_key, ticket_first_response_at, ticket_created_by, ticket_assigned_to, ticket_client_id + FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + WHERE ticket_id = $ticket_id + "); + + $row = mysqli_fetch_assoc($ticket_sql); + + $contact_name = escapeSql($row['contact_name']); + $contact_email = escapeSql($row['contact_email']); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $ticket_status = intval($row['ticket_status']); + $ticket_status_name = escapeSql($row['ticket_status_name']); + $url_key = escapeSql($row['ticket_url_key']); + $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); + $ticket_created_by = intval($row['ticket_created_by']); + $ticket_assigned_to = intval($row['ticket_assigned_to']); + $client_id = intval($row['ticket_client_id']); + + if ($client_id) { + $client_uri = "&client_id=$client_id"; + } else { + $client_uri = ''; + } + + // Sanitize Config vars from get_settings.php + $config_ticket_from_name = escapeSql($config_ticket_from_name); + $config_ticket_from_email = escapeSql($config_ticket_from_email); + $config_base_url = escapeSql($config_base_url); + + $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); + $row = mysqli_fetch_assoc($sql); + $company_name = escapeSql($row['company_name']); + $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); + + // Send e-mail to client if public update & email is set up + if ($ticket_reply_type == 'Public' && $send_email == 1 && (!empty($config_smtp_provider))) { + + // Slightly different email subject/text depending on if this update set auto-close + + if ($ticket_status == 4) { + // Resolved + $subject = "Ticket resolved - [$ticket_prefix$ticket_number] - $ticket_subject | (pending closure)"; + $body = "##- Please type your reply above this line -##

Hello $contact_name,

Your ticket regarding $ticket_subject has been marked as solved and is pending closure.

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

If your request/issue is resolved, you can simply ignore this email. If you need further assistance, please reply or re-open to let us know!

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status_name
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + } else { + // Anything else + $subject = "Ticket update - [$ticket_prefix$ticket_number] - $ticket_subject"; + $body = "##- Please type your reply above this line -##

Hello $contact_name,

Your ticket regarding $ticket_subject has been updated.

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

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status_name
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + } + + if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { + + $data = []; + + // Email Ticket Contact + // Queue Mail + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body + ]; + } + + // Also Email all the watchers + $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); + $body .= "

----------------------------------------
YOU ARE A COLLABORATOR ON THIS TICKET"; + while ($row = mysqli_fetch_assoc($sql_watchers)) { + $watcher_email = escapeSql($row['watcher_email']); + + // Queue Mail + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $watcher_email, + 'recipient_name' => $watcher_email, + 'subject' => $subject, + 'body' => $body + ]; + } + addToMailQueue($data); + + } + //End Mail IF + + // Notification for assigned ticket user + if ($session_user_id != $ticket_assigned_to && $ticket_assigned_to != 0) { + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$session_name updated Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject that is assigned to you', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $ticket_assigned_to"); + } + + // Notification for user that opened the ticket + if ($session_user_id != $ticket_created_by && $ticket_created_by != 0) { + mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = 'Ticket', notification = '$session_name updated Ticket $ticket_prefix$ticket_number - Subject: $ticket_subject that you opened', notification_action = '/agent/ticket.php?ticket_id=$ticket_id$client_uri', notification_client_id = $client_id, notification_user_id = $ticket_created_by"); + } + + // Handle first response + if (empty($ticket_first_response_at) && $ticket_reply_type == 'Public') { + mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); + } + + // Custom action/notif handler + if ($ticket_reply_type == 'Internal') { + triggerCustomAction('ticket_reply_agent_internal', $ticket_id); + } else { + triggerCustomAction('reply_reply_agent_public', $ticket_id); + } + + flashAlert("Ticket $ticket_prefix$ticket_number has been updated with your reply and was $ticket_reply_type"); + + } else { + flashAlert("Ticket updated"); + } + + logAudit("Ticket", "Reply", "$session_name replied to ticket $ticket_prefix$ticket_number - $ticket_subject and was a $ticket_reply_type reply", $client_id, $ticket_id); + + redirect(); + +} + +if (isset($_POST['edit_ticket_reply'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_reply_id = intval($_POST['ticket_reply_id']); + $ticket_reply = mysqli_real_escape_string($mysqli, $_POST['ticket_reply']); + $ticket_reply_type = escapeSql($_POST['ticket_reply_type']); + $ticket_reply_time_worked = escapeSql($_POST['time']); + + $sql = mysqli_query($mysqli, "SELECT ticket_client_id FROM ticket_replies + LEFT JOIN tickets ON ticket_id = ticket_reply_ticket_id + WHERE ticket_reply_id = $ticket_reply_id + LIMIT 1" + ); + + $row = mysqli_fetch_assoc($sql); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply = '$ticket_reply', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '$ticket_reply_time_worked' WHERE ticket_reply_id = $ticket_reply_id AND ticket_reply_type != 'Client'") or die(mysqli_error($mysqli)); + + logAudit("Ticket", "Reply", "$session_name edited ticket_reply", $client_id, $ticket_reply_id); + + flashAlert("Ticket reply updated"); + + redirect(); + +} + +if (isset($_POST['redact_ticket_reply'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_reply_id = intval($_POST['ticket_reply_id']); + $ticket_reply = mysqli_real_escape_string($mysqli, $_POST['ticket_reply']); + + $sql = mysqli_query($mysqli, "SELECT ticket_client_id FROM ticket_replies + LEFT JOIN tickets ON ticket_id = ticket_reply_ticket_id + WHERE ticket_reply_id = $ticket_reply_id + LIMIT 1" + ); + + $row = mysqli_fetch_assoc($sql); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply = '$ticket_reply' WHERE ticket_reply_id = $ticket_reply_id"); + + logAudit("Ticket", "Reply", "$session_name redacted ticket_reply", $client_id, $ticket_reply_id); + + flashAlert("Ticket reply redacted"); + + redirect(); + +} + +if (isset($_GET['archive_ticket_reply'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_reply_id = intval($_GET['archive_ticket_reply']); + + $ticket_id = intval(getFieldById('ticket_replies', $ticket_reply_id, 'ticket_reply_ticket_id')); + $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply_archived_at = NOW() WHERE ticket_reply_id = $ticket_reply_id"); + + logAudit("Ticket Reply", "Archive", "$session_name archived ticket_reply", $client_id, $ticket_reply_id); + + flashAlert("Ticket reply archived", 'error'); + + redirect(); + +} + +if (isset($_POST['merge_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); // Child ticket ID to be closed + $merge_into_ticket_id = intval($_POST['merge_into_ticket_id']); // Parent ticket id + $merge_comment = escapeSql($_POST['merge_comment']); // Merge comment + $move_replies = intval($_POST['merge_move_replies']); // Whether to move replies to the new parent ticket + $ticket_reply_type = 'Internal'; // Default all replies to internal + + // Get current ticket details + $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject, ticket_details FROM tickets WHERE ticket_id = $ticket_id"); + if (mysqli_num_rows($sql) == 0) { + flashAlert("No ticket with that ID found.", 'error'); + redirect(); + } + // CURRENT ticket details + $row = mysqli_fetch_assoc($sql); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $ticket_details = mysqli_escape_string($mysqli, $row['ticket_details']); + $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); + + // NEW PARENT ticket details + // Get merge into ticket id (as it may differ from the number) + $sql = mysqli_query($mysqli, "SELECT ticket_id, ticket_number, ticket_client_id FROM tickets WHERE ticket_id = $merge_into_ticket_id"); + if (mysqli_num_rows($sql) == 0) { + flashAlert("Cannot merge into that ticket.", 'error'); + redirect(); + } + $merge_row = mysqli_fetch_assoc($sql); + $client_id = intval($merge_row['ticket_client_id']); + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + $merge_into_ticket_number = intval($merge_row['ticket_number']); + if ($client_id) { + $has_client = "&client_id=$client_id"; + } else { + $has_client = ""; + } + // Sanity check + if ($ticket_id == $merge_into_ticket_id) { + flashAlert("Cannot merge into the same ticket.", 'error'); + redirect(); + } + + // Move ticket replies from child > parent + if ($move_replies) { + mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply_ticket_id = $merge_into_ticket_id WHERE ticket_reply_ticket_id = $ticket_id"); + } + + // Update current ticket + if (empty($ticket_first_response_at)) { + mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); + } + + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket $ticket_prefix$ticket_number merged into $ticket_prefix$merge_into_ticket_number. Comment: $merge_comment', ticket_reply_time_worked = '00:01:00', ticket_reply_type = '$ticket_reply_type', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = '5', ticket_resolved_at = NOW(), ticket_closed_at = NOW(), ticket_closed_by = $session_user_id WHERE ticket_id = $ticket_id") or die(mysqli_error($mysqli)); + + //Update new parent ticket + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket $ticket_prefix$ticket_number was merged into this ticket with comment: $merge_comment.

$ticket_subject
$ticket_details', ticket_reply_time_worked = '00:01:00', ticket_reply_type = '$ticket_reply_type', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $merge_into_ticket_id"); + + mysqli_query($mysqli, "UPDATE tickets SET ticket_updated_at = NOW() WHERE ticket_id = $merge_into_ticket_id"); + + logAudit("Ticket", "Merged", "$session_name Merged ticket $ticket_prefix$ticket_number into $ticket_prefix$merge_into_ticket_number"); + + triggerCustomAction('ticket_merge', $ticket_id); + + flashAlert("Ticket merged into $ticket_prefix$merge_into_ticket_number"); + + redirect("ticket.php?ticket_id=$merge_into_ticket_id$has_client"); + +} + +if (isset($_POST['change_client_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); + $client_id = intval($_POST['new_client_id']); + $contact_id = intval($_POST['new_contact_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + // Set any/all existing replies to internal + mysqli_query($mysqli, "UPDATE ticket_replies SET ticket_reply_type = 'Internal' WHERE ticket_reply_ticket_id = $ticket_id"); + + // Update ticket client & contact + mysqli_query($mysqli, "UPDATE tickets SET ticket_client_id = $client_id, ticket_contact_id = $contact_id WHERE ticket_id = $ticket_id LIMIT 1"); + + logAudit("Ticket", "Change", "$session_name changed ticket client", $client_id, $ticket_id); + + triggerCustomAction('ticket_update', $ticket_id); + + flashAlert("Ticket client updated"); + + redirect(); + +} + +if (isset($_GET['resolve_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_GET['resolve_ticket']); + + $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_first_response_at = escapeSql($row['ticket_first_response_at']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + // Mark FR + if (empty($ticket_first_response_at)) { + mysqli_query($mysqli, "UPDATE tickets SET ticket_first_response_at = NOW() WHERE ticket_id = $ticket_id"); + } + + // Resolve + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 4, ticket_resolved_at = NOW() WHERE ticket_id = $ticket_id"); + + logAudit("Ticket", "Resolved", "$session_name resolved ticket $ticket_prefix$ticket_number (ID: $ticket_id)", $client_id, $ticket_id); + + triggerCustomAction('ticket_resolve', $ticket_id); + + // Client notification email + if ((!empty($config_smtp_provider)) && $config_ticket_client_general_notifications == 1) { + + // Get details + $ticket_sql = mysqli_query($mysqli, "SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_subject, ticket_status_name, ticket_assigned_to, ticket_url_key FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + WHERE ticket_id = $ticket_id + "); + $row = mysqli_fetch_assoc($ticket_sql); + + $contact_name = escapeSql($row['contact_name']); + $contact_email = escapeSql($row['contact_email']); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $ticket_assigned_to = intval($row['ticket_assigned_to']); + $ticket_status = escapeSql($row['ticket_status_name']); + $url_key = escapeSql($row['ticket_url_key']); + + // Sanitize Config vars from get_settings.php + $config_ticket_from_name = escapeSql($config_ticket_from_name); + $config_ticket_from_email = escapeSql($config_ticket_from_email); + $config_base_url = escapeSql($config_base_url); + + // Get Company Info + $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); + $row = mysqli_fetch_assoc($sql); + $company_name = escapeSql($row['company_name']); + $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); + + // EMAIL + $subject = "Ticket resolved - [$ticket_prefix$ticket_number] - $ticket_subject | (pending closure)"; + $body = "##- Please type your reply above this line -##

Hello $contact_name,

Your ticket regarding $ticket_subject has been marked as solved and is pending closure.

If your request/issue is resolved, you can simply ignore this email. If you need further assistance, please reply or re-open to let us know!

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Status: $ticket_status
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + + // Check email valid + if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { + + $data = []; + + // Email Ticket Contact + // Queue Mail + + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body + ]; + } + + // Also Email all the watchers + $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); + $body .= "

----------------------------------------
YOU ARE A COLLABORATOR ON THIS TICKET"; + while ($row = mysqli_fetch_assoc($sql_watchers)) { + $watcher_email = escapeSql($row['watcher_email']); + + // Queue Mail + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $watcher_email, + 'recipient_name' => $watcher_email, + 'subject' => $subject, + 'body' => $body + ]; + } + addToMailQueue($data); + } + //End Mail IF + + flashAlert("Ticket resolved"); + + redirect(); + +} + +if (isset($_GET['close_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_GET['close_ticket']); + $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 5, ticket_closed_at = NOW(), ticket_closed_by = $session_user_id WHERE ticket_id = $ticket_id") or die(mysqli_error($mysqli)); + + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Ticket closed.', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + logAudit("Ticket", "Closed", "$session_name closed ticket ID $ticket_id", $client_id, $ticket_id); + + triggerCustomAction('ticket_close', $ticket_id); + + // Client notification email + if ((!empty($config_smtp_provider)) && $config_ticket_client_general_notifications == 1) { + + // Get details + $ticket_sql = mysqli_query($mysqli, "SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_subject, ticket_url_key FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + WHERE ticket_id = $ticket_id + "); + $row = mysqli_fetch_assoc($ticket_sql); + + $contact_name = escapeSql($row['contact_name']); + $contact_email = escapeSql($row['contact_email']); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $url_key = escapeSql($row['ticket_url_key']); + + // Sanitize Config vars from get_settings.php + $config_ticket_from_name = escapeSql($config_ticket_from_name); + $config_ticket_from_email = escapeSql($config_ticket_from_email); + $config_base_url = escapeSql($config_base_url); + + // Get Company Info + $sql = mysqli_query($mysqli, "SELECT company_name, company_phone, company_phone_country_code FROM companies WHERE company_id = 1"); + $row = mysqli_fetch_assoc($sql); + $company_name = escapeSql($row['company_name']); + $company_phone = escapeSql(formatPhoneNumber($row['company_phone'], $row['company_phone_country_code'])); + + // EMAIL + $subject = "Ticket closed - [$ticket_prefix$ticket_number] - $ticket_subject | (do not reply)"; + $body = "Hello $contact_name,

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

We hope the request/issue was resolved to your satisfaction, please provide your feedback here.
If you need further assistance, please raise a new ticket using the below details. Please do not reply to this email.

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Portal: https://$config_base_url/client/ticket.php?id=$ticket_id

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + + // Check email valid + if (filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { + + $data = []; + + // Email Ticket Contact + // Queue Mail + + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body + ]; + } + + // Also Email all the watchers + $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); + $body .= "

----------------------------------------
YOU ARE A COLLABORATOR ON THIS TICKET"; + while ($row = mysqli_fetch_assoc($sql_watchers)) { + $watcher_email = escapeSql($row['watcher_email']); + + // Queue Mail + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $watcher_email, + 'recipient_name' => $watcher_email, + 'subject' => $subject, + 'body' => $body + ]; + } + addToMailQueue($data); + } + //End Mail IF + + flashAlert("Ticket Closed, this cannot not be reopened but you may start another one"); + + redirect(); + +} + +if (isset($_GET['reopen_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_GET['reopen_ticket']); + + $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 2, ticket_resolved_at = NULL WHERE ticket_id = $ticket_id"); + + logAudit("Ticket", "Reopened", "$session_name reopened ticket ID $ticket_id", $client_id, $ticket_id); + + triggerCustomAction('ticket_update', $ticket_id); + + flashAlert("Ticket re-opened"); + + redirect(); + +} + +if (isset($_POST['add_invoice_from_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + enforceUserPermission('module_sales', 2); + + $invoice_id = intval($_POST['invoice_id']); + $ticket_id = intval($_POST['ticket_id']); + $date = escapeSql($_POST['date']); + $category = intval($_POST['category']); + $scope = escapeSql($_POST['scope']); + + $sql = mysqli_query( + $mysqli, + "SELECT * FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + LEFT JOIN assets ON ticket_asset_id = asset_id + LEFT JOIN locations ON ticket_location_id = location_id + WHERE ticket_id = $ticket_id" + ); + + $row = mysqli_fetch_assoc($sql); + $client_id = intval($row['client_id']); + $client_net_terms = intval($row['client_net_terms']); + if ($client_net_terms == 0) { + $client_net_terms = $config_default_net_terms; + } + + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_category = escapeSql($row['ticket_category']); + $ticket_subject = escapeSql($row['ticket_subject']); + $ticket_created_at = escapeSql($row['ticket_created_at']); + $ticket_updated_at = escapeSql($row['ticket_updated_at']); + $ticket_closed_at = escapeSql($row['ticket_closed_at']); + + $contact_id = intval($row['contact_id']); + $contact_name = escapeSql($row['contact_name']); + $contact_email = escapeSql($row['contact_email']); + + $asset_id = intval($row['asset_id']); + + $location_name = escapeSql($row['location_name']); + + enforceClientAccess(); + + if ($invoice_id == 0) { + + $invoice_prefix = escapeSql($config_invoice_prefix); + + // Atomically increment and get the new invoice number + mysqli_query($mysqli, " + UPDATE settings + SET + config_invoice_next_number = LAST_INSERT_ID(config_invoice_next_number), + config_invoice_next_number = config_invoice_next_number + 1 + WHERE company_id = 1 + "); + + $invoice_number = mysqli_insert_id($mysqli); + + //Generate a unique URL key for clients to access + $url_key = randomString(32); + + mysqli_query($mysqli, "INSERT INTO invoices SET invoice_prefix = '$config_invoice_prefix', invoice_number = $invoice_number, invoice_scope = '$scope', invoice_date = '$date', invoice_due = DATE_ADD('$date', INTERVAL $client_net_terms day), invoice_currency_code = '$session_company_currency', invoice_category_id = $category, invoice_status = 'Draft', invoice_url_key = '$url_key', invoice_client_id = $client_id"); + $invoice_id = mysqli_insert_id($mysqli); + } else { + $sql_invoice = mysqli_query($mysqli, "SELECT invoice_prefix, invoice_number FROM invoices WHERE invoice_id = $invoice_id"); + $row = mysqli_fetch_assoc($sql_invoice); + $invoice_prefix = escapeSql($row['invoice_prefix']); + $invoice_number = intval($row['invoice_number']); + } + + //Add Item + $item_name = escapeSql($_POST['item_name']); + $item_description = escapeSql($_POST['item_description']); + $qty = floatval($_POST['qty']); + $price = floatval($_POST['price']); + $tax_id = intval($_POST['tax_id']); + + $subtotal = $price * $qty; + + if ($tax_id > 0) { + $sql = mysqli_query($mysqli, "SELECT * FROM taxes WHERE tax_id = $tax_id"); + $row = mysqli_fetch_assoc($sql); + $tax_percent = floatval($row['tax_percent']); + $tax_amount = $subtotal * $tax_percent / 100; + } else { + $tax_amount = 0; + } + + $total = $subtotal + $tax_amount; + + mysqli_query($mysqli, "INSERT INTO invoice_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_order = 1, item_tax_id = $tax_id, item_invoice_id = $invoice_id"); + + //Update Invoice Balances + + $sql = mysqli_query($mysqli, "SELECT * FROM invoices WHERE invoice_id = $invoice_id"); + $row = mysqli_fetch_assoc($sql); + + $new_invoice_amount = floatval($row['invoice_amount']) + $total; + + mysqli_query($mysqli, "UPDATE invoices SET invoice_amount = $new_invoice_amount WHERE invoice_id = $invoice_id"); + + mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Draft', history_description = 'Invoice created from Ticket $ticket_prefix$ticket_number', history_invoice_id = $invoice_id"); + + // Add internal note to ticket, and link to invoice in database + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Created invoice $config_invoice_prefix$invoice_number for this ticket.', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + mysqli_query($mysqli, "UPDATE tickets SET ticket_invoice_id = $invoice_id WHERE ticket_id = $ticket_id"); + + logAudit("Invoice", "Create", "$session_name created invoice $invoice_prefix$invoice_number from Ticket $ticket_prefix$ticket_number", $client_id, $invoice_id); + + flashAlert("Invoice $invoice_prefix$invoice_number created from ticket"); + + redirect("invoice.php?invoice_id=$invoice_id"); + +} + +if (isset($_POST['add_quote_from_ticket'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + enforceUserPermission('module_sales', 2); + + require_once 'quote_model.php'; + + $ticket_id = intval($_POST['ticket_id']); + $item_name = escapeSql($_POST['item_name']); + $item_description = escapeSql($_POST['item_description']); + $qty = floatval($_POST['qty']); + $price = floatval($_POST['price']); + $tax_id = intval($_POST['tax_id']); + + // Totals + $subtotal = $price * $qty; + $tax_amount = 0; + if ($tax_id > 0) { + $sql = mysqli_query($mysqli, "SELECT * FROM taxes WHERE tax_id = $tax_id"); + $row = mysqli_fetch_assoc($sql); + $tax_percent = floatval($row['tax_percent']); + $tax_amount = $subtotal * $tax_percent / 100; + } + $total = floatval($subtotal + $tax_amount); + + // Ticket info + $sql = mysqli_query( + $mysqli, + "SELECT ticket_prefix, ticket_number, ticket_client_id FROM tickets WHERE ticket_id = $ticket_id LIMIT 1" + ); + $row = mysqli_fetch_assoc($sql); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $client_id = intval($row['ticket_client_id']); + + enforceClientAccess(); + + // Atomically increment and get the new quote number + mysqli_query($mysqli, " + UPDATE settings + SET + config_quote_next_number = LAST_INSERT_ID(config_quote_next_number), + config_quote_next_number = config_quote_next_number + 1 + WHERE company_id = 1 + "); + + $quote_number = mysqli_insert_id($mysqli); + + //Generate a unique URL key for clients to access + $quote_url_key = randomString(32); + + mysqli_query($mysqli,"INSERT INTO quotes SET quote_prefix = '$config_quote_prefix', quote_number = $quote_number, quote_scope = '$scope', quote_date = '$date', quote_expire = '$expire', quote_amount = $total, quote_currency_code = '$session_company_currency', quote_category_id = $category, quote_status = 'Draft', quote_url_key = '$quote_url_key', quote_client_id = $client_id"); + + $quote_id = mysqli_insert_id($mysqli); + + // Add line item + mysqli_query($mysqli, "INSERT INTO quote_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = $qty, item_price = $price, item_subtotal = $subtotal, item_tax = $tax_amount, item_total = $total, item_order = 1, item_tax_id = $tax_id, item_quote_id = $quote_id"); + + // Add internal note to ticket, and link to invoice in database + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = 'Created quote $config_quote_prefix$quote_number for this ticket.', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + mysqli_query($mysqli, "UPDATE tickets SET ticket_quote_id = $quote_id WHERE ticket_id = $ticket_id LIMIT 1"); + + // Logging + redirects + mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Draft', history_description = 'Quote created from Ticket $ticket_prefix$ticket_number!', history_quote_id = $quote_id"); + logAudit("Quote", "Create", "$session_name created quote $config_quote_prefix$quote_number from ticket $ticket_prefix$ticket_number", $client_id, $quote_id); + + triggerCustomAction('quote_create', $quote_id); + + flashAlert("Quote $config_quote_prefix$quote_number created"); + redirect("quote.php?quote_id=$quote_id"); + +} + +if (isset($_POST['export_tickets_csv'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + if ($_POST['client_id']) { + $client_id = intval($_POST['client_id']); + $client_query = "WHERE ticket_client_id = $client_id"; + $client_name = getFieldById('clients', $client_id, 'client_name'); + $file_name_prepend = "$client_name-"; + } else { + $client_query = ''; + $client_name = ''; + $file_name_prepend = "$session_company_name-"; + } + + $sql = mysqli_query( + $mysqli, + "SELECT * FROM tickets + LEFT JOIN ticket_statuses ON ticket_status = ticket_status_id + $client_query ORDER BY ticket_number ASC" + ); + + if ($sql->num_rows > 0) { + $delimiter = ","; + $enclosure = '"'; + $escape = '\\'; // backslash + $filename = sanitizeFilename($file_name_prepend . "Tickets-" . date('Y-m-d_H-i-s') . ".csv"); + + //create a file pointer + $f = fopen('php://memory', 'w'); + + //set column headers + $fields = array('Ticket Number', 'Priority', 'Status', 'Subject', 'Date Opened', 'Date Resolved', 'Date Closed'); + fputcsv($f, $fields, $delimiter, $enclosure, $escape); + + //output each row of the data, format line as csv and write to file pointer + while ($row = $sql->fetch_assoc()) { + $lineData = array($config_ticket_prefix . $row['ticket_number'], $row['ticket_priority'], $row['ticket_status_name'], $row['ticket_subject'], $row['ticket_created_at'], $row['ticket_resolved_at'], $row['ticket_closed_at']); + fputcsv($f, array_map('escapeCsvFormula', $lineData), $delimiter, $enclosure, $escape); + } + + //move back to beginning of file + fseek($f, 0); + + //set headers to download file rather than displayed + header('Content-Type: text/csv'); + header('Content-Disposition: attachment; filename="' . $filename . '";'); + + //output all remaining data on a file pointer + fpassthru($f); + } + exit; + +} + +if (isset($_POST['edit_ticket_billable_status'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + enforceUserPermission('module_sales', 2); + + $ticket_id = intval($_POST['ticket_id']); + $billable_status = intval($_POST['billable_status']); + if ($billable_status == 0 ) { + $billable_wording = "Not"; + } + + // Get ticket details for logging + $sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_client_id FROM tickets WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $client_id = intval($row['ticket_client_id']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli,"UPDATE tickets SET ticket_billable = $billable_status WHERE ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name marked ticket $ticket_prefix$ticket_number as $billable_wording Billable", $client_id, $ticket_id); + + flashAlert("Ticket marked $billable_wording Billable"); + + redirect(); + +} + +if (isset($_POST['edit_ticket_schedule'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_POST['ticket_id']); + $onsite = intval($_POST['onsite']); + $schedule = escapeSql($_POST['scheduled_date_time']); + $ticket_link = "client/ticket.php?id=$ticket_id"; + $full_ticket_url = "https://$config_base_url/client/ticket.php?id=$ticket_id"; + $ticket_link_html = "$ticket_link"; + + $client_id = intval(getFieldById('tickets', $ticket_id, 'ticket_client_id')); + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + mysqli_query($mysqli,"UPDATE tickets + SET ticket_schedule = '$schedule', ticket_onsite = $onsite + WHERE ticket_id = $ticket_id" + ); + + // Check for other conflicting scheduled items based on 2 hr window + //TODO make this configurable + $start = date('Y-m-d H:i:s', strtotime($schedule) - 7200); + $end = date('Y-m-d H:i:s', strtotime($schedule) + 7200); + $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_schedule BETWEEN '$start' AND '$end' AND ticket_id != $ticket_id"); + if (mysqli_num_rows($sql) > 0) { + $conflicting_tickets = []; + while ($row = mysqli_fetch_assoc($sql)) { + $conflicting_tickets[] = $row['ticket_id'] . " - " . $row['ticket_subject'] . " @ " . $row['ticket_schedule']; + } + } + $sql = mysqli_query($mysqli, "SELECT * FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + LEFT JOIN locations on contact_location_id = location_id + LEFT JOIN users ON ticket_assigned_to = user_id + WHERE ticket_id = $ticket_id + "); + + $row = mysqli_fetch_assoc($sql); + + $client_name = escapeSql($row['client_name']); + $ticket_details = escapeSql($row['ticket_details']); + $contact_name = escapeSql($row['contact_name']); + $contact_email = escapeSql($row['contact_email']); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $user_name = escapeSql($row['user_name']); + $user_email = escapeSql($row['user_email']); + $cal_subject = $ticket_number . ": " . $client_name . " - " . $ticket_subject; + $ticket_details_truncated = substr($ticket_details, 0, 100); + $cal_description = $ticket_details_truncated . " - " . $full_ticket_url; + $cal_location = escapeSql($row["location_address"]); + $email_datetime = date('l, F j, Y \a\t g:ia', strtotime($schedule)); + + if ($client_id) { + $client_uri = "&client_id=$client_id"; + } else { + $client_uri = ''; + } + + // Sanitize Config Vars + $config_ticket_from_email = escapeSql($config_ticket_from_email); + $config_ticket_from_name = escapeSql($config_ticket_from_name); + $session_company_name = escapeSql($session_company_name); + + + /// Create iCal event + $cal_str = createiCalStr($schedule, $cal_subject, $cal_description, $cal_location); + + // Notify the agent of the scheduled work + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $user_email, + 'recipient_name' => $user_name, + 'subject' => "Ticket Scheduled - [$ticket_prefix$ticket_number] - $ticket_subject", + 'body' => "Hello, " . $user_name . "

The ticket regarding $ticket_subject has been scheduled for $email_datetime.

--------------------------------
$ticket_link
--------------------------------

Please do not reply to this email.

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Portal: https://$config_base_url/agent/ticket.php?ticket_id=$ticket_id$client_uri

~
$session_company_name
Support Department
$config_ticket_from_email", + 'cal_str' => $cal_str + ]; + + if ($config_ticket_client_general_notifications) { + // Notify the ticket contact of the scheduled work + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => "Ticket Scheduled - [$ticket_prefix$ticket_number] - $ticket_subject", + 'body' => mysqli_escape_string($mysqli, "
+ Hello, $contact_name +
+ Your ticket regarding $ticket_subject has been scheduled for $email_datetime. +

+ Access your ticket here +

+ Please do not reply to this email. +

+ Ticket: $ticket_prefix$ticket_number
+ Subject: $ticket_subject
+

+ +
+ This is an automated message. Please do not reply directly to this email. +
"), + 'cal_str' => $cal_str + ]; + + // Notify the watchers of the scheduled work + $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); + + while ($row = mysqli_fetch_assoc($sql_watchers)) { + $watcher_email = escapeSql($row['watcher_email']); + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $watcher_email, + 'recipient_name' => $watcher_email, + 'subject' => "Ticket Scheduled - [$ticket_prefix$ticket_number] - $ticket_subject", + 'body' => mysqli_escape_string($mysqli, escapeHtml("
+ Hello, +
+ The ticket regarding $ticket_subject has been scheduled for $email_datetime. +

+ $ticket_link +

+ Please do not reply to this email. +

+ Ticket: $ticket_prefix$ticket_number
+ Subject: $ticket_subject
+ Portal: Access the ticket here +

+ +
+ This is an automated message. Please do not reply directly to this email. +
")), + 'cal_str' => $cal_str + ]; + } + } + + // Send + $response = addToMailQueue($data); + + // Update ticket reply + $ticket_reply_note = "Ticket scheduled for $email_datetime " . (boolval($onsite) ? '(onsite).' : '(remote).'); + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply_note', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name edited ticket schedule", $client_id, $ticket_id); + + triggerCustomAction('ticket_schedule', $ticket_id); + + if (empty($conflicting_tickets)) { + flashAlert("Ticket scheduled for $email_datetime"); + redirect(); + } else { + $_SESSION['alert_type'] = "error"; + flashAlert("Ticket scheduled for $email_datetime. Yet there are conflicting tickets scheduled for the same time:
" . implode(",
", $conflicting_tickets), 'error'); + redirect("calendar.php"); + } + +} + +if (isset($_GET['cancel_ticket_schedule'])) { + + validateCSRFToken(); + + enforceUserPermission('module_support', 2); + + $ticket_id = intval($_GET['cancel_ticket_schedule']); + + $sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_id = $ticket_id"); + $row = mysqli_fetch_assoc($sql); + + $client_id = intval($row['ticket_client_id']); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $ticket_schedule = escapeSql($row['ticket_schedule']); + $ticket_cal_str = escapeSql($row['ticket_cal_str']); + + // Don't Enforce Client Access if Ticket doesn't have an assigned client + if ($client_id) { + enforceClientAccess(); + } + + if ($client_id) { + $client_uri = "&client_id=$client_id"; + } else { + $client_uri = ''; + } + + mysqli_query($mysqli, "UPDATE tickets SET ticket_schedule = NULL WHERE ticket_id = $ticket_id"); + + // Sanitize Config Vars + $config_ticket_from_email = escapeSql($config_ticket_from_email); + $config_ticket_from_name = escapeSql($config_ticket_from_name); + $session_company_name = escapeSql($session_company_name); + + //Create iCal event + $cal_str = createiCalStrCancel($ticket_cal_str); + + //Send emails + + $sql = mysqli_query($mysqli, "SELECT * FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + LEFT JOIN locations on contact_location_id = location_id + LEFT JOIN users ON ticket_assigned_to = user_id + WHERE ticket_id = $ticket_id + "); + $row = mysqli_fetch_assoc($sql); + + $client_id = intval($row['ticket_client_id']); + $client_name = escapeSql($row['client_name']); + $ticket_details = escapeSql($row['ticket_details']); + $contact_name = escapeSql($row['contact_name']); + $contact_email = escapeSql($row['contact_email']); + $ticket_prefix = escapeSql($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = escapeSql($row['ticket_subject']); + $user_name = escapeSql($row['user_name']); + $user_email = escapeSql($row['user_email']); + + // Notify the agent of the cancellation + $data[] = [ + // User Email + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $user_email, + 'recipient_name' => $user_name, + 'subject' => "Ticket Schedule Cancelled - [$ticket_prefix$ticket_number] - $ticket_subject", + 'body' => "Hello, " . $user_name . "

Scheduled work for the ticket regarding $ticket_subject has been cancelled.

--------------------------------
$ticket_link
--------------------------------

Please do not reply to this email.

Ticket: $ticket_prefix$ticket_number
Subject: $ticket_subject
Portal: https://$config_base_url/agent/ticket.php?id=$ticket_id&client_id=$client_id

~
$session_company_name
Support Department
$config_ticket_from_email", + 'cal_str' => $cal_str + ]; + + if ($config_ticket_client_general_notifications) { + // Notify the ticket contact of the cancellation + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => "Ticket Schedule Cancelled - [$ticket_prefix$ticket_number] - $ticket_subject", + 'body' => mysqli_escape_string($mysqli, "
+ Hello, $contact_name +
+ Scheduled work for your ticket regarding $ticket_subject has been cancelled. +

+ Access your ticket here +

+ Please do not reply to this email. +

+ Ticket: $ticket_prefix$ticket_number
+ Subject: $ticket_subject
+

+ +
+ This is an automated message. Please do not reply directly to this email. +
"), + 'cal_str' => $cal_str + ]; + + // Notify the watchers of the cancellation + $sql_watchers = mysqli_query($mysqli, "SELECT watcher_email FROM ticket_watchers WHERE watcher_ticket_id = $ticket_id"); + while ($row = mysqli_fetch_assoc($sql_watchers)) { + $watcher_email = escapeSql($row['watcher_email']); + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $watcher_email, + 'recipient_name' => $watcher_email, + 'subject' => "Ticket Schedule Cancelled - [$ticket_prefix$ticket_number] - $ticket_subject", + 'body' => mysqli_escape_string($mysqli, escapeHtml("
+ Hello, +
+ Scheduled work for the ticket regarding $ticket_subject has been cancelled. +

+ $ticket_link +

+ Please do not reply to this email. +

+ Ticket: $ticket_prefix$ticket_number
+ Subject: $ticket_subject
+ Portal: Access the ticket here +

+ +
+ This is an automated message. Please do not reply directly to this email. +
")), + 'cal_str' => $cal_str + ]; + } + } + + // Send email(s) + addToMailQueue($data); + + // Update ticket reply + $ticket_reply_note = "Ticket schedule cancelled."; + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$ticket_reply_note', ticket_reply_type = 'Internal', ticket_reply_time_worked = '00:01:00', ticket_reply_by = $session_user_id, ticket_reply_ticket_id = $ticket_id"); + + logAudit("Ticket", "Edit", "$session_name cancelled ticket schedule", $client_id, $ticket_id); + + triggerCustomAction('ticket_unschedule', $ticket_id); + + flashAlert("Ticket schedule cancelled", 'error'); + + redirect(); + +} diff --git a/cron/mail_queue.php b/cron/mail_queue.php index cab72968..a0a0fc21 100644 --- a/cron/mail_queue.php +++ b/cron/mail_queue.php @@ -1,476 +1,476 @@ -email = $email; - $this->accessToken = $accessToken; - } - public function getOauth64(): string { - $auth = "user={$this->email}\x01auth=Bearer {$this->accessToken}\x01\x01"; - return base64_encode($auth); - } -} - -/** ======================================================================= - * Load settings - * ======================================================================= */ -$sql_settings = mysqli_query($mysqli, "SELECT * FROM settings WHERE company_id = 1"); -$row = mysqli_fetch_assoc($sql_settings); - -$config_enable_cron = intval($row['config_enable_cron']); - -// SMTP baseline -$config_smtp_host = $row['config_smtp_host']; -$config_smtp_username = $row['config_smtp_username']; -$config_smtp_password = $row['config_smtp_password']; -$config_smtp_port = intval($row['config_smtp_port']); -$config_smtp_encryption = $row['config_smtp_encryption']; - -// SMTP provider + shared OAuth fields -$config_smtp_provider = $row['config_smtp_provider']; // 'standard_smtp' | 'google_oauth' | 'microsoft_oauth' -$config_mail_oauth_client_id = $row['config_mail_oauth_client_id'] ?? ''; -$config_mail_oauth_client_secret = $row['config_mail_oauth_client_secret'] ?? ''; -$config_mail_oauth_tenant_id = $row['config_mail_oauth_tenant_id'] ?? ''; -$config_mail_oauth_refresh_token = $row['config_mail_oauth_refresh_token'] ?? ''; -$config_mail_oauth_access_token = $row['config_mail_oauth_access_token'] ?? ''; -$config_mail_oauth_access_token_expires_at = $row['config_mail_oauth_access_token_expires_at'] ?? ''; - -if ($config_enable_cron == 0) { - logApp("Cron-Mail-Queue", "error", "Cron Mail Queue unable to run - cron not enabled in admin settings."); - exit("Cron: is not enabled -- Quitting.."); -} - -if (empty($config_smtp_provider)) { - logApp("Cron-Mail-Queue", "info", "SMTP sending skipped: provider not configured."); - exit(0); -} - -/** ======================================================================= - * Mail OAuth helpers + sender function - * ======================================================================= */ -function tokenIsExpired(?string $expires_at): bool { - if (empty($expires_at)) { - return true; - } - - $ts = strtotime($expires_at); - - if ($ts === false) { - return true; - } - - return ($ts - 60) <= time(); -} - -function httpFormPost(string $url, array $fields): array { - $ch = curl_init($url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields, '', '&')); - curl_setopt($ch, CURLOPT_TIMEOUT, 20); - - $raw = curl_exec($ch); - $err = curl_error($ch); - $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - - curl_close($ch); - - return [ - 'ok' => ($raw !== false && $code >= 200 && $code < 300), - 'body' => $raw, - 'code' => $code, - 'err' => $err, - ]; -} - -function persistMailOauthTokens(string $access_token, string $expires_at, ?string $refresh_token = null): void { - global $mysqli; - - $access_token_esc = mysqli_real_escape_string($mysqli, $access_token); - $expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at); - - $refresh_sql = ''; - if (!empty($refresh_token)) { - $refresh_token_esc = mysqli_real_escape_string($mysqli, $refresh_token); - $refresh_sql = ", config_mail_oauth_refresh_token = '{$refresh_token_esc}'"; - } - - mysqli_query($mysqli, "UPDATE settings SET config_mail_oauth_access_token = '{$access_token_esc}', config_mail_oauth_access_token_expires_at = '{$expires_at_esc}'{$refresh_sql} WHERE company_id = 1"); -} - -function refreshMailOauthAccessToken(string $provider, string $oauth_client_id, string $oauth_client_secret, string $oauth_tenant_id, string $oauth_refresh_token): ?array { - $result = null; - $response = null; - - if (!empty($oauth_client_id) && !empty($oauth_client_secret) && !empty($oauth_refresh_token)) { - if ($provider === 'google_oauth') { - $response = httpFormPost(GOOGLE_OAUTH_TOKEN_URL, [ - 'client_id' => $oauth_client_id, - 'client_secret' => $oauth_client_secret, - 'refresh_token' => $oauth_refresh_token, - 'grant_type' => 'refresh_token', - ]); - } elseif ($provider === 'microsoft_oauth' && !empty($oauth_tenant_id)) { - $token_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($oauth_tenant_id) . "/oauth2/v2.0/token"; - $response = httpFormPost($token_url, [ - 'client_id' => $oauth_client_id, - 'client_secret' => $oauth_client_secret, - 'refresh_token' => $oauth_refresh_token, - 'grant_type' => 'refresh_token', - ]); - } - } - - if (is_array($response) && !empty($response['ok'])) { - $json = json_decode($response['body'], true); - - if (is_array($json) && !empty($json['access_token'])) { - $expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600)); - $result = [ - 'access_token' => $json['access_token'], - 'expires_at' => $expires_at, - 'refresh_token' => $json['refresh_token'] ?? null, - ]; - } - } - - return $result; -} - -function resolveMailOauthAccessToken(string $provider, string $oauth_client_id, string $oauth_client_secret, string $oauth_tenant_id, string $oauth_refresh_token, string $oauth_access_token, string $oauth_access_token_expires_at): ?string { - if (!empty($oauth_access_token) && !tokenIsExpired($oauth_access_token_expires_at)) { - return $oauth_access_token; - } - - $tokens = refreshMailOauthAccessToken($provider, $oauth_client_id, $oauth_client_secret, $oauth_tenant_id, $oauth_refresh_token); - - if (!is_array($tokens) || empty($tokens['access_token']) || empty($tokens['expires_at'])) { - return null; - } - - persistMailOauthTokens($tokens['access_token'], $tokens['expires_at'], $tokens['refresh_token'] ?? null); - - return $tokens['access_token']; -} - -function sendQueueEmail( - string $provider, - string $host, - int $port, - string $encryption, - string $username, - string $password, - string $from_email, - string $from_name, - string $to_email, - string $to_name, - string $subject, - string $html_body, - string $ics_str, - string $oauth_client_id, - string $oauth_client_secret, - string $oauth_tenant_id, - string $oauth_refresh_token, - string $oauth_access_token, - string $oauth_access_token_expires_at -) { - // Sensible defaults for OAuth providers if fields were left blank - if ($provider === 'google_oauth') { - if (!$host) $host = 'smtp.gmail.com'; - if (!$port) $port = 587; - if (!$encryption) $encryption = 'tls'; - if (!$username) $username = $from_email; - } elseif ($provider === 'microsoft_oauth') { - if (!$host) $host = 'smtp.office365.com'; - if (!$port) $port = 587; - if (!$encryption) $encryption = 'tls'; - if (!$username) $username = $from_email; - } - - $mail = new PHPMailer(true); - $mail->CharSet = "UTF-8"; - $mail->SMTPDebug = 0; - $mail->isSMTP(); - $mail->Host = $host; - $mail->Port = $port; - // Bound the SMTP conversation. Without this an unresponsive mail server can - // hold the cron lock open indefinitely and stall the whole queue. - $mail->Timeout = 30; - - $enc = strtolower($encryption); - if ($enc === '' || $enc === 'none') { - $mail->SMTPAutoTLS = false; - $mail->SMTPSecure = false; - $mail->SMTPOptions = ['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]; - } else { - $mail->SMTPSecure = $enc; // 'tls' | 'ssl' - } - - if ($provider === 'google_oauth' || $provider === 'microsoft_oauth') { - // XOAUTH2 - $mail->SMTPAuth = true; - $mail->AuthType = 'XOAUTH2'; - $mail->Username = $username; - - $access_token = resolveMailOauthAccessToken( - $provider, - trim($oauth_client_id), - trim($oauth_client_secret), - trim($oauth_tenant_id), - trim($oauth_refresh_token), - trim($oauth_access_token), - trim($oauth_access_token_expires_at) - ); - - if (empty($access_token)) { - throw new Exception("Missing OAuth access token for XOAUTH2 SMTP."); - } - - $mail->setOAuth(new StaticTokenProvider($username, $access_token)); - } else { - // Standard SMTP (with or without auth) - $mail->SMTPAuth = !empty($username); - $mail->Username = $username ?: ''; - $mail->Password = $password ?: ''; - } - - // Recipients & content - $mail->setFrom($from_email, $from_name); - $mail->addAddress($to_email, $to_name); - $mail->isHTML(true); - $mail->Subject = $subject; - $mail->Body = $html_body; - - if (!empty($ics_str)) { - $mail->addStringAttachment($ics_str, 'Scheduled_ticket.ics', 'base64', 'text/calendar'); - } - - $mail->send(); - return true; -} - -/** ======================================================================= - * RECOVER: status = 1 (Sending) left behind by a run that died - * - * Nothing else in the codebase ever selects status 1, so without this a row - * claimed by a run that was killed mid-send stays 'Sending' forever and is never - * delivered. The cron lock above guarantees no other run of this script is in - * progress, so any row still sitting at status 1 is by definition orphaned and - * safe to reclaim. It is moved to failed rather than queued so it inherits the - * retry pass's 30 minute backoff and attempt cap instead of retrying instantly. - * - * This can re-send a message that did go out but died before being marked sent. - * That trade is deliberate: a duplicate is recoverable, an invoice that silently - * never arrives is not. - * ======================================================================= */ -mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = email_attempts + 1 WHERE email_status = 1"); -$orphaned_emails = mysqli_affected_rows($mysqli); -if ($orphaned_emails > 0) { - logApp("Cron-Mail-Queue", "warning", "Recovered $orphaned_emails email(s) left in a sending state by a previous run - queued for retry."); -} - -/** ======================================================================= - * SEND: status = 0 (Queued) - * ======================================================================= */ -$sql_queue = mysqli_query($mysqli, "SELECT * FROM email_queue WHERE email_status = 0 AND email_queued_at <= NOW()"); - -if (mysqli_num_rows($sql_queue) > 0) { - while ($rowq = mysqli_fetch_assoc($sql_queue)) { - $email_id = (int)$rowq['email_id']; - $email_from = $rowq['email_from']; - $email_from_name = $rowq['email_from_name']; - $email_recipient = $rowq['email_recipient']; - $email_recipient_name = $rowq['email_recipient_name']; - $email_subject = $rowq['email_subject']; - $email_content = $rowq['email_content']; - $email_ics_str = $rowq['email_cal_str']; - - // Check sender - if (!filter_var($email_from, FILTER_VALIDATE_EMAIL)) { - $email_from_logging = escapeSql($rowq['email_from']); - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99 WHERE email_id = $email_id"); - logApp("Cron-Mail-Queue", "Error", "Failed to send email #$email_id due to invalid sender address: $email_from_logging - check configuration in settings."); - appNotify("Mail", "Failed to send email #$email_id due to invalid sender address"); - continue; - } - - // Claim the row - the conditional UPDATE is the lock. If another run already took - // this email, skip it rather than sending the client a second copy. - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id AND email_status = 0"); - if (mysqli_affected_rows($mysqli) !== 1) { - continue; - } - - // Basic recipient syntax check - if (!filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99 WHERE email_id = $email_id"); - $email_to_logging = escapeSql($email_recipient); - $email_subject_logging = escapeSql($rowq['email_subject']); - logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_to_logging due to invalid recipient address. Email subject was: $email_subject_logging"); - appNotify("Mail", "Failed to send email #$email_id to $email_to_logging due to invalid recipient address: Email subject was: $email_subject_logging"); - continue; - } - - // More intelligent recipient MX check (if not disabled with --no-mx-validation) - $domain = escapeSql(substr($email_recipient, strpos($email_recipient, '@') + 1)); - if (!in_array('--no-mx-validation', $argv) && !checkdnsrr($domain, 'MX')) { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99 WHERE email_id = $email_id"); - $email_to_logging = escapeSql($email_recipient); - $email_subject_logging = escapeSql($rowq['email_subject']); - logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_to_logging due to invalid recipient domain (no MX). Email subject was: $email_subject_logging"); - appNotify("Mail", "Failed to send email #$email_id to $email_to_logging due to invalid recipient domain (no MX): Email subject was: $email_subject_logging"); - continue; - } - - try { - sendQueueEmail( - ($config_smtp_provider ?: 'standard_smtp'), - $config_smtp_host, - (int)$config_smtp_port, - (string)$config_smtp_encryption, - (string)$config_smtp_username, - (string)$config_smtp_password, - (string)$email_from, - (string)$email_from_name, - (string)$email_recipient, - (string)$email_recipient_name, - (string)$email_subject, - (string)$email_content, - (string)$email_ics_str, - (string)$config_mail_oauth_client_id, - (string)$config_mail_oauth_client_secret, - (string)$config_mail_oauth_tenant_id, - (string)$config_mail_oauth_refresh_token, - (string)$config_mail_oauth_access_token, - (string)$config_mail_oauth_access_token_expires_at - ); - - // Scrub the body on delivery - it can carry share decryption keys and temporary passwords - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = 1, email_content = '', email_cal_str = '' WHERE email_id = $email_id"); - - } catch (Exception $e) { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = 1 WHERE email_id = $email_id"); - - $email_recipient_logging = escapeSql($rowq['email_recipient']); - $email_subject_logging = escapeSql($rowq['email_subject']); - $err = substr("Mailer Error: " . $e->getMessage(), 0, 100) . "..."; - - appNotify("Cron-Mail-Queue", "Failed to send email #$email_id to $email_recipient_logging"); - logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_recipient_logging regarding $email_subject_logging. $err"); - } - } -} - -/** ======================================================================= - * RETRIES: status = 2 (Failed), attempts < 4, wait 30 min - * NOTE: Backoff is `email_failed_at <= NOW() - INTERVAL 30 MINUTE` - * ======================================================================= - */ -$sql_failed_queue = mysqli_query( - $mysqli, - "SELECT * FROM email_queue - WHERE email_status = 2 - AND email_attempts < 4 - AND email_failed_at <= NOW() - INTERVAL 30 MINUTE" -); - -if (mysqli_num_rows($sql_failed_queue) > 0) { - while ($rowf = mysqli_fetch_assoc($sql_failed_queue)) { - $email_id = (int)$rowf['email_id']; - $email_from = $rowf['email_from']; - $email_from_name = $rowf['email_from_name']; - $email_recipient = $rowf['email_recipient']; - $email_recipient_name = $rowf['email_recipient_name']; - $email_subject = $rowf['email_subject']; - $email_content = $rowf['email_content']; - $email_ics_str = $rowf['email_cal_str']; - $email_attempts = (int)$rowf['email_attempts'] + 1; - - // Claim the row - same lock as the send path, from the failed state this time. - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id AND email_status = 2"); - if (mysqli_affected_rows($mysqli) !== 1) { - continue; - } - - if (!filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = $email_attempts WHERE email_id = $email_id"); - continue; - } - - try { - sendQueueEmail( - ($config_smtp_provider ?: 'standard_smtp'), - $config_smtp_host, - (int)$config_smtp_port, - (string)$config_smtp_encryption, - (string)$config_smtp_username, - (string)$config_smtp_password, - (string)$email_from, - (string)$email_from_name, - (string)$email_recipient, - (string)$email_recipient_name, - (string)$email_subject, - (string)$email_content, - (string)$email_ics_str, - (string)$config_mail_oauth_client_id, - (string)$config_mail_oauth_client_secret, - (string)$config_mail_oauth_tenant_id, - (string)$config_mail_oauth_refresh_token, - (string)$config_mail_oauth_access_token, - (string)$config_mail_oauth_access_token_expires_at - ); - - // Scrub the body on delivery - it can carry share decryption keys and temporary passwords - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = $email_attempts, email_content = '', email_cal_str = '' WHERE email_id = $email_id"); - - } catch (Exception $e) { - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = $email_attempts WHERE email_id = $email_id"); - - $email_recipient_logging = escapeSql($rowf['email_recipient']); - $email_subject_logging = escapeSql($rowf['email_subject']); - $err = substr("Mailer Error: " . $e->getMessage(), 0, 100) . "..."; - - logApp("Cron-Mail-Queue", "Error", "Failed to re-send email #$email_id to $email_recipient_logging regarding $email_subject_logging. $err"); - } - } -} +email = $email; + $this->accessToken = $accessToken; + } + public function getOauth64(): string { + $auth = "user={$this->email}\x01auth=Bearer {$this->accessToken}\x01\x01"; + return base64_encode($auth); + } +} + +/** ======================================================================= + * Load settings + * ======================================================================= */ +$sql_settings = mysqli_query($mysqli, "SELECT * FROM settings WHERE company_id = 1"); +$row = mysqli_fetch_assoc($sql_settings); + +$config_enable_cron = intval($row['config_enable_cron']); + +// SMTP baseline +$config_smtp_host = $row['config_smtp_host']; +$config_smtp_username = $row['config_smtp_username']; +$config_smtp_password = $row['config_smtp_password']; +$config_smtp_port = intval($row['config_smtp_port']); +$config_smtp_encryption = $row['config_smtp_encryption']; + +// SMTP provider + shared OAuth fields +$config_smtp_provider = $row['config_smtp_provider']; // 'standard_smtp' | 'google_oauth' | 'microsoft_oauth' +$config_mail_oauth_client_id = $row['config_mail_oauth_client_id'] ?? ''; +$config_mail_oauth_client_secret = $row['config_mail_oauth_client_secret'] ?? ''; +$config_mail_oauth_tenant_id = $row['config_mail_oauth_tenant_id'] ?? ''; +$config_mail_oauth_refresh_token = $row['config_mail_oauth_refresh_token'] ?? ''; +$config_mail_oauth_access_token = $row['config_mail_oauth_access_token'] ?? ''; +$config_mail_oauth_access_token_expires_at = $row['config_mail_oauth_access_token_expires_at'] ?? ''; + +if ($config_enable_cron == 0) { + logApp("Cron-Mail-Queue", "error", "Cron Mail Queue unable to run - cron not enabled in admin settings."); + exit("Cron: is not enabled -- Quitting.."); +} + +if (empty($config_smtp_provider)) { + logApp("Cron-Mail-Queue", "info", "SMTP sending skipped: provider not configured."); + exit(0); +} + +/** ======================================================================= + * Mail OAuth helpers + sender function + * ======================================================================= */ +function tokenIsExpired(?string $expires_at): bool { + if (empty($expires_at)) { + return true; + } + + $ts = strtotime($expires_at); + + if ($ts === false) { + return true; + } + + return ($ts - 60) <= time(); +} + +function httpFormPost(string $url, array $fields): array { + $ch = curl_init($url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields, '', '&')); + curl_setopt($ch, CURLOPT_TIMEOUT, 20); + + $raw = curl_exec($ch); + $err = curl_error($ch); + $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + + curl_close($ch); + + return [ + 'ok' => ($raw !== false && $code >= 200 && $code < 300), + 'body' => $raw, + 'code' => $code, + 'err' => $err, + ]; +} + +function persistMailOauthTokens(string $access_token, string $expires_at, ?string $refresh_token = null): void { + global $mysqli; + + $access_token_esc = mysqli_real_escape_string($mysqli, $access_token); + $expires_at_esc = mysqli_real_escape_string($mysqli, $expires_at); + + $refresh_sql = ''; + if (!empty($refresh_token)) { + $refresh_token_esc = mysqli_real_escape_string($mysqli, $refresh_token); + $refresh_sql = ", config_mail_oauth_refresh_token = '{$refresh_token_esc}'"; + } + + mysqli_query($mysqli, "UPDATE settings SET config_mail_oauth_access_token = '{$access_token_esc}', config_mail_oauth_access_token_expires_at = '{$expires_at_esc}'{$refresh_sql} WHERE company_id = 1"); +} + +function refreshMailOauthAccessToken(string $provider, string $oauth_client_id, string $oauth_client_secret, string $oauth_tenant_id, string $oauth_refresh_token): ?array { + $result = null; + $response = null; + + if (!empty($oauth_client_id) && !empty($oauth_client_secret) && !empty($oauth_refresh_token)) { + if ($provider === 'google_oauth') { + $response = httpFormPost(GOOGLE_OAUTH_TOKEN_URL, [ + 'client_id' => $oauth_client_id, + 'client_secret' => $oauth_client_secret, + 'refresh_token' => $oauth_refresh_token, + 'grant_type' => 'refresh_token', + ]); + } elseif ($provider === 'microsoft_oauth' && !empty($oauth_tenant_id)) { + $token_url = MICROSOFT_OAUTH_BASE_URL . rawurlencode($oauth_tenant_id) . "/oauth2/v2.0/token"; + $response = httpFormPost($token_url, [ + 'client_id' => $oauth_client_id, + 'client_secret' => $oauth_client_secret, + 'refresh_token' => $oauth_refresh_token, + 'grant_type' => 'refresh_token', + ]); + } + } + + if (is_array($response) && !empty($response['ok'])) { + $json = json_decode($response['body'], true); + + if (is_array($json) && !empty($json['access_token'])) { + $expires_at = date('Y-m-d H:i:s', time() + (int)($json['expires_in'] ?? 3600)); + $result = [ + 'access_token' => $json['access_token'], + 'expires_at' => $expires_at, + 'refresh_token' => $json['refresh_token'] ?? null, + ]; + } + } + + return $result; +} + +function resolveMailOauthAccessToken(string $provider, string $oauth_client_id, string $oauth_client_secret, string $oauth_tenant_id, string $oauth_refresh_token, string $oauth_access_token, string $oauth_access_token_expires_at): ?string { + if (!empty($oauth_access_token) && !tokenIsExpired($oauth_access_token_expires_at)) { + return $oauth_access_token; + } + + $tokens = refreshMailOauthAccessToken($provider, $oauth_client_id, $oauth_client_secret, $oauth_tenant_id, $oauth_refresh_token); + + if (!is_array($tokens) || empty($tokens['access_token']) || empty($tokens['expires_at'])) { + return null; + } + + persistMailOauthTokens($tokens['access_token'], $tokens['expires_at'], $tokens['refresh_token'] ?? null); + + return $tokens['access_token']; +} + +function sendQueueEmail( + string $provider, + string $host, + int $port, + string $encryption, + string $username, + string $password, + string $from_email, + string $from_name, + string $to_email, + string $to_name, + string $subject, + string $html_body, + string $ics_str, + string $oauth_client_id, + string $oauth_client_secret, + string $oauth_tenant_id, + string $oauth_refresh_token, + string $oauth_access_token, + string $oauth_access_token_expires_at +) { + // Sensible defaults for OAuth providers if fields were left blank + if ($provider === 'google_oauth') { + if (!$host) $host = 'smtp.gmail.com'; + if (!$port) $port = 587; + if (!$encryption) $encryption = 'tls'; + if (!$username) $username = $from_email; + } elseif ($provider === 'microsoft_oauth') { + if (!$host) $host = 'smtp.office365.com'; + if (!$port) $port = 587; + if (!$encryption) $encryption = 'tls'; + if (!$username) $username = $from_email; + } + + $mail = new PHPMailer(true); + $mail->CharSet = "UTF-8"; + $mail->SMTPDebug = 0; + $mail->isSMTP(); + $mail->Host = $host; + $mail->Port = $port; + // Bound the SMTP conversation. Without this an unresponsive mail server can + // hold the cron lock open indefinitely and stall the whole queue. + $mail->Timeout = 30; + + $enc = strtolower($encryption); + if ($enc === '' || $enc === 'none') { + $mail->SMTPAutoTLS = false; + $mail->SMTPSecure = false; + $mail->SMTPOptions = ['ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]; + } else { + $mail->SMTPSecure = $enc; // 'tls' | 'ssl' + } + + if ($provider === 'google_oauth' || $provider === 'microsoft_oauth') { + // XOAUTH2 + $mail->SMTPAuth = true; + $mail->AuthType = 'XOAUTH2'; + $mail->Username = $username; + + $access_token = resolveMailOauthAccessToken( + $provider, + trim($oauth_client_id), + trim($oauth_client_secret), + trim($oauth_tenant_id), + trim($oauth_refresh_token), + trim($oauth_access_token), + trim($oauth_access_token_expires_at) + ); + + if (empty($access_token)) { + throw new Exception("Missing OAuth access token for XOAUTH2 SMTP."); + } + + $mail->setOAuth(new StaticTokenProvider($username, $access_token)); + } else { + // Standard SMTP (with or without auth) + $mail->SMTPAuth = !empty($username); + $mail->Username = $username ?: ''; + $mail->Password = $password ?: ''; + } + + // Recipients & content + $mail->setFrom($from_email, $from_name); + $mail->addAddress($to_email, $to_name); + $mail->isHTML(true); + $mail->Subject = $subject; + $mail->Body = $html_body; + + if (!empty($ics_str)) { + $mail->addStringAttachment($ics_str, 'Scheduled_ticket.ics', 'base64', 'text/calendar'); + } + + $mail->send(); + return true; +} + +/** ======================================================================= + * RECOVER: status = 1 (Sending) left behind by a run that died + * + * Nothing else in the codebase ever selects status 1, so without this a row + * claimed by a run that was killed mid-send stays 'Sending' forever and is never + * delivered. The cron lock above guarantees no other run of this script is in + * progress, so any row still sitting at status 1 is by definition orphaned and + * safe to reclaim. It is moved to failed rather than queued so it inherits the + * retry pass's 30 minute backoff and attempt cap instead of retrying instantly. + * + * This can re-send a message that did go out but died before being marked sent. + * That trade is deliberate: a duplicate is recoverable, an invoice that silently + * never arrives is not. + * ======================================================================= */ +mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = email_attempts + 1 WHERE email_status = 1"); +$orphaned_emails = mysqli_affected_rows($mysqli); +if ($orphaned_emails > 0) { + logApp("Cron-Mail-Queue", "warning", "Recovered $orphaned_emails email(s) left in a sending state by a previous run - queued for retry."); +} + +/** ======================================================================= + * SEND: status = 0 (Queued) + * ======================================================================= */ +$sql_queue = mysqli_query($mysqli, "SELECT * FROM email_queue WHERE email_status = 0 AND email_queued_at <= NOW()"); + +if (mysqli_num_rows($sql_queue) > 0) { + while ($rowq = mysqli_fetch_assoc($sql_queue)) { + $email_id = (int)$rowq['email_id']; + $email_from = $rowq['email_from']; + $email_from_name = $rowq['email_from_name']; + $email_recipient = $rowq['email_recipient']; + $email_recipient_name = $rowq['email_recipient_name']; + $email_subject = $rowq['email_subject']; + $email_content = $rowq['email_content']; + $email_ics_str = $rowq['email_cal_str']; + + // Check sender + if (!filter_var($email_from, FILTER_VALIDATE_EMAIL)) { + $email_from_logging = escapeSql($rowq['email_from']); + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99 WHERE email_id = $email_id"); + logApp("Cron-Mail-Queue", "Error", "Failed to send email #$email_id due to invalid sender address: $email_from_logging - check configuration in settings."); + appNotify("Mail", "Failed to send email #$email_id due to invalid sender address"); + continue; + } + + // Claim the row - the conditional UPDATE is the lock. If another run already took + // this email, skip it rather than sending the client a second copy. + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id AND email_status = 0"); + if (mysqli_affected_rows($mysqli) !== 1) { + continue; + } + + // Basic recipient syntax check + if (!filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) { + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99 WHERE email_id = $email_id"); + $email_to_logging = escapeSql($email_recipient); + $email_subject_logging = escapeSql($rowq['email_subject']); + logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_to_logging due to invalid recipient address. Email subject was: $email_subject_logging"); + appNotify("Mail", "Failed to send email #$email_id to $email_to_logging due to invalid recipient address: Email subject was: $email_subject_logging"); + continue; + } + + // More intelligent recipient MX check (if not disabled with --no-mx-validation) + $domain = escapeSql(substr($email_recipient, strpos($email_recipient, '@') + 1)); + if (!in_array('--no-mx-validation', $argv) && !checkdnsrr($domain, 'MX')) { + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99 WHERE email_id = $email_id"); + $email_to_logging = escapeSql($email_recipient); + $email_subject_logging = escapeSql($rowq['email_subject']); + logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_to_logging due to invalid recipient domain (no MX). Email subject was: $email_subject_logging"); + appNotify("Mail", "Failed to send email #$email_id to $email_to_logging due to invalid recipient domain (no MX): Email subject was: $email_subject_logging"); + continue; + } + + try { + sendQueueEmail( + ($config_smtp_provider ?: 'standard_smtp'), + $config_smtp_host, + (int)$config_smtp_port, + (string)$config_smtp_encryption, + (string)$config_smtp_username, + (string)$config_smtp_password, + (string)$email_from, + (string)$email_from_name, + (string)$email_recipient, + (string)$email_recipient_name, + (string)$email_subject, + (string)$email_content, + (string)$email_ics_str, + (string)$config_mail_oauth_client_id, + (string)$config_mail_oauth_client_secret, + (string)$config_mail_oauth_tenant_id, + (string)$config_mail_oauth_refresh_token, + (string)$config_mail_oauth_access_token, + (string)$config_mail_oauth_access_token_expires_at + ); + + // Scrub the body on delivery - it can carry share decryption keys and temporary passwords + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = 1, email_content = '', email_cal_str = '' WHERE email_id = $email_id"); + + } catch (Exception $e) { + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = 1 WHERE email_id = $email_id"); + + $email_recipient_logging = escapeSql($rowq['email_recipient']); + $email_subject_logging = escapeSql($rowq['email_subject']); + $err = substr("Mailer Error: " . $e->getMessage(), 0, 100) . "..."; + + appNotify("Cron-Mail-Queue", "Failed to send email #$email_id to $email_recipient_logging"); + logApp("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_recipient_logging regarding $email_subject_logging. $err"); + } + } +} + +/** ======================================================================= + * RETRIES: status = 2 (Failed), attempts < 4, wait 30 min + * NOTE: Backoff is `email_failed_at <= NOW() - INTERVAL 30 MINUTE` + * ======================================================================= + */ +$sql_failed_queue = mysqli_query( + $mysqli, + "SELECT * FROM email_queue + WHERE email_status = 2 + AND email_attempts < 4 + AND email_failed_at <= NOW() - INTERVAL 30 MINUTE" +); + +if (mysqli_num_rows($sql_failed_queue) > 0) { + while ($rowf = mysqli_fetch_assoc($sql_failed_queue)) { + $email_id = (int)$rowf['email_id']; + $email_from = $rowf['email_from']; + $email_from_name = $rowf['email_from_name']; + $email_recipient = $rowf['email_recipient']; + $email_recipient_name = $rowf['email_recipient_name']; + $email_subject = $rowf['email_subject']; + $email_content = $rowf['email_content']; + $email_ics_str = $rowf['email_cal_str']; + $email_attempts = (int)$rowf['email_attempts'] + 1; + + // Claim the row - same lock as the send path, from the failed state this time. + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id AND email_status = 2"); + if (mysqli_affected_rows($mysqli) !== 1) { + continue; + } + + if (!filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) { + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = $email_attempts WHERE email_id = $email_id"); + continue; + } + + try { + sendQueueEmail( + ($config_smtp_provider ?: 'standard_smtp'), + $config_smtp_host, + (int)$config_smtp_port, + (string)$config_smtp_encryption, + (string)$config_smtp_username, + (string)$config_smtp_password, + (string)$email_from, + (string)$email_from_name, + (string)$email_recipient, + (string)$email_recipient_name, + (string)$email_subject, + (string)$email_content, + (string)$email_ics_str, + (string)$config_mail_oauth_client_id, + (string)$config_mail_oauth_client_secret, + (string)$config_mail_oauth_tenant_id, + (string)$config_mail_oauth_refresh_token, + (string)$config_mail_oauth_access_token, + (string)$config_mail_oauth_access_token_expires_at + ); + + // Scrub the body on delivery - it can carry share decryption keys and temporary passwords + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = $email_attempts, email_content = '', email_cal_str = '' WHERE email_id = $email_id"); + + } catch (Exception $e) { + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = $email_attempts WHERE email_id = $email_id"); + + $email_recipient_logging = escapeSql($rowf['email_recipient']); + $email_subject_logging = escapeSql($rowf['email_subject']); + $err = substr("Mailer Error: " . $e->getMessage(), 0, 100) . "..."; + + logApp("Cron-Mail-Queue", "Error", "Failed to re-send email #$email_id to $email_recipient_logging regarding $email_subject_logging. $err"); + } + } +} diff --git a/js/app.js b/js/app.js index 41ed075b..36d15e1a 100644 --- a/js/app.js +++ b/js/app.js @@ -1,412 +1,412 @@ -$(document).ready(function() { - // Prevents resubmit on forms - if (window.history.replaceState) { - window.history.replaceState(null, null, window.location.href); - } - - // Slide alert up after 4 secs - $("#alert").fadeTo(5000, 500).slideUp(500, function() { - $("#alert").slideUp(500); - }); - - // Initialize Select2 Elements - $('.select2').select2({ - theme: 'bootstrap4', - }); - - // Initialize TinyMCE - tinymce.init({ - selector: '.tinymce-simple', - browser_spellcheck: true, - contextmenu: false, - resize: true, - min_height: 300, - max_height: 600, - promotion: false, - branding: false, - menubar: false, - statusbar: false, - toolbar: [ - { name: 'styles', items: ['styles'] }, - { name: 'formatting', items: ['bold', 'italic', 'forecolor'] }, - { name: 'link', items: ['link'] }, - { name: 'lists', items: ['bullist', 'numlist'] }, - { name: 'alignment', items: ['alignleft', 'aligncenter', 'alignright', 'alignjustify'] }, - { name: 'indentation', items: ['outdent', 'indent'] }, - { name: 'table', items: ['table'] }, - { name: 'extra', items: ['code', 'fullscreen'] } - ], - mobile: { - menubar: false, - plugins: 'autosave lists autolink', - toolbar: 'bold italic styles' - }, - convert_urls: false, - plugins: 'link image lists table code codesample fullscreen autoresize', - setup: function (editor) { - editor.on('init', function() { - window.onbeforeunload = function() { - // If editor is dirty AND not inside a visible modal → warn - const inVisibleModal = editor.getContainer()?.closest('.modal.show'); - if (!inVisibleModal && editor.isDirty()) { - return "You have unsaved changes. Are you sure you want to leave?"; - } - }; - - // When the modal closes, mark editor clean - const modal = editor.getContainer()?.closest('.modal'); - if (modal) { - modal.addEventListener('hidden.bs.modal', () => { - editor.undoManager.clear(); - editor.setDirty(false); - }); - } - }); - }, - license_key: 'gpl' - }); - - // Initialize TinyMCE with AI - tinymce.init({ - selector: '.tinymce', - browser_spellcheck: true, - contextmenu: false, - resize: true, - min_height: 300, - max_height: 600, - promotion: false, - branding: false, - menubar: false, - statusbar: false, - toolbar: [ - { name: 'styles', items: ['styles'] }, - { name: 'formatting', items: ['bold', 'italic', 'forecolor'] }, - { name: 'link', items: ['link'] }, - { name: 'lists', items: ['bullist', 'numlist'] }, - { name: 'alignment', items: ['alignleft', 'aligncenter', 'alignright', 'alignjustify'] }, - { name: 'indentation', items: ['outdent', 'indent'] }, - { name: 'table', items: ['table'] }, - { name: 'extra', items: ['code', 'fullscreen'] }, - { name: 'ai', items: ['reword', 'undo', 'redo'] } - ], - mobile: { - menubar: false, - plugins: 'autosave lists autolink', - toolbar: 'bold italic styles' - }, - convert_urls: false, - plugins: 'link image lists table code codesample fullscreen autoresize', - license_key: 'gpl', - setup: function(editor) { - editor.on('init', function() { - window.onbeforeunload = function() { - // If editor is dirty AND not inside a visible modal → warn - const inVisibleModal = editor.getContainer()?.closest('.modal.show'); - if (!inVisibleModal && editor.isDirty()) { - return "You have unsaved changes. Are you sure you want to leave?"; - } - }; - - // When the modal closes, mark editor clean - const modal = editor.getContainer()?.closest('.modal'); - if (modal) { - modal.addEventListener('hidden.bs.modal', () => { - editor.undoManager.clear(); - editor.setDirty(false); - }); - } - }); - - var rewordButtonApi; - - editor.ui.registry.addButton('reword', { - icon: 'ai', - tooltip: 'Reword Text', - onAction: function() { - var content = editor.getContent(); - - // Disable the Reword button - rewordButtonApi.setEnabled(false); - - // Show the progress indicator - editor.setProgressState(true); - - fetch('ajax.php?ai_reword', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ text: content }), - }) - .then(response => { - if (!response.ok) { - throw new Error('Network response was not ok'); - } - return response.json(); - }) - .then(data => { - editor.undoManager.transact(function() { - editor.setContent(data.rewordedText || 'Error: Could not reword the text.'); - }); - - editor.setProgressState(false); - rewordButtonApi.setEnabled(true); - - editor.notificationManager.open({ - text: 'Text reworded successfully!', - type: 'success', - timeout: 3000 - }); - }) - .catch(error => { - console.error('Error:', error); - editor.setProgressState(false); - rewordButtonApi.setEnabled(true); - editor.notificationManager.open({ - text: 'An error occurred while rewording the text.', - type: 'error', - timeout: 5000 - }); - }); - }, - onSetup: function(buttonApi) { - rewordButtonApi = buttonApi; - return function() {}; - } - }); - } - }); - - // Initialize TinyMCE AI for Tickets - tinymce.init({ - selector: '.tinymceTicket', - browser_spellcheck: true, - contextmenu: false, - resize: true, - min_height: 200, - max_height: 600, - promotion: false, - branding: false, - menubar: false, - statusbar: false, - toolbar: [ - { name: 'styles', items: ['styles'] }, - { name: 'formatting', items: ['bold', 'italic', 'forecolor'] }, - { name: 'link', items: ['link'] }, - { name: 'lists', items: ['bullist', 'numlist'] }, - { name: 'indentation', items: ['outdent', 'indent'] }, - { name: 'ai', items: ['reword', 'undo', 'redo'] }, - { name: 'custom', items: ['redactButton'] }, - { name: 'code', items: ['code'] }, - ], - mobile: { - menubar: false, - toolbar: [ - { name: 'styles', items: ['styles'] }, - { name: 'formatting', items: ['bold', 'italic', 'forecolor'] }, - { name: 'link', items: ['link'] }, - { name: 'lists', items: ['bullist', 'numlist'] }, - { name: 'indentation', items: ['outdent', 'indent'] }, - { name: 'ai', items: ['reword', 'undo', 'redo'] }, - { name: 'custom', items: ['redactButton'] }, - { name: 'code', items: ['code'] }, - ], - }, - convert_urls: false, - plugins: 'link image lists table code codesample fullscreen autoresize code', - license_key: 'gpl', - setup: function(editor) { - editor.on('init', function() { - window.onbeforeunload = function() { - // If editor is dirty AND not inside a visible modal → warn - const inVisibleModal = editor.getContainer()?.closest('.modal.show'); - if (!inVisibleModal && editor.isDirty()) { - return "You have unsaved changes. Are you sure you want to leave?"; - } - }; - - // When the modal closes, mark editor clean - const modal = editor.getContainer()?.closest('.modal'); - if (modal) { - modal.addEventListener('hidden.bs.modal', () => { - editor.undoManager.clear(); - editor.setDirty(false); - }); - } - }); - - var rewordButtonApi; - - editor.ui.registry.addButton('reword', { - icon: 'ai', - tooltip: 'Reword Text', - onAction: function() { - var content = editor.getContent(); - rewordButtonApi.setEnabled(false); - editor.setProgressState(true); - - fetch('ajax.php?ai_reword', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ text: content }), - }) - .then(response => { - if (!response.ok) throw new Error('Network response was not ok'); - return response.json(); - }) - .then(data => { - editor.undoManager.transact(function() { - editor.setContent(data.rewordedText || 'Error: Could not reword the text.'); - }); - editor.setProgressState(false); - rewordButtonApi.setEnabled(true); - editor.notificationManager.open({ - text: 'Text reworded successfully!', - type: 'success', - timeout: 3000 - }); - }) - .catch(error => { - console.error('Error:', error); - editor.setProgressState(false); - rewordButtonApi.setEnabled(true); - editor.notificationManager.open({ - text: 'An error occurred while rewording the text.', - type: 'error', - timeout: 5000 - }); - }); - }, - onSetup: function(buttonApi) { - rewordButtonApi = buttonApi; - return function() {}; - } - }); - - editor.ui.registry.addButton('redactButton', { - icon: 'permanent-pen', - tooltip: 'Redact Text', - onAction: function() { - var selectedText = editor.selection.getContent({ format: 'text' }); - if (selectedText) { - var newContent = '[REDACTED]'; - editor.selection.setContent(newContent); - } else { - alert('Please select a word to redact'); - } - } - }); - } - }); - - // Initialize TinyMCE Redact-only - tinymce.init({ - selector: '.tinymceRedact', - browser_spellcheck: true, - contextmenu: false, - resize: true, - min_height: 300, - max_height: 600, - promotion: false, - branding: false, - menubar: false, - statusbar: false, - toolbar: 'redactButton', - mobile: { - menubar: false, - plugins: 'autosave lists autolink', - toolbar: 'redactButton' - }, - convert_urls: false, - plugins: 'link image lists table code fullscreen autoresize', - license_key: 'gpl', - setup: function(editor) { - - editor.on('init', function() { - window.onbeforeunload = function() { - // If editor is dirty AND not inside a visible modal → warn - const inVisibleModal = editor.getContainer()?.closest('.modal.show'); - if (!inVisibleModal && editor.isDirty()) { - return "You have unsaved changes. Are you sure you want to leave?"; - } - }; - - // When the modal closes, mark editor clean - const modal = editor.getContainer()?.closest('.modal'); - if (modal) { - modal.addEventListener('hidden.bs.modal', () => { - editor.undoManager.clear(); - editor.setDirty(false); - }); - } - }); - - editor.on('keydown', function(e) { - e.preventDefault(); - }); - - editor.ui.registry.addButton('redactButton', { - icon: 'permanent-pen', - tooltip: 'Redact', - text: 'REDACT', - onAction: function() { - var selectedText = editor.selection.getContent({ format: 'text' }); - if (selectedText) { - var newContent = '[REDACTED]'; - editor.selection.setContent(newContent); - } else { - alert('Please select a word to redact'); - } - } - }); - } - }); - - // DateTime - $('.datetimepicker').datetimepicker(); - - // Data Input Mask - $('[data-mask]').inputmask(); - - // ClipboardJS fix for Bootstrap modals - $.fn.modal.Constructor.prototype._enforceFocus = function() {}; - - // Tooltip - $('button').tooltip({ - trigger: 'click', - placement: 'bottom' - }); - - function setTooltip(btn, message) { - $(btn).tooltip('hide') - .attr('data-original-title', message) - .tooltip('show'); - } - - function hideTooltip(btn) { - setTimeout(function() { - $(btn).tooltip('hide'); - }, 1000); - } - - // Clipboard - var clipboard = new ClipboardJS('.clipboardjs'); - - clipboard.on('success', function(e) { - setTooltip(e.trigger, 'Copied!'); - hideTooltip(e.trigger); - }); - - clipboard.on('error', function(e) { - setTooltip(e.trigger, 'Failed!'); - hideTooltip(e.trigger); - }); - - // Enable Popovers - $(function() { - $('[data-toggle="popover"]').popover(); - }); - - // Data Tables - new DataTable('.dataTables'); -}); +$(document).ready(function() { + // Prevents resubmit on forms + if (window.history.replaceState) { + window.history.replaceState(null, null, window.location.href); + } + + // Slide alert up after 4 secs + $("#alert").fadeTo(5000, 500).slideUp(500, function() { + $("#alert").slideUp(500); + }); + + // Initialize Select2 Elements + $('.select2').select2({ + theme: 'bootstrap4', + }); + + // Initialize TinyMCE + tinymce.init({ + selector: '.tinymce-simple', + browser_spellcheck: true, + contextmenu: false, + resize: true, + min_height: 300, + max_height: 600, + promotion: false, + branding: false, + menubar: false, + statusbar: false, + toolbar: [ + { name: 'styles', items: ['styles'] }, + { name: 'formatting', items: ['bold', 'italic', 'forecolor'] }, + { name: 'link', items: ['link'] }, + { name: 'lists', items: ['bullist', 'numlist'] }, + { name: 'alignment', items: ['alignleft', 'aligncenter', 'alignright', 'alignjustify'] }, + { name: 'indentation', items: ['outdent', 'indent'] }, + { name: 'table', items: ['table'] }, + { name: 'extra', items: ['code', 'fullscreen'] } + ], + mobile: { + menubar: false, + plugins: 'autosave lists autolink', + toolbar: 'bold italic styles' + }, + convert_urls: false, + plugins: 'link image lists table code codesample fullscreen autoresize', + setup: function (editor) { + editor.on('init', function() { + window.onbeforeunload = function() { + // If editor is dirty AND not inside a visible modal → warn + const inVisibleModal = editor.getContainer()?.closest('.modal.show'); + if (!inVisibleModal && editor.isDirty()) { + return "You have unsaved changes. Are you sure you want to leave?"; + } + }; + + // When the modal closes, mark editor clean + const modal = editor.getContainer()?.closest('.modal'); + if (modal) { + modal.addEventListener('hidden.bs.modal', () => { + editor.undoManager.clear(); + editor.setDirty(false); + }); + } + }); + }, + license_key: 'gpl' + }); + + // Initialize TinyMCE with AI + tinymce.init({ + selector: '.tinymce', + browser_spellcheck: true, + contextmenu: false, + resize: true, + min_height: 300, + max_height: 600, + promotion: false, + branding: false, + menubar: false, + statusbar: false, + toolbar: [ + { name: 'styles', items: ['styles'] }, + { name: 'formatting', items: ['bold', 'italic', 'forecolor'] }, + { name: 'link', items: ['link'] }, + { name: 'lists', items: ['bullist', 'numlist'] }, + { name: 'alignment', items: ['alignleft', 'aligncenter', 'alignright', 'alignjustify'] }, + { name: 'indentation', items: ['outdent', 'indent'] }, + { name: 'table', items: ['table'] }, + { name: 'extra', items: ['code', 'fullscreen'] }, + { name: 'ai', items: ['reword', 'undo', 'redo'] } + ], + mobile: { + menubar: false, + plugins: 'autosave lists autolink', + toolbar: 'bold italic styles' + }, + convert_urls: false, + plugins: 'link image lists table code codesample fullscreen autoresize', + license_key: 'gpl', + setup: function(editor) { + editor.on('init', function() { + window.onbeforeunload = function() { + // If editor is dirty AND not inside a visible modal → warn + const inVisibleModal = editor.getContainer()?.closest('.modal.show'); + if (!inVisibleModal && editor.isDirty()) { + return "You have unsaved changes. Are you sure you want to leave?"; + } + }; + + // When the modal closes, mark editor clean + const modal = editor.getContainer()?.closest('.modal'); + if (modal) { + modal.addEventListener('hidden.bs.modal', () => { + editor.undoManager.clear(); + editor.setDirty(false); + }); + } + }); + + var rewordButtonApi; + + editor.ui.registry.addButton('reword', { + icon: 'ai', + tooltip: 'Reword Text', + onAction: function() { + var content = editor.getContent(); + + // Disable the Reword button + rewordButtonApi.setEnabled(false); + + // Show the progress indicator + editor.setProgressState(true); + + fetch('ajax.php?ai_reword', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ text: content }), + }) + .then(response => { + if (!response.ok) { + throw new Error('Network response was not ok'); + } + return response.json(); + }) + .then(data => { + editor.undoManager.transact(function() { + editor.setContent(data.rewordedText || 'Error: Could not reword the text.'); + }); + + editor.setProgressState(false); + rewordButtonApi.setEnabled(true); + + editor.notificationManager.open({ + text: 'Text reworded successfully!', + type: 'success', + timeout: 3000 + }); + }) + .catch(error => { + console.error('Error:', error); + editor.setProgressState(false); + rewordButtonApi.setEnabled(true); + editor.notificationManager.open({ + text: 'An error occurred while rewording the text.', + type: 'error', + timeout: 5000 + }); + }); + }, + onSetup: function(buttonApi) { + rewordButtonApi = buttonApi; + return function() {}; + } + }); + } + }); + + // Initialize TinyMCE AI for Tickets + tinymce.init({ + selector: '.tinymceTicket', + browser_spellcheck: true, + contextmenu: false, + resize: true, + min_height: 200, + max_height: 600, + promotion: false, + branding: false, + menubar: false, + statusbar: false, + toolbar: [ + { name: 'styles', items: ['styles'] }, + { name: 'formatting', items: ['bold', 'italic', 'forecolor'] }, + { name: 'link', items: ['link'] }, + { name: 'lists', items: ['bullist', 'numlist'] }, + { name: 'indentation', items: ['outdent', 'indent'] }, + { name: 'ai', items: ['reword', 'undo', 'redo'] }, + { name: 'custom', items: ['redactButton'] }, + { name: 'code', items: ['code'] }, + ], + mobile: { + menubar: false, + toolbar: [ + { name: 'styles', items: ['styles'] }, + { name: 'formatting', items: ['bold', 'italic', 'forecolor'] }, + { name: 'link', items: ['link'] }, + { name: 'lists', items: ['bullist', 'numlist'] }, + { name: 'indentation', items: ['outdent', 'indent'] }, + { name: 'ai', items: ['reword', 'undo', 'redo'] }, + { name: 'custom', items: ['redactButton'] }, + { name: 'code', items: ['code'] }, + ], + }, + convert_urls: false, + plugins: 'link image lists table code codesample fullscreen autoresize code', + license_key: 'gpl', + setup: function(editor) { + editor.on('init', function() { + window.onbeforeunload = function() { + // If editor is dirty AND not inside a visible modal → warn + const inVisibleModal = editor.getContainer()?.closest('.modal.show'); + if (!inVisibleModal && editor.isDirty()) { + return "You have unsaved changes. Are you sure you want to leave?"; + } + }; + + // When the modal closes, mark editor clean + const modal = editor.getContainer()?.closest('.modal'); + if (modal) { + modal.addEventListener('hidden.bs.modal', () => { + editor.undoManager.clear(); + editor.setDirty(false); + }); + } + }); + + var rewordButtonApi; + + editor.ui.registry.addButton('reword', { + icon: 'ai', + tooltip: 'Reword Text', + onAction: function() { + var content = editor.getContent(); + rewordButtonApi.setEnabled(false); + editor.setProgressState(true); + + fetch('ajax.php?ai_reword', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ text: content }), + }) + .then(response => { + if (!response.ok) throw new Error('Network response was not ok'); + return response.json(); + }) + .then(data => { + editor.undoManager.transact(function() { + editor.setContent(data.rewordedText || 'Error: Could not reword the text.'); + }); + editor.setProgressState(false); + rewordButtonApi.setEnabled(true); + editor.notificationManager.open({ + text: 'Text reworded successfully!', + type: 'success', + timeout: 3000 + }); + }) + .catch(error => { + console.error('Error:', error); + editor.setProgressState(false); + rewordButtonApi.setEnabled(true); + editor.notificationManager.open({ + text: 'An error occurred while rewording the text.', + type: 'error', + timeout: 5000 + }); + }); + }, + onSetup: function(buttonApi) { + rewordButtonApi = buttonApi; + return function() {}; + } + }); + + editor.ui.registry.addButton('redactButton', { + icon: 'permanent-pen', + tooltip: 'Redact Text', + onAction: function() { + var selectedText = editor.selection.getContent({ format: 'text' }); + if (selectedText) { + var newContent = '[REDACTED]'; + editor.selection.setContent(newContent); + } else { + alert('Please select a word to redact'); + } + } + }); + } + }); + + // Initialize TinyMCE Redact-only + tinymce.init({ + selector: '.tinymceRedact', + browser_spellcheck: true, + contextmenu: false, + resize: true, + min_height: 300, + max_height: 600, + promotion: false, + branding: false, + menubar: false, + statusbar: false, + toolbar: 'redactButton', + mobile: { + menubar: false, + plugins: 'autosave lists autolink', + toolbar: 'redactButton' + }, + convert_urls: false, + plugins: 'link image lists table code fullscreen autoresize', + license_key: 'gpl', + setup: function(editor) { + + editor.on('init', function() { + window.onbeforeunload = function() { + // If editor is dirty AND not inside a visible modal → warn + const inVisibleModal = editor.getContainer()?.closest('.modal.show'); + if (!inVisibleModal && editor.isDirty()) { + return "You have unsaved changes. Are you sure you want to leave?"; + } + }; + + // When the modal closes, mark editor clean + const modal = editor.getContainer()?.closest('.modal'); + if (modal) { + modal.addEventListener('hidden.bs.modal', () => { + editor.undoManager.clear(); + editor.setDirty(false); + }); + } + }); + + editor.on('keydown', function(e) { + e.preventDefault(); + }); + + editor.ui.registry.addButton('redactButton', { + icon: 'permanent-pen', + tooltip: 'Redact', + text: 'REDACT', + onAction: function() { + var selectedText = editor.selection.getContent({ format: 'text' }); + if (selectedText) { + var newContent = '[REDACTED]'; + editor.selection.setContent(newContent); + } else { + alert('Please select a word to redact'); + } + } + }); + } + }); + + // DateTime + $('.datetimepicker').datetimepicker(); + + // Data Input Mask + $('[data-mask]').inputmask(); + + // ClipboardJS fix for Bootstrap modals + $.fn.modal.Constructor.prototype._enforceFocus = function() {}; + + // Tooltip + $('button').tooltip({ + trigger: 'click', + placement: 'bottom' + }); + + function setTooltip(btn, message) { + $(btn).tooltip('hide') + .attr('data-original-title', message) + .tooltip('show'); + } + + function hideTooltip(btn) { + setTimeout(function() { + $(btn).tooltip('hide'); + }, 1000); + } + + // Clipboard + var clipboard = new ClipboardJS('.clipboardjs'); + + clipboard.on('success', function(e) { + setTooltip(e.trigger, 'Copied!'); + hideTooltip(e.trigger); + }); + + clipboard.on('error', function(e) { + setTooltip(e.trigger, 'Failed!'); + hideTooltip(e.trigger); + }); + + // Enable Popovers + $(function() { + $('[data-toggle="popover"]').popover(); + }); + + // Data Tables + new DataTable('.dataTables'); +}); diff --git a/normalize_eol.sh b/normalize_eol.sh new file mode 100644 index 00000000..57a64d5c --- /dev/null +++ b/normalize_eol.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# +# ITFlow - one-shot CRLF -> LF normalization. +# +# Converts every tracked text file outside libs/ to LF. Vendored libraries are +# left byte-for-byte as shipped upstream (CONTRIBUTING.md: libs/ is replaced +# wholesale, never edited), and binary assets are skipped outright. +# +# Run once, from the repo root, alongside adding .gitattributes. After that +# .gitattributes keeps new files in line and this script should be a no-op. +# +set -euo pipefail + +cd "$(git rev-parse --show-toplevel)" + +BINARY_RE='\.(png|gif|jpg|jpeg|webp|ico|icc|woff|woff2|ttf|eot|crt|ser|z)$' + +mapfile -t candidates < <(git ls-files | grep -v '^libs/' | grep -viE "$BINARY_RE") + +changed=0 +for f in "${candidates[@]}"; do + [ -f "$f" ] || continue + # only touch files that actually contain a CR + if LC_ALL=C grep -qU $'\r' "$f" 2>/dev/null; then + LC_ALL=C sed -i 's/\r$//' "$f" + changed=$((changed + 1)) + fi +done + +echo "normalized $changed file(s)" diff --git a/scripts/normalize_eol.sh b/scripts/normalize_eol.sh new file mode 100755 index 00000000..57a64d5c --- /dev/null +++ b/scripts/normalize_eol.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# +# ITFlow - one-shot CRLF -> LF normalization. +# +# Converts every tracked text file outside libs/ to LF. Vendored libraries are +# left byte-for-byte as shipped upstream (CONTRIBUTING.md: libs/ is replaced +# wholesale, never edited), and binary assets are skipped outright. +# +# Run once, from the repo root, alongside adding .gitattributes. After that +# .gitattributes keeps new files in line and this script should be a no-op. +# +set -euo pipefail + +cd "$(git rev-parse --show-toplevel)" + +BINARY_RE='\.(png|gif|jpg|jpeg|webp|ico|icc|woff|woff2|ttf|eot|crt|ser|z)$' + +mapfile -t candidates < <(git ls-files | grep -v '^libs/' | grep -viE "$BINARY_RE") + +changed=0 +for f in "${candidates[@]}"; do + [ -f "$f" ] || continue + # only touch files that actually contain a CR + if LC_ALL=C grep -qU $'\r' "$f" 2>/dev/null; then + LC_ALL=C sed -i 's/\r$//' "$f" + changed=$((changed + 1)) + fi +done + +echo "normalized $changed file(s)"