diff --git a/README.md b/README.md index d7271c9a..9c68f846 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ ITFlow is self-hosted. There is a full installation guide in the [docs](https:// 1. Install a LAMP stack (Linux, Apache, MariaDB, PHP) ```sh - sudo apt install git apache2 php libapache2-mod-php php-intl php-mysqli php-curl mariadb-server + sudo apt install git apache2 php libapache2-mod-php php-intl php-imap php-mysqli php-curl mariadb-server ``` 2. Clone the repo ```sh diff --git a/check_login.php b/check_login.php index 9bda9444..2b1a4850 100644 --- a/check_login.php +++ b/check_login.php @@ -16,7 +16,7 @@ if(!isset($config_enable_setup) || $config_enable_setup == 1){ exit; } -if(!$_SESSION['logged']){ +if(!isset($_SESSION['logged']) || !$_SESSION['logged']){ header("Location: login.php"); die; } diff --git a/cron.php b/cron.php index aaca58bb..87f90f4b 100644 --- a/cron.php +++ b/cron.php @@ -9,201 +9,241 @@ $sql_companies = mysqli_query($mysqli,"SELECT * FROM companies, settings WHERE companies.company_id = settings.company_id"); while($row = mysqli_fetch_array($sql_companies)){ - $company_id = $row['company_id']; - $company_name = $row['company_name']; - $company_phone = formatPhoneNumber($row['company_phone']); - $company_email = $row['company_email']; - $company_website = $row['company_website']; - $company_locale = $row['company_locale']; - $config_enable_cron = $row['config_enable_cron']; - $config_invoice_overdue_reminders = $row['config_invoice_overdue_reminders']; - $config_invoice_prefix = $row['config_invoice_prefix']; - $config_invoice_from_email = $row['config_invoice_from_email']; - $config_invoice_from_name = $row['config_invoice_from_name']; - $config_smtp_host = $row['config_smtp_host']; - $config_smtp_username = $row['config_smtp_username']; - $config_smtp_password = $row['config_smtp_password']; - $config_smtp_port = $row['config_smtp_port']; - $config_smtp_encryption = $row['config_smtp_encryption']; - $config_mail_from_email = $row['config_mail_from_email']; - $config_mail_from_name = $row['config_mail_from_name']; - $config_recurring_auto_send_invoice = $row['config_recurring_auto_send_invoice']; + $company_id = $row['company_id']; + $company_name = $row['company_name']; + $company_phone = formatPhoneNumber($row['company_phone']); + $company_email = $row['company_email']; + $company_website = $row['company_website']; + $company_locale = $row['company_locale']; + $config_enable_cron = $row['config_enable_cron']; + $config_invoice_overdue_reminders = $row['config_invoice_overdue_reminders']; + $config_invoice_prefix = $row['config_invoice_prefix']; + $config_invoice_from_email = $row['config_invoice_from_email']; + $config_invoice_from_name = $row['config_invoice_from_name']; + $config_smtp_host = $row['config_smtp_host']; + $config_smtp_username = $row['config_smtp_username']; + $config_smtp_password = $row['config_smtp_password']; + $config_smtp_port = $row['config_smtp_port']; + $config_smtp_encryption = $row['config_smtp_encryption']; + $config_mail_from_email = $row['config_mail_from_email']; + $config_mail_from_name = $row['config_mail_from_name']; + $config_recurring_auto_send_invoice = $row['config_recurring_auto_send_invoice']; - // Tickets - $config_ticket_prefix = $row['config_ticket_prefix']; - $config_ticket_next_number = $row['config_ticket_next_number']; + // Tickets + $config_ticket_prefix = $row['config_ticket_prefix']; + $config_ticket_next_number = $row['config_ticket_next_number']; + $config_ticket_from_name = $row['config_ticket_from_name']; + $config_ticket_from_email = $row['config_ticket_from_email']; - // Set Currency Format - $currency_format = numfmt_create($company_locale, NumberFormatter::CURRENCY); + // Set Currency Format + $currency_format = numfmt_create($company_locale, NumberFormatter::CURRENCY); - if($config_enable_cron == 1){ + if($config_enable_cron == 1){ - //Logging - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Cron', log_action = 'Started', log_description = 'Cron started for $company_name', company_id = $company_id"); + //Logging + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Cron', log_action = 'Started', log_description = 'Cron started for $company_name', company_id = $company_id"); - // GET NOTIFICATIONS + // GET NOTIFICATIONS - // DOMAINS EXPIRING + // DOMAINS EXPIRING - $domainAlertArray = [1,7,14,30,90,120]; + $domainAlertArray = [1,7,14,30,90,120]; - foreach($domainAlertArray as $day){ + foreach($domainAlertArray as $day){ - //Get Domains Expiring - $sql = mysqli_query($mysqli,"SELECT * FROM domains + //Get Domains Expiring + $sql = mysqli_query($mysqli,"SELECT * FROM domains LEFT JOIN clients ON domain_client_id = client_id WHERE domain_expire = CURDATE() + INTERVAL $day DAY AND domains.company_id = $company_id" - ); + ); - while($row = mysqli_fetch_array($sql)){ - $domain_id = $row['domain_id']; - $domain_name = mysqli_real_escape_string($mysqli,$row['domain_name']); - $domain_expire = $row['domain_expire']; - $client_id = $row['client_id']; - $client_name = mysqli_real_escape_string($mysqli,$row['client_name']); + while($row = mysqli_fetch_array($sql)){ + $domain_id = $row['domain_id']; + $domain_name = mysqli_real_escape_string($mysqli,$row['domain_name']); + $domain_expire = $row['domain_expire']; + $client_id = $row['client_id']; + $client_name = mysqli_real_escape_string($mysqli,$row['client_name']); - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Domain', notification = 'Domain $domain_name for $client_name will expire in $day Days on $domain_expire', notification_timestamp = NOW(), notification_client_id = $client_id, company_id = $company_id"); + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Domain', notification = 'Domain $domain_name for $client_name will expire in $day Days on $domain_expire', notification_timestamp = NOW(), notification_client_id = $client_id, company_id = $company_id"); - } + } - } + } - // CERTIFICATES EXPIRING + // CERTIFICATES EXPIRING - $certificateAlertArray = [1,7,14,30,90,120]; + $certificateAlertArray = [1,7,14,30,90,120]; - foreach($certificateAlertArray as $day){ + foreach($certificateAlertArray as $day){ - //Get Certs Expiring - $sql = mysqli_query($mysqli,"SELECT * FROM certificates + //Get Certs Expiring + $sql = mysqli_query($mysqli,"SELECT * FROM certificates LEFT JOIN clients ON certificate_client_id = client_id WHERE certificate_expire = CURDATE() + INTERVAL $day DAY AND certificates.company_id = $company_id" - ); + ); - while($row = mysqli_fetch_array($sql)){ - $certificate_id = $row['certificate_id']; - $certificate_name = mysqli_real_escape_string($mysqli,$row['certificate_name']); - $certificate_domain = $row['certificate_domain']; - $certificate_expire = $row['certificate_expire']; - $client_id = $row['client_id']; - $client_name = mysqli_real_escape_string($mysqli,$row['client_name']); + while($row = mysqli_fetch_array($sql)){ + $certificate_id = $row['certificate_id']; + $certificate_name = mysqli_real_escape_string($mysqli,$row['certificate_name']); + $certificate_domain = $row['certificate_domain']; + $certificate_expire = $row['certificate_expire']; + $client_id = $row['client_id']; + $client_name = mysqli_real_escape_string($mysqli,$row['client_name']); - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Certificate', notification = 'Certificate $certificate_name for $client_name will expire in $day Days on $certificate_expire', notification_timestamp = NOW(), notification_client_id = $client_id, company_id = $company_id"); + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Certificate', notification = 'Certificate $certificate_name for $client_name will expire in $day Days on $certificate_expire', notification_timestamp = NOW(), notification_client_id = $client_id, company_id = $company_id"); - } + } - } + } - // Asset Warranties Expiring + // Asset Warranties Expiring - $warranty_alert_array = [1,7,14,30,90,120]; + $warranty_alert_array = [1,7,14,30,90,120]; - foreach($warranty_alert_array as $day){ + foreach($warranty_alert_array as $day){ - //Get Asset Warranty Expiring - $sql = mysqli_query($mysqli,"SELECT * FROM assets + //Get Asset Warranty Expiring + $sql = mysqli_query($mysqli,"SELECT * FROM assets LEFT JOIN clients ON asset_client_id = client_id WHERE asset_warranty_expire = CURDATE() + INTERVAL $day DAY AND assets.company_id = $company_id" - ); + ); - while($row = mysqli_fetch_array($sql)){ - $asset_id = $row['asset_id']; - $asset_name = mysqli_real_escape_string($mysqli,$row['asset_name']); - $asset_warranty_expire = $row['asset_warranty_expire']; - $client_id = $row['client_id']; - $client_name = mysqli_real_escape_string($mysqli,$row['client_name']); + while($row = mysqli_fetch_array($sql)){ + $asset_id = $row['asset_id']; + $asset_name = mysqli_real_escape_string($mysqli,$row['asset_name']); + $asset_warranty_expire = $row['asset_warranty_expire']; + $client_id = $row['client_id']; + $client_name = mysqli_real_escape_string($mysqli,$row['client_name']); - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Asset', notification = 'Asset $asset_name warranty for $client_name will expire in $day Days on $asset_warranty_expire', notification_timestamp = NOW(), notification_client_id = $client_id, company_id = $company_id"); + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Asset', notification = 'Asset $asset_name warranty for $client_name will expire in $day Days on $asset_warranty_expire', notification_timestamp = NOW(), notification_client_id = $client_id, company_id = $company_id"); - } + } - } - - // Scheduled tickets - - // Get date for search - $today = new DateTime(); - $today_text = $today->format('Y-m-d'); - - // Get scheduled tickets for today - $sql_scheduled_tickets = mysqli_query($mysqli, "SELECT * FROM scheduled_tickets WHERE scheduled_ticket_next_run = '$today_text'"); - - if(mysqli_num_rows($sql_scheduled_tickets) > 0){ - while($row = mysqli_fetch_array($sql_scheduled_tickets)){ - $schedule_id = $row['scheduled_ticket_id']; - $subject = mysqli_real_escape_string($mysqli,$row['scheduled_ticket_subject']); - $details = mysqli_real_escape_string($mysqli,$row['scheduled_ticket_details']); - $priority = $row['scheduled_ticket_priority']; - $frequency = strtolower($row['scheduled_ticket_frequency']); - $created_id = $row['scheduled_ticket_created_by']; - $client_id = $row['scheduled_ticket_client_id']; - $contact_id = $row['scheduled_ticket_contact_id']; - $asset_id = $row['scheduled_ticket_asset_id']; - $company_id = $row['company_id']; - - //Get the next Ticket Number and add 1 for the new ticket number - $ticket_number = $config_ticket_next_number; - $new_config_ticket_next_number = $config_ticket_next_number + 1; - mysqli_query($mysqli,"UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = '$company_id'"); - - // Raise the ticket - mysqli_query($mysqli,"INSERT INTO tickets SET ticket_prefix = '$config_ticket_prefix', ticket_number = $ticket_number, ticket_subject = '$subject', ticket_details = '$details', ticket_priority = '$priority', ticket_status = 'Open', ticket_created_at = NOW(), ticket_created_by = $created_id, ticket_contact_id = $contact_id, ticket_client_id = $client_id, ticket_asset_id = $asset_id, company_id = $company_id"); - - // Logging - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Ticket', log_action = 'Create', log_description = 'System created scheduled $frequency ticket - $subject', log_created_at = NOW(), log_client_id = $client_id, company_id = $company_id, log_user_id = $created_id"); - - // Set the next run date - if($frequency == "weekly"){ - // Note: We seemingly have to initialize a new datetime for each loop to avoid stacking the dates - $now = new DateTime(); - $next_run = date_add($now, date_interval_create_from_date_string('1 week')); - } - elseif($frequency == "monthly"){ - $now = new DateTime(); - $next_run = date_add($now, date_interval_create_from_date_string('1 month')); - } - elseif($frequency == "quarterly"){ - $now = new DateTime(); - $next_run = date_add($now, date_interval_create_from_date_string('3 months')); - } - elseif($frequency == "biannually"){ - $now = new DateTime(); - $next_run = date_add($now, date_interval_create_from_date_string('6 months')); - } - elseif($frequency == "annually"){ - $now = new DateTime(); - $next_run = date_add($now, date_interval_create_from_date_string('12 months')); } - // Update the run date - $next_run = $next_run->format('Y-m-d'); - $a = mysqli_query($mysqli, "UPDATE scheduled_tickets SET scheduled_ticket_next_run = '$next_run' WHERE scheduled_ticket_id = '$schedule_id'"); + // Scheduled tickets - } - } + // Get date for search + $today = new DateTime(); + $today_text = $today->format('Y-m-d'); - // Clean-up ticket views table used for collision detection - mysqli_query($mysqli, "TRUNCATE TABLE ticket_views"); + // Get scheduled tickets for today + $sql_scheduled_tickets = mysqli_query($mysqli, "SELECT * FROM scheduled_tickets WHERE scheduled_ticket_next_run = '$today_text'"); - // Clean-up shared items that have been used - mysqli_query($mysqli, "DELETE FROM shared_items WHERE item_views = item_view_limit"); + if(mysqli_num_rows($sql_scheduled_tickets) > 0){ + while($row = mysqli_fetch_array($sql_scheduled_tickets)){ + $schedule_id = $row['scheduled_ticket_id']; + $subject = mysqli_real_escape_string($mysqli,$row['scheduled_ticket_subject']); + $details = mysqli_real_escape_string($mysqli,$row['scheduled_ticket_details']); + $priority = $row['scheduled_ticket_priority']; + $frequency = strtolower($row['scheduled_ticket_frequency']); + $created_id = $row['scheduled_ticket_created_by']; + $client_id = $row['scheduled_ticket_client_id']; + $contact_id = $row['scheduled_ticket_contact_id']; + $asset_id = $row['scheduled_ticket_asset_id']; + $company_id = $row['company_id']; - // Clean-up shared items that have expired - mysqli_query($mysqli, "DELETE FROM shared_items WHERE item_expire_at < NOW()"); + //Get the next Ticket Number and add 1 for the new ticket number + $ticket_number = $config_ticket_next_number; + $new_config_ticket_next_number = $config_ticket_next_number + 1; + mysqli_query($mysqli,"UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = '$company_id'"); - // Invalidate any password reset links - mysqli_query($mysqli, "UPDATE contacts SET contact_password_reset_token = NULL WHERE contact_archived_at IS NULL"); + // Raise the ticket + mysqli_query($mysqli,"INSERT INTO tickets SET ticket_prefix = '$config_ticket_prefix', ticket_number = $ticket_number, ticket_subject = '$subject', ticket_details = '$details', ticket_priority = '$priority', ticket_status = 'Open', ticket_created_at = NOW(), ticket_created_by = $created_id, ticket_contact_id = $contact_id, ticket_client_id = $client_id, ticket_asset_id = $asset_id, company_id = $company_id"); + $id = mysqli_insert_id($mysqli); - // PAST DUE INVOICE Notifications - //$invoiceAlertArray = [$config_invoice_overdue_reminders]; - $invoiceAlertArray = [30,60,90,120,150,180,210,240,270,300,330,360,390,420,450,480,510,540,570,590,620]; + // Logging + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Ticket', log_action = 'Create', log_description = 'System created scheduled $frequency ticket - $subject', log_created_at = NOW(), log_client_id = $client_id, company_id = $company_id, log_user_id = $created_id"); - foreach($invoiceAlertArray as $day){ + // E-mail client + if (!empty($config_smtp_host) && $config_ticket_client_general_notifications == 1) { - $sql = mysqli_query($mysqli,"SELECT * FROM invoices + // Get contact/ticket/company details + $sql = mysqli_query($mysqli,"SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_subject, company_phone FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + LEFT JOIN companies ON tickets.company_id = companies.company_id + WHERE ticket_id = $id AND tickets.company_id = $company_id"); + $row = mysqli_fetch_array($sql); + + $contact_name = $row['contact_name']; + $contact_email = $row['contact_email']; + $ticket_prefix = $row['ticket_prefix']; + $ticket_number = $row['ticket_number']; + $ticket_subject = $row['ticket_subject']; + $company_phone = formatPhoneNumber($row['company_phone']); + + // Verify contact email is valid + if(filter_var($contact_email, FILTER_VALIDATE_EMAIL)){ + + $subject = "Ticket created - [$ticket_prefix$ticket_number] - $ticket_subject (scheduled)"; + $body = "#--itflow--#

Hello, $contact_name

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

--------------------------------
$details--------------------------------

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

~
$company_name
Support Department
$config_ticket_from_email
$company_phone"; + + $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, + $config_ticket_from_email, $config_ticket_from_name, + $contact_email, $contact_name, + $subject, $body); + + if ($mail !== true) { + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Mail', notification = 'Failed to send email to $contact_email', notification_timestamp = NOW(), company_id = $company_id"); + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Failed to send email to $contact_email regarding $subject. $mail', company_id = $company_id"); + } + + } + } + + // Set the next run date + if($frequency == "weekly"){ + // Note: We seemingly have to initialize a new datetime for each loop to avoid stacking the dates + $now = new DateTime(); + $next_run = date_add($now, date_interval_create_from_date_string('1 week')); + } + elseif($frequency == "monthly"){ + $now = new DateTime(); + $next_run = date_add($now, date_interval_create_from_date_string('1 month')); + } + elseif($frequency == "quarterly"){ + $now = new DateTime(); + $next_run = date_add($now, date_interval_create_from_date_string('3 months')); + } + elseif($frequency == "biannually"){ + $now = new DateTime(); + $next_run = date_add($now, date_interval_create_from_date_string('6 months')); + } + elseif($frequency == "annually"){ + $now = new DateTime(); + $next_run = date_add($now, date_interval_create_from_date_string('12 months')); + } + + // Update the run date + $next_run = $next_run->format('Y-m-d'); + $a = mysqli_query($mysqli, "UPDATE scheduled_tickets SET scheduled_ticket_next_run = '$next_run' WHERE scheduled_ticket_id = '$schedule_id'"); + + } + } + + // Clean-up ticket views table used for collision detection + mysqli_query($mysqli, "TRUNCATE TABLE ticket_views"); + + // Clean-up shared items that have been used + mysqli_query($mysqli, "DELETE FROM shared_items WHERE item_views = item_view_limit"); + + // Clean-up shared items that have expired + mysqli_query($mysqli, "DELETE FROM shared_items WHERE item_expire_at < NOW()"); + + // Invalidate any password reset links + mysqli_query($mysqli, "UPDATE contacts SET contact_password_reset_token = NULL WHERE contact_archived_at IS NULL"); + + // PAST DUE INVOICE Notifications + //$invoiceAlertArray = [$config_invoice_overdue_reminders]; + $invoiceAlertArray = [30,60,90,120,150,180,210,240,270,300,330,360,390,420,450,480,510,540,570,590,620]; + + foreach($invoiceAlertArray as $day){ + + $sql = mysqli_query($mysqli,"SELECT * FROM invoices LEFT JOIN clients ON invoice_client_id = client_id LEFT JOIN contacts ON contact_id = primary_contact WHERE invoice_status NOT LIKE 'Draft' @@ -212,159 +252,159 @@ while($row = mysqli_fetch_array($sql_companies)){ AND DATE_ADD(invoice_due, INTERVAL $day DAY) = CURDATE() AND invoices.company_id = $company_id ORDER BY invoice_number DESC" - ); + ); - while($row = mysqli_fetch_array($sql)){ - $invoice_id = $row['invoice_id']; - $invoice_prefix = $row['invoice_prefix']; - $invoice_number = $row['invoice_number']; - $invoice_status = $row['invoice_status']; - $invoice_date = $row['invoice_date']; - $invoice_due = $row['invoice_due']; - $invoice_url_key = $row['invoice_url_key']; - $invoice_amount = $row['invoice_amount']; - $invoice_currency_code = $row['invoice_currency_code']; - $client_id = $row['client_id']; - $client_name = mysqli_real_escape_string($mysqli,$row['client_name']); - $contact_name = $row['contact_name']; - $contact_email = $row['contact_email']; + while($row = mysqli_fetch_array($sql)){ + $invoice_id = $row['invoice_id']; + $invoice_prefix = $row['invoice_prefix']; + $invoice_number = $row['invoice_number']; + $invoice_status = $row['invoice_status']; + $invoice_date = $row['invoice_date']; + $invoice_due = $row['invoice_due']; + $invoice_url_key = $row['invoice_url_key']; + $invoice_amount = $row['invoice_amount']; + $invoice_currency_code = $row['invoice_currency_code']; + $client_id = $row['client_id']; + $client_name = mysqli_real_escape_string($mysqli,$row['client_name']); + $contact_name = $row['contact_name']; + $contact_email = $row['contact_email']; - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Invoice Overdue', notification = 'Invoice $invoice_prefix$invoice_number for $client_name in the amount of $invoice_amount is overdue by $day days', notification_timestamp = NOW(), notification_client_id = $client_id, company_id = $company_id"); + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Invoice Overdue', notification = 'Invoice $invoice_prefix$invoice_number for $client_name in the amount of $invoice_amount is overdue by $day days', notification_timestamp = NOW(), notification_client_id = $client_id, company_id = $company_id"); - $subject = "Overdue Invoice $invoice_prefix$invoice_number"; - $body = "Hello $contact_name,

According to our records, we have not received payment for invoice $invoice_prefix$invoice_number. Please submit your payment as soon as possible. If you have any questions please contact us at $company_phone. + $subject = "Overdue Invoice $invoice_prefix$invoice_number"; + $body = "Hello $contact_name,

According to our records, we have not received payment for invoice $invoice_prefix$invoice_number. Please submit your payment as soon as possible. If you have any questions please contact us at $company_phone.

Please view the details of the invoice below.

Invoice: $invoice_prefix$invoice_number
Issue Date: $invoice_date
Total: " . numfmt_format_currency($currency_format, $invoice_amount, $invoice_currency_code) . "
Due Date: $invoice_due


To view your invoice click here


~
$company_name
Billing Department
$config_invoice_from_email
$company_phone"; - $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, - $config_invoice_from_email, $config_invoice_from_name, - $contact_email, $contact_name, - $subject, $body); + $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, + $config_invoice_from_email, $config_invoice_from_name, + $contact_email, $contact_name, + $subject, $body); - if ($mail === true) { - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Emailed Overdue Invoice', history_created_at = NOW(), history_invoice_id = $invoice_id, company_id = $company_id"); - } else { - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Failed to send Overdue Invoice', history_created_at = NOW(), history_invoice_id = $invoice_id, company_id = $company_id"); + if ($mail === true) { + mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Emailed Overdue Invoice', history_created_at = NOW(), history_invoice_id = $invoice_id, company_id = $company_id"); + } else { + mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Failed to send Overdue Invoice', history_created_at = NOW(), history_invoice_id = $invoice_id, company_id = $company_id"); + + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Mail', notification = 'Failed to send email to $contact_email', notification_timestamp = NOW(), company_id = $company_id"); + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Failed to send email to $contact_email regarding $subject. $mail', company_id = $company_id"); + } + + } - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Mail', notification = 'Failed to send email to $contact_email', notification_timestamp = NOW(), company_id = $company_id"); - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Failed to send email to $contact_email regarding $subject. $mail', company_id = $company_id"); } - } + //Send Recurring Invoices that match todays date and are active - } + //Loop through all recurring that match today's date and is active + $sql_recurring = mysqli_query($mysqli,"SELECT * FROM recurring LEFT JOIN clients ON client_id = recurring_client_id WHERE recurring_next_date = CURDATE() AND recurring_status = 1 AND recurring.company_id = $company_id"); - //Send Recurring Invoices that match todays date and are active - - //Loop through all recurring that match today's date and is active - $sql_recurring = mysqli_query($mysqli,"SELECT * FROM recurring LEFT JOIN clients ON client_id = recurring_client_id WHERE recurring_next_date = CURDATE() AND recurring_status = 1 AND recurring.company_id = $company_id"); - - while($row = mysqli_fetch_array($sql_recurring)){ - $recurring_id = $row['recurring_id']; - $recurring_scope = $row['recurring_scope']; - $recurring_frequency = $row['recurring_frequency']; - $recurring_status = $row['recurring_status']; - $recurring_last_sent = $row['recurring_last_sent']; - $recurring_next_date = $row['recurring_next_date']; - $recurring_amount = $row['recurring_amount']; - $recurring_currency_code = $row['recurring_currency_code']; - $recurring_note = mysqli_real_escape_string($mysqli,$row['recurring_note']); //Escape SQL - $category_id = $row['recurring_category_id']; - $client_id = $row['recurring_client_id']; - $client_name = mysqli_real_escape_string($mysqli,$row['client_name']); //Escape SQL just in case a name is like Safran's etc - $client_net_terms = $row['client_net_terms']; + while($row = mysqli_fetch_array($sql_recurring)){ + $recurring_id = $row['recurring_id']; + $recurring_scope = $row['recurring_scope']; + $recurring_frequency = $row['recurring_frequency']; + $recurring_status = $row['recurring_status']; + $recurring_last_sent = $row['recurring_last_sent']; + $recurring_next_date = $row['recurring_next_date']; + $recurring_amount = $row['recurring_amount']; + $recurring_currency_code = $row['recurring_currency_code']; + $recurring_note = mysqli_real_escape_string($mysqli,$row['recurring_note']); //Escape SQL + $category_id = $row['recurring_category_id']; + $client_id = $row['recurring_client_id']; + $client_name = mysqli_real_escape_string($mysqli,$row['client_name']); //Escape SQL just in case a name is like Safran's etc + $client_net_terms = $row['client_net_terms']; - //Get the last Invoice Number and add 1 for the new invoice number - $sql_invoice_number = mysqli_query($mysqli,"SELECT * FROM settings WHERE company_id = $company_id"); - $row = mysqli_fetch_array($sql_invoice_number); - $config_invoice_next_number = $row['config_invoice_next_number']; + //Get the last Invoice Number and add 1 for the new invoice number + $sql_invoice_number = mysqli_query($mysqli,"SELECT * FROM settings WHERE company_id = $company_id"); + $row = mysqli_fetch_array($sql_invoice_number); + $config_invoice_next_number = $row['config_invoice_next_number']; - $new_invoice_number = $config_invoice_next_number; - $new_config_invoice_next_number = $config_invoice_next_number + 1; - mysqli_query($mysqli,"UPDATE settings SET config_invoice_next_number = $new_config_invoice_next_number WHERE company_id = $company_id"); + $new_invoice_number = $config_invoice_next_number; + $new_config_invoice_next_number = $config_invoice_next_number + 1; + mysqli_query($mysqli,"UPDATE settings SET config_invoice_next_number = $new_config_invoice_next_number WHERE company_id = $company_id"); - //Generate a unique URL key for clients to access - $url_key = bin2hex(random_bytes(78)); + //Generate a unique URL key for clients to access + $url_key = bin2hex(random_bytes(78)); - mysqli_query($mysqli,"INSERT INTO invoices SET invoice_prefix = '$config_invoice_prefix', invoice_number = $new_invoice_number, invoice_scope = '$recurring_scope', invoice_date = CURDATE(), invoice_due = DATE_ADD(CURDATE(), INTERVAL $client_net_terms day), invoice_amount = '$recurring_amount', invoice_currency_code = '$recurring_currency_code', invoice_note = '$recurring_note', invoice_category_id = $category_id, invoice_status = 'Sent', invoice_url_key = '$url_key', invoice_created_at = NOW(), invoice_client_id = $client_id, company_id = $company_id"); + mysqli_query($mysqli,"INSERT INTO invoices SET invoice_prefix = '$config_invoice_prefix', invoice_number = $new_invoice_number, invoice_scope = '$recurring_scope', invoice_date = CURDATE(), invoice_due = DATE_ADD(CURDATE(), INTERVAL $client_net_terms day), invoice_amount = '$recurring_amount', invoice_currency_code = '$recurring_currency_code', invoice_note = '$recurring_note', invoice_category_id = $category_id, invoice_status = 'Sent', invoice_url_key = '$url_key', invoice_created_at = NOW(), invoice_client_id = $client_id, company_id = $company_id"); - $new_invoice_id = mysqli_insert_id($mysqli); + $new_invoice_id = mysqli_insert_id($mysqli); - //Copy Items from original recurring invoice to new invoice - $sql_invoice_items = mysqli_query($mysqli,"SELECT * FROM invoice_items WHERE item_recurring_id = $recurring_id ORDER BY item_id ASC"); + //Copy Items from original recurring invoice to new invoice + $sql_invoice_items = mysqli_query($mysqli,"SELECT * FROM invoice_items WHERE item_recurring_id = $recurring_id ORDER BY item_id ASC"); - while($row = mysqli_fetch_array($sql_invoice_items)){ - $item_id = $row['item_id']; - $item_name = mysqli_real_escape_string($mysqli,$row['item_name']); //SQL Escape incase of , - $item_description = mysqli_real_escape_string($mysqli,$row['item_description']); //SQL Escape incase of , - $item_quantity = $row['item_quantity']; - $item_price = $row['item_price']; - $item_subtotal = $row['item_subtotal']; - $item_tax = $row['item_tax']; - $item_total = $row['item_total']; - $tax_id = $row['item_tax_id']; + while($row = mysqli_fetch_array($sql_invoice_items)){ + $item_id = $row['item_id']; + $item_name = mysqli_real_escape_string($mysqli,$row['item_name']); //SQL Escape incase of , + $item_description = mysqli_real_escape_string($mysqli,$row['item_description']); //SQL Escape incase of , + $item_quantity = $row['item_quantity']; + $item_price = $row['item_price']; + $item_subtotal = $row['item_subtotal']; + $item_tax = $row['item_tax']; + $item_total = $row['item_total']; + $tax_id = $row['item_tax_id']; - //Insert Items into New Invoice - mysqli_query($mysqli,"INSERT INTO invoice_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = '$item_quantity', item_price = '$item_price', item_subtotal = '$item_subtotal', item_tax = '$item_tax', item_total = '$item_total', item_created_at = NOW(), item_tax_id = $tax_id, item_invoice_id = $new_invoice_id, company_id = $company_id"); + //Insert Items into New Invoice + mysqli_query($mysqli,"INSERT INTO invoice_items SET item_name = '$item_name', item_description = '$item_description', item_quantity = '$item_quantity', item_price = '$item_price', item_subtotal = '$item_subtotal', item_tax = '$item_tax', item_total = '$item_total', item_created_at = NOW(), item_tax_id = $tax_id, item_invoice_id = $new_invoice_id, company_id = $company_id"); - } + } - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Invoice Generated from Recurring!', history_created_at = NOW(), history_invoice_id = $new_invoice_id, company_id = $company_id"); + mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Invoice Generated from Recurring!', history_created_at = NOW(), history_invoice_id = $new_invoice_id, company_id = $company_id"); - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Recurring Sent', notification = 'Recurring Invoice $config_invoice_prefix$new_invoice_number for $client_name Sent', notification_timestamp = NOW(), notification_client_id = $client_id, company_id = $company_id"); + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Recurring Sent', notification = 'Recurring Invoice $config_invoice_prefix$new_invoice_number for $client_name Sent', notification_timestamp = NOW(), notification_client_id = $client_id, company_id = $company_id"); - //Update recurring dates + //Update recurring dates - mysqli_query($mysqli,"UPDATE recurring SET recurring_last_sent = CURDATE(), recurring_next_date = DATE_ADD(CURDATE(), INTERVAL 1 $recurring_frequency), recurring_updated_at = NOW() WHERE recurring_id = $recurring_id"); + mysqli_query($mysqli,"UPDATE recurring SET recurring_last_sent = CURDATE(), recurring_next_date = DATE_ADD(CURDATE(), INTERVAL 1 $recurring_frequency), recurring_updated_at = NOW() WHERE recurring_id = $recurring_id"); - if($config_recurring_auto_send_invoice == 1){ - $sql = mysqli_query($mysqli,"SELECT * FROM invoices + if($config_recurring_auto_send_invoice == 1){ + $sql = mysqli_query($mysqli,"SELECT * FROM invoices LEFT JOIN clients ON invoice_client_id = client_id LEFT JOIN contacts ON contact_id = primary_contact WHERE invoice_id = $new_invoice_id AND invoices.company_id = $company_id" - ); + ); - $row = mysqli_fetch_array($sql); - $invoice_prefix = $row['invoice_prefix']; - $invoice_number = $row['invoice_number']; - $invoice_date = $row['invoice_date']; - $invoice_due = $row['invoice_due']; - $invoice_amount = $row['invoice_amount']; - $invoice_url_key = $row['invoice_url_key']; - $client_id = $row['client_id']; - $client_name = $row['client_name']; - $contact_name = $row['contact_name']; - $contact_email = $row['contact_email']; + $row = mysqli_fetch_array($sql); + $invoice_prefix = $row['invoice_prefix']; + $invoice_number = $row['invoice_number']; + $invoice_date = $row['invoice_date']; + $invoice_due = $row['invoice_due']; + $invoice_amount = $row['invoice_amount']; + $invoice_url_key = $row['invoice_url_key']; + $client_id = $row['client_id']; + $client_name = $row['client_name']; + $contact_name = $row['contact_name']; + $contact_email = $row['contact_email']; - $subject = "Invoice $invoice_prefix$invoice_number"; - $body = "Hello $contact_name,

Please view the details of the invoice below.

Invoice: $invoice_prefix$invoice_number
Issue Date: $invoice_date
Total: " . numfmt_format_currency($currency_format, $invoice_amount, $recurring_currency_code) . "
Due Date: $invoice_due


To view your invoice click here


~
$company_name
Billing Department
$config_invoice_from_email
$company_phone"; + $subject = "Invoice $invoice_prefix$invoice_number"; + $body = "Hello $contact_name,

Please view the details of the invoice below.

Invoice: $invoice_prefix$invoice_number
Issue Date: $invoice_date
Total: " . numfmt_format_currency($currency_format, $invoice_amount, $recurring_currency_code) . "
Due Date: $invoice_due


To view your invoice click here


~
$company_name
Billing Department
$config_invoice_from_email
$company_phone"; - $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, - $config_invoice_from_email, $config_invoice_from_name, - $contact_email, $contact_name, - $subject, $body); + $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, + $config_invoice_from_email, $config_invoice_from_name, + $contact_email, $contact_name, + $subject, $body); - if ($mail === true) { - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Emailed Invoice!', history_created_at = NOW(), history_invoice_id = $new_invoice_id, company_id = $company_id"); - mysqli_query($mysqli,"UPDATE invoices SET invoice_status = 'Sent', invoice_updated_at = NOW(), invoice_client_id = $client_id WHERE invoice_id = $new_invoice_id"); + if ($mail === true) { + mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Emailed Invoice!', history_created_at = NOW(), history_invoice_id = $new_invoice_id, company_id = $company_id"); + mysqli_query($mysqli,"UPDATE invoices SET invoice_status = 'Sent', invoice_updated_at = NOW(), invoice_client_id = $client_id WHERE invoice_id = $new_invoice_id"); - } else { - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Draft', history_description = 'Cron Failed to send Invoice!', history_created_at = NOW(), history_invoice_id = $new_invoice_id, company_id = $company_id"); + } else { + mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Draft', history_description = 'Cron Failed to send Invoice!', history_created_at = NOW(), history_invoice_id = $new_invoice_id, company_id = $company_id"); - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Mail', notification = 'Failed to send email to $contact_email', notification_timestamp = NOW(), company_id = $company_id"); - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Failed to send email to $contact_email regarding $subject. $mail', company_id = $company_id"); - } + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Mail', notification = 'Failed to send email to $contact_email', notification_timestamp = NOW(), company_id = $company_id"); + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Failed to send email to $contact_email regarding $subject. $mail', company_id = $company_id"); + } - } //End if Autosend is on - } //End Recurring Invoices Loop - //Send Alert to inform Cron was run - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Cron', notification = 'Cron.php successfully executed', notification_timestamp = NOW(), company_id = $company_id"); - //Logging - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Cron', log_action = 'Ended', log_description = 'Cron executed successfully for $company_name', company_id = $company_id"); - } //End Cron Check + } //End if Autosend is on + } //End Recurring Invoices Loop + //Send Alert to inform Cron was run + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Cron', notification = 'Cron.php successfully executed', notification_timestamp = NOW(), company_id = $company_id"); + //Logging + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Cron', log_action = 'Ended', log_description = 'Cron executed successfully for $company_name', company_id = $company_id"); + } //End Cron Check } //End Company Loop through diff --git a/cron_ticket_email_parser.php b/cron_ticket_email_parser.php index f4398063..7e5bb7ba 100644 --- a/cron_ticket_email_parser.php +++ b/cron_ticket_email_parser.php @@ -27,13 +27,13 @@ include_once("get_settings.php"); // Check setting enabled if ($config_ticket_email_parse == 0) { - exit("Feature is not enabled - see Settings > Ticketing > Email-to-ticket parsing"); + exit("Feature is not enabled - see Settings > Ticketing > Email-to-ticket parsing"); } // Check IMAP function exists if (!function_exists('imap_open')) { - echo "PHP IMAP extension is not installed, quitting.."; - exit(); + echo "PHP IMAP extension is not installed, quitting.."; + exit(); } // Prepare connection string with encryption (TLS/SSL/) @@ -44,11 +44,11 @@ $imap = imap_open("{{$imap_mailbox}}INBOX", $config_smtp_username, $config_smtp_ // Check connection if (!$imap) { - // Logging - $extended_log_description = var_export(imap_errors(), true); - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Failed to connect to IMAP: $extended_log_description', company_id = $session_company_id"); + // Logging + $extended_log_description = var_export(imap_errors(), true); + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Failed to connect to IMAP: $extended_log_description', company_id = $session_company_id"); - exit("Could not connect to IMAP"); + exit("Could not connect to IMAP"); } // Search for unread (UNSEEN) emails @@ -56,149 +56,151 @@ $emails = imap_search($imap,'UNSEEN'); if ($emails) { - // Sort - rsort($emails); + // Sort + rsort($emails); - // Loop through each email - foreach($emails as $email) { + // Loop through each email + foreach($emails as $email) { - // Get message details - $metadata = imap_fetch_overview($imap, $email,0); // Date, Subject, Size - $header = imap_headerinfo($imap, $email); // To get the From as an email, not a contact name - $message = imap_fetchbody($imap, $email, 1); // Body + // Get message details + $metadata = imap_fetch_overview($imap, $email,0); // Date, Subject, Size + $header = imap_headerinfo($imap, $email); // To get the From as an email, not a contact name + $message = imap_fetchbody($imap, $email, 1); // Body - $from = trim(mysqli_real_escape_string($mysqli, htmlentities(strip_tags($header->from[0]->mailbox . "@" . $header->from[0]->host)))); - $subject = trim(mysqli_real_escape_string($mysqli, htmlentities(strip_tags($metadata[0]->subject)))); - $date = trim(mysqli_real_escape_string($mysqli, htmlentities(strip_tags($metadata[0]->date)))); + $from = trim(mysqli_real_escape_string($mysqli, htmlentities(strip_tags($header->from[0]->mailbox . "@" . $header->from[0]->host)))); + $subject = trim(mysqli_real_escape_string($mysqli, htmlentities(strip_tags($metadata[0]->subject)))); + $date = trim(mysqli_real_escape_string($mysqli, htmlentities(strip_tags($metadata[0]->date)))); - // Check if we can identify a ticket number (in square brackets) - if (preg_match("/\[$config_ticket_prefix\d+\]/", $subject, $ticket_number)) { + // Check if we can identify a ticket number (in square brackets) + if (preg_match("/\[$config_ticket_prefix\d+\]/", $subject, $ticket_number)) { - // Get the actual ticket number (without the brackets) - preg_match('/\d+/', $ticket_number[0], $ticket_number); - $ticket_number = intval($ticket_number[0]); + // Get the actual ticket number (without the brackets) + preg_match('/\d+/', $ticket_number[0], $ticket_number); + $ticket_number = intval($ticket_number[0]); - // Split the email into just the latest reply, with some metadata - // We base this off the string "#--itflow--#" that we prepend the outgoing emails with (similar to the old school --reply above this line--) - $message = explode("#--itflow--#", $message); - $message = nl2br(htmlentities(strip_tags($message[0]))); - $message = "Email from: $from at $date:-

$message"; + // Split the email into just the latest reply, with some metadata + // We base this off the string "#--itflow--#" that we prepend the outgoing emails with (similar to the old school --reply above this line--) + $message = explode("#--itflow--#", $message); + $message = nl2br(htmlentities(strip_tags($message[0]))); + $message = "Email from: $from at $date:-

$message"; - // Lookup the ticket ID to add the reply to (just to check in-case the ID is different from the number). - $ticket_sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_number = '$ticket_number' LIMIT 1"); - $row = mysqli_fetch_array($ticket_sql); - $ticket_id = $row['ticket_id']; - $ticket_reply_contact = $row['ticket_contact_id']; - $ticket_assigned_to = $row['ticket_assigned_to']; - $client_id = $row['ticket_client_id']; - $session_company_id = $row['company_id']; - $ticket_reply_type = 'Client'; // Setting to client as a default value + // Lookup the ticket ID to add the reply to (just to check in-case the ID is different from the number). + $ticket_sql = mysqli_query($mysqli, "SELECT * FROM tickets WHERE ticket_number = '$ticket_number' LIMIT 1"); + $row = mysqli_fetch_array($ticket_sql); + $ticket_id = $row['ticket_id']; + $ticket_reply_contact = $row['ticket_contact_id']; + $ticket_assigned_to = $row['ticket_assigned_to']; + $client_id = $row['ticket_client_id']; + $session_company_id = $row['company_id']; + $ticket_reply_type = 'Client'; // Setting to client as a default value - // Check the ticket ID is valid - if (intval($ticket_id) && $ticket_id !== '0') { + // Check the ticket ID is valid + if (intval($ticket_id) && $ticket_id !== '0') { - // Check that ticket is open - if ($row['ticket_status'] == "Closed") { + // Check that ticket is open + if ($row['ticket_status'] == "Closed") { + + // It's closed - let's notify someone that a client tried to reply + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Ticket', notification = '$from attempted to re-open ticket ID $ticket_id ($config_ticket_prefix$ticket_number) - check inbox manually to see email', notification_timestamp = NOW(), notification_client_id = '$client_id', company_id = '$session_company_id'"); + + } else { + + // Ticket is open, proceed. + + // Check the email matches the contact's email - if it doesn't then mark the reply as internal (so the contact doesn't see it, and the tech can edit/delete if needed) + // Niche edge case - possibly where CC's on an email reply to a ticket? + $contact_sql = mysqli_query($mysqli, "SELECT contact_email FROM contacts WHERE contact_id = '$ticket_reply_contact'"); + $row = mysqli_fetch_array($contact_sql); + if ($from !== $row['contact_email']) { + $ticket_reply_type = 'Internal'; + $ticket_reply_contact = '0'; + $message = "WARNING: Contact email mismatch
$message"; // Add a warning at the start of the message - for the techs benefit (think phishing/scams) + } + + // Sanitize ticket reply + $comment = trim(mysqli_real_escape_string($mysqli,$message)); + + // Add the comment + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$message', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '00:00:00', ticket_reply_created_at = NOW(), ticket_reply_by = '$ticket_reply_contact', ticket_reply_ticket_id = '$ticket_id', company_id = '$session_company_id'"); + + // Update Ticket Last Response Field & set ticket to open as client has replied + mysqli_query($mysqli,"UPDATE tickets SET ticket_status = 'Open', ticket_updated_at = NOW() WHERE ticket_id = $ticket_id AND ticket_client_id = '$client_id' LIMIT 1"); + + echo "Updated existing ticket.
"; + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Ticket', log_action = 'Update', log_description = 'Client contact $from updated ticket $subject via email', log_created_at = NOW(), log_client_id = $client_id, company_id = $session_company_id"); + } + + } - // It's closed - let's notify someone that a client tried to reply - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Ticket', notification = '$from attempted to re-open ticket ID $ticket_id ($config_ticket_prefix$ticket_number) - check inbox manually to see email', notification_timestamp = NOW(), notification_client_id = '$client_id', company_id = '$session_company_id'"); } else { + // Couldn't match this email to an existing ticket - // Ticket is open, proceed. + // Check if we can match the sender to a pre-existing contact + $any_contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from' LIMIT 1"); + $row = mysqli_fetch_array($any_contact_sql); - // Check the email matches the contact's email - if it doesn't then mark the reply as internal (so the contact doesn't see it, and the tech can edit/delete if needed) - // Niche edge case - possibly where CC's on an email reply to a ticket? - $contact_sql = mysqli_query($mysqli, "SELECT contact_email FROM contacts WHERE contact_id = '$ticket_reply_contact'"); - $row = mysqli_fetch_array($contact_sql); - if ($from !== $row['contact_email']) { - $ticket_reply_type = 'Internal'; - $ticket_reply_contact = '0'; - $message = "WARNING: Contact email mismatch
$message"; // Add a warning at the start of the message - for the techs benefit (think phishing/scams) - } + $contact_name = $row['contact_name']; + $contact_id = $row['contact_id']; + $contact_email = $row['contact_email']; + $client_id = $row['contact_client_id']; + $session_company_id = $row['company_id']; - // Sanitize ticket reply - $comment = trim(mysqli_real_escape_string($mysqli,$message)); + if ($from == $contact_email) { - // Add the comment - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$message', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '00:00:00', ticket_reply_created_at = NOW(), ticket_reply_by = '$ticket_reply_contact', ticket_reply_ticket_id = '$ticket_id', company_id = '$session_company_id'"); + // Prep ticket details + $message = nl2br(htmlentities(strip_tags($message))); + $message = trim(mysqli_real_escape_string($mysqli,"Email from: $from at $date:-

$message")); - // Update Ticket Last Response Field & set ticket to open as client has replied - mysqli_query($mysqli,"UPDATE tickets SET ticket_status = 'Open', ticket_updated_at = NOW() WHERE ticket_id = $ticket_id AND ticket_client_id = '$client_id' LIMIT 1"); + // Get the next Ticket Number and add 1 for the new ticket number + $ticket_number = $config_ticket_next_number; + $new_config_ticket_next_number = $config_ticket_next_number + 1; + mysqli_query($mysqli,"UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = $session_company_id"); + + mysqli_query($mysqli,"INSERT INTO tickets SET ticket_prefix = '$config_ticket_prefix', ticket_number = $ticket_number, ticket_subject = '$subject', ticket_details = '$message', ticket_priority = 'Low', ticket_status = 'Open', ticket_created_at = NOW(), ticket_created_by = '0', ticket_contact_id = $contact_id, ticket_client_id = $client_id, company_id = $session_company_id"); + $id = mysqli_insert_id($mysqli); + + // Logging + echo "Created new ticket.
"; + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Ticket', log_action = 'Create', log_description = 'Client contact $from created ticket $subject via email', log_created_at = NOW(), log_client_id = $client_id, company_id = $session_company_id"); + + // Get company name & phone + $sql = mysqli_query($mysqli,"SELECT company_name, company_phone FROM companies WHERE company_id = $session_company_id"); + $row = mysqli_fetch_array($sql); + $company_phone = formatPhoneNumber($row['company_phone']); + $session_company_name = $row['company_name']; + + + // E-mail client notification that ticket has been created + if ($config_ticket_client_general_notifications == 1) { + + $email_subject = "Ticket created - [$config_ticket_prefix$ticket_number] - $subject"; + $email_body = "#--itflow--#

Hello, $contact_name

Thank you for your email. A ticket regarding \"$subject\" has been automatically created for you.

Ticket: $config_ticket_prefix$ticket_number
Subject: $subject
Status: Open
https://$config_base_url/portal/ticket.php?id=$id

~
$session_company_name
Support Department
$config_ticket_from_email
$company_phone"; + + $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, + $config_ticket_from_email, $config_ticket_from_name, + $contact_email, $contact_name, + $email_subject, $email_body); + + if ($mail !== true) { + mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Mail', notification = 'Failed to send email to $contact_email', notification_timestamp = NOW(), company_id = $session_company_id"); + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Failed to send email to $contact_email regarding $subject. $mail', company_id = $session_company_id"); + } + + } + + + } else { + + // Couldn't match this against a specific client contact -- do nothing for now + // In the future, we'll try to match on client domain + // or even log this to an inbox in the ITFlow portal or something to allow a new contact/ticket to be created manually + + } - echo "Updated existing ticket.
"; - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Ticket', log_action = 'Update', log_description = 'Client contact $from updated ticket $subject via email', log_created_at = NOW(), log_client_id = $client_id, company_id = $session_company_id"); } - } - - - } else { - // Couldn't match this email to an existing ticket - - // Check if we can match the sender to a pre-existing contact - $any_contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from' LIMIT 1"); - $row = mysqli_fetch_array($any_contact_sql); - - $contact_name = $row['contact_name']; - $contact_id = $row['contact_id']; - $contact_email = $row['contact_email']; - $client_id = $row['contact_client_id']; - $session_company_id = $row['company_id']; - - if ($from == $contact_email) { - - // Prep ticket details - $message = nl2br(htmlentities(strip_tags($message))); - $message = trim(mysqli_real_escape_string($mysqli,"Email from: $from at $date:-

$message")); - - // Get the next Ticket Number and add 1 for the new ticket number - $ticket_number = $config_ticket_next_number; - $new_config_ticket_next_number = $config_ticket_next_number + 1; - mysqli_query($mysqli,"UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = $session_company_id"); - - mysqli_query($mysqli,"INSERT INTO tickets SET ticket_prefix = '$config_ticket_prefix', ticket_number = $ticket_number, ticket_subject = '$subject', ticket_details = '$message', ticket_priority = 'Low', ticket_status = 'Open', ticket_created_at = NOW(), ticket_created_by = '0', ticket_contact_id = $contact_id, ticket_client_id = $client_id, company_id = $session_company_id"); - $id = mysqli_insert_id($mysqli); - - // Logging - echo "Created new ticket.
"; - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Ticket', log_action = 'Create', log_description = 'Client contact $from created ticket $subject via email', log_created_at = NOW(), log_client_id = $client_id, company_id = $session_company_id"); - - // Get company name & phone - $sql = mysqli_query($mysqli,"SELECT company_name, company_phone FROM companies WHERE company_id = $session_company_id"); - $row = mysqli_fetch_array($sql); - $company_phone = formatPhoneNumber($row['company_phone']); - $session_company_name = $row['company_name']; - - - // E-mail client notification that ticket has been created - - $email_subject = "Ticket created - [$config_ticket_prefix$ticket_number] - $subject"; - $email_body = "#--itflow--#

Hello, $contact_name

Thank you for your email. A ticket regarding \"$subject\" has been automatically created for you.

Ticket: $config_ticket_prefix$ticket_number
Subject: $subject
Status: Open
https://$config_base_url/portal/ticket.php?id=$id

~
$session_company_name
Support Department
$config_ticket_from_email
$company_phone"; - - $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, - $config_ticket_from_email, $config_ticket_from_name, - $contact_email, $contact_name, - $email_subject, $email_body); - - if ($mail !== true) { - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Mail', notification = 'Failed to send email to $contact_email', notification_timestamp = NOW(), company_id = $session_company_id"); - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Mail', log_action = 'Error', log_description = 'Failed to send email to $contact_email regarding $subject. $mail', company_id = $session_company_id"); - } - - - - } else { - - // Couldn't match this against a specific client contact -- do nothing for now - // In the future, we'll try to match on client domain - // or even log this to an inbox in the ITFlow portal or something to allow a new contact/ticket to be created manually - - } } - - } - } \ No newline at end of file diff --git a/database_updates.php b/database_updates.php index 0156adfb..d9b64ca0 100644 --- a/database_updates.php +++ b/database_updates.php @@ -8,341 +8,341 @@ // Check if our database versions are defined // If undefined, the file is probably being accessed directly rather than called via post.php?update_db if(!defined("LATEST_DATABASE_VERSION") || !defined("CURRENT_DATABASE_VERSION") || !isset($mysqli)){ - echo "Cannot access this file directly."; - exit(); + echo "Cannot access this file directly."; + exit(); } // Check if we need an update if(LATEST_DATABASE_VERSION > CURRENT_DATABASE_VERSION){ - // We need updates! + // We need updates! - if(CURRENT_DATABASE_VERSION == '0.0.1'){ - // Insert queries here required to update to DB version 0.0.2 + if(CURRENT_DATABASE_VERSION == '0.0.1'){ + // Insert queries here required to update to DB version 0.0.2 - mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_module_enable_itdoc` TINYINT(1) DEFAULT 1 AFTER `config_backup_path`"); - mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_module_enable_ticketing` TINYINT(1) DEFAULT 1 AFTER `config_module_enable_itdoc`"); - mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_module_enable_accounting` TINYINT(1) DEFAULT 1 AFTER `config_module_enable_ticketing`"); + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_module_enable_itdoc` TINYINT(1) DEFAULT 1 AFTER `config_backup_path`"); + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_module_enable_ticketing` TINYINT(1) DEFAULT 1 AFTER `config_module_enable_itdoc`"); + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_module_enable_accounting` TINYINT(1) DEFAULT 1 AFTER `config_module_enable_ticketing`"); - // Update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.2'"); - } - - if(CURRENT_DATABASE_VERSION == '0.0.2'){ - // Insert queries here required to update to DB version 0.0.3 - - // Add document content raw column & index - mysqli_query($mysqli, "ALTER TABLE `documents` ADD `document_content_raw` LONGTEXT NOT NULL AFTER `document_content`, ADD FULLTEXT `document_content_raw` (`document_content_raw`)"); - - // Populate content raw column with existing document data - $documents_sql = mysqli_query($mysqli, "SELECT * FROM `documents`"); - while($row = mysqli_fetch_array($documents_sql)){ - $id = $row['document_id']; - $name = $row['document_name']; - $content = $row['document_content']; - $content_raw = trim(mysqli_real_escape_string($mysqli, strip_tags($name . " " . str_replace("<", " <", $content)))); - - mysqli_query($mysqli, "UPDATE `documents` SET `document_content_raw` = '$content_raw' WHERE `document_id` = '$id'"); + // Update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.2'"); } - // Add API key client column - mysqli_query($mysqli, "ALTER TABLE `api_keys` ADD `api_key_client_id` INT NOT NULL DEFAULT '0' AFTER `api_key_expire`"); + if(CURRENT_DATABASE_VERSION == '0.0.2'){ + // Insert queries here required to update to DB version 0.0.3 - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.3'"); - } + // Add document content raw column & index + mysqli_query($mysqli, "ALTER TABLE `documents` ADD `document_content_raw` LONGTEXT NOT NULL AFTER `document_content`, ADD FULLTEXT `document_content_raw` (`document_content_raw`)"); - if(CURRENT_DATABASE_VERSION == '0.0.3'){ - // Insert queries here required to update to DB version 0.0.4 - // mysqli_query($mysqli, "ALTER TABLE ....."); + // Populate content raw column with existing document data + $documents_sql = mysqli_query($mysqli, "SELECT * FROM `documents`"); + while($row = mysqli_fetch_array($documents_sql)){ + $id = $row['document_id']; + $name = $row['document_name']; + $content = $row['document_content']; + $content_raw = trim(mysqli_real_escape_string($mysqli, strip_tags($name . " " . str_replace("<", " <", $content)))); - // Update all tables updated/modified fields to be automatic + mysqli_query($mysqli, "UPDATE `documents` SET `document_content_raw` = '$content_raw' WHERE `document_id` = '$id'"); + } - mysqli_query($mysqli, "ALTER TABLE `accounts` CHANGE `account_created_at` `account_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `account_updated_at` `account_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL;"); + // Add API key client column + mysqli_query($mysqli, "ALTER TABLE `api_keys` ADD `api_key_client_id` INT NOT NULL DEFAULT '0' AFTER `api_key_expire`"); - mysqli_query($mysqli, "ALTER TABLE `api_keys` CHANGE `api_key_created_at` `api_key_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - - mysqli_query($mysqli, "ALTER TABLE `assets` CHANGE `asset_created_at` `asset_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `asset_updated_at` `asset_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL;"); - - mysqli_query($mysqli, "ALTER TABLE `calendars` CHANGE `calendar_created_at` `calendar_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `calendar_updated_at` `calendar_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `campaigns` CHANGE `campaign_created_at` `campaign_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `campaign_updated_at` `campaign_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `campaign_messages` CHANGE `message_created_at` `message_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `message_updated_at` `message_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `categories` CHANGE `category_created_at` `category_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `category_updated_at` `category_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `certificates` CHANGE `certificate_created_at` `certificate_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `certificate_updated_at` `certificate_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `clients` CHANGE `client_created_at` `client_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `client_updated_at` `client_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `companies` CHANGE `company_created_at` `company_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `company_updated_at` `company_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `contacts` CHANGE `contact_created_at` `contact_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `contact_updated_at` `contact_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `contracts` CHANGE `contract_created_at` `contract_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `contract_updated_at` `contract_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `custom_links` CHANGE `custom_link_created_at` `custom_link_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - - mysqli_query($mysqli, "ALTER TABLE `departments` CHANGE `department_created_at` `department_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `department_updated_at` `department_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `documents` CHANGE `document_created_at` `document_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `document_updated_at` `document_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `domains` CHANGE `domain_created_at` `domain_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `domain_updated_at` `domain_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `events` CHANGE `event_created_at` `event_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `event_updated_at` `event_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `expenses` CHANGE `expense_created_at` `expense_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `expense_updated_at` `expense_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `files` CHANGE `file_created_at` `file_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `file_updated_at` `file_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL;"); - - mysqli_query($mysqli, "ALTER TABLE `history` CHANGE `history_created_at` `history_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - - mysqli_query($mysqli, "ALTER TABLE `invoices` CHANGE `invoice_created_at` `invoice_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `invoice_updated_at` `invoice_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `invoice_items` CHANGE `item_created_at` `item_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `item_updated_at` `item_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `locations` CHANGE `location_created_at` `location_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `location_updated_at` `location_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `logins` CHANGE `login_created_at` `login_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `login_updated_at` `login_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `logs` CHANGE `log_created_at` `log_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - - mysqli_query($mysqli, "ALTER TABLE `networks` CHANGE `network_created_at` `network_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `network_updated_at` `network_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `notifications` CHANGE `notification_timestamp` `notification_timestamp` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - - mysqli_query($mysqli, "ALTER TABLE `payments` CHANGE `payment_created_at` `payment_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `payment_updated_at` `payment_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `products` CHANGE `product_created_at` `product_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `product_updated_at` `product_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `quotes` CHANGE `quote_created_at` `quote_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `quote_updated_at` `quote_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `records` CHANGE `record_created_at` `record_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `record_updated_at` `record_updated_at` DATETIME on update CURRENT_TIMESTAMP NOT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `recurring` CHANGE `recurring_created_at` `recurring_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `recurring_updated_at` `recurring_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `scheduled_tickets` CHANGE `scheduled_ticket_created_at` `scheduled_ticket_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `scheduled_ticket_updated_at` `scheduled_ticket_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `services` CHANGE `service_created_at` `service_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `service_updated_at` `service_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `shared_items` CHANGE `item_created_at` `item_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - - mysqli_query($mysqli, "ALTER TABLE `software` CHANGE `software_created_at` `software_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `software_updated_at` `software_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `tags` CHANGE `tag_created_at` `tag_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `tag_updated_at` `tag_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `taxes` CHANGE `tax_created_at` `tax_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `tax_updated_at` `tax_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `tickets` CHANGE `ticket_created_at` `ticket_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `ticket_updated_at` `ticket_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `ticket_replies` CHANGE `ticket_reply_created_at` `ticket_reply_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `ticket_reply_updated_at` `ticket_reply_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `transfers` CHANGE `transfer_created_at` `transfer_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `transfer_updated_at` `transfer_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `trips` CHANGE `trip_created_at` `trip_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `trip_updated_at` `trip_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `users` CHANGE `user_created_at` `user_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `user_updated_at` `user_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - mysqli_query($mysqli, "ALTER TABLE `vendors` CHANGE `vendor_created_at` `vendor_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `vendor_updated_at` `vendor_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE settings SET config_current_database_version = '0.0.4'"); - - } - - if(CURRENT_DATABASE_VERSION == '0.0.4'){ - // Queries here required to update to DB version 0.0.5 - - mysqli_query($mysqli, "ALTER TABLE `assets` DROP `asset_meshcentral_id`;"); - mysqli_query($mysqli, "ALTER TABLE `clients` DROP `client_meshcentral_group`;"); - mysqli_query($mysqli, "ALTER TABLE `settings` DROP `config_meshcentral_uri`, DROP `config_meshcentral_user`, DROP `config_meshcentral_secret`;"); - - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.5'"); - } - - if(CURRENT_DATABASE_VERSION == '0.0.5'){ - // Insert queries here required to update to DB version 0.0.6 - - mysqli_query($mysqli, "UPDATE documents SET document_folder_id = 0"); - - mysqli_query($mysqli, "DROP TABLE documents_tagged"); - mysqli_query($mysqli, "DROP TABLE document_tags"); - - - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE settings SET config_current_database_version = '0.0.6'"); - } - - if(CURRENT_DATABASE_VERSION == '0.0.6'){ - // Insert queries here required to update to DB version 0.0.7 - mysqli_query($mysqli, "ALTER TABLE contacts ADD contact_department VARCHAR(200) NULL AFTER contact_title"); - mysqli_query($mysqli, "DROP TABLE departments"); - mysqli_query($mysqli, "ALTER TABLE contacts DROP contact_department_id"); - - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.7'"); - } - - if(CURRENT_DATABASE_VERSION == '0.0.7'){ - // Insert queries here required to update to DB version 0.0.8 - - // Add contact_department column to tables without it (fresh installs) - this will cause an error if it already exists so catch and discard it - try{ - mysqli_query($mysqli, "ALTER TABLE contacts ADD contact_department VARCHAR(200) NULL AFTER contact_title"); - } catch(Exception $e) { - // Nothing + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.3'"); } - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.8'"); - } + if(CURRENT_DATABASE_VERSION == '0.0.3'){ + // Insert queries here required to update to DB version 0.0.4 + // mysqli_query($mysqli, "ALTER TABLE ....."); - if(CURRENT_DATABASE_VERSION == '0.0.8'){ - // Insert queries here required to update to DB version 0.0.9 + // Update all tables updated/modified fields to be automatic - mysqli_query($mysqli, "ALTER TABLE `revenues` CHANGE `revenue_created_at` `revenue_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `revenue_updated_at` `revenue_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + mysqli_query($mysqli, "ALTER TABLE `accounts` CHANGE `account_created_at` `account_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `account_updated_at` `account_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL;"); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.9'"); - } + mysqli_query($mysqli, "ALTER TABLE `api_keys` CHANGE `api_key_created_at` `api_key_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - if(CURRENT_DATABASE_VERSION == '0.0.9'){ - // Insert queries here required to update to DB version 0.0.9 - // Remove unused tables - mysqli_query($mysqli, "DROP TABLE contracts"); - mysqli_query($mysqli, "DROP TABLE messages"); - mysqli_query($mysqli, "DROP TABLE roles"); + mysqli_query($mysqli, "ALTER TABLE `assets` CHANGE `asset_created_at` `asset_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `asset_updated_at` `asset_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL;"); - //Remove updated at as API keys can only be added or revoked - mysqli_query($mysqli, "ALTER TABLE `api_keys` DROP `api_key_updated_at`"); + mysqli_query($mysqli, "ALTER TABLE `calendars` CHANGE `calendar_created_at` `calendar_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `calendar_updated_at` `calendar_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.0'"); - } + mysqli_query($mysqli, "ALTER TABLE `campaigns` CHANGE `campaign_created_at` `campaign_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `campaign_updated_at` `campaign_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - if(CURRENT_DATABASE_VERSION == '0.1.0'){ - // Insert queries here required to update to DB version 0.1.1 - // Logs don't get archived - mysqli_query($mysqli, "ALTER TABLE `logs` DROP `log_archived_at`"); + mysqli_query($mysqli, "ALTER TABLE `campaign_messages` CHANGE `message_created_at` `message_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `message_updated_at` `message_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - // Assets will eventualy have file associatons which could include a receipt. - mysqli_query($mysqli, "ALTER TABLE `assets` DROP `asset_reciept`"); + mysqli_query($mysqli, "ALTER TABLE `categories` CHANGE `category_created_at` `category_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `category_updated_at` `category_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - mysqli_query($mysqli, "ALTER TABLE `campaign_messages` DROP `message_updated_at`"); - // This will be a seperate table eventually called contact_documents because contact can have several documents - mysqli_query($mysqli, "ALTER TABLE `documents` DROP `document_contact_id`"); + mysqli_query($mysqli, "ALTER TABLE `certificates` CHANGE `certificate_created_at` `certificate_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `certificate_updated_at` `certificate_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - mysqli_query($mysqli, "ALTER TABLE `expenses` DROP `expense_asset_id`"); - mysqli_query($mysqli, "ALTER TABLE `files` DROP `file_contact_id`"); - mysqli_query($mysqli, "ALTER TABLE `history` DROP `history_archived_at`"); + mysqli_query($mysqli, "ALTER TABLE `clients` CHANGE `client_created_at` `client_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `client_updated_at` `client_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.1'"); - } + mysqli_query($mysqli, "ALTER TABLE `companies` CHANGE `company_created_at` `company_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `company_updated_at` `company_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - if(CURRENT_DATABASE_VERSION == '0.1.1'){ - // Insert queries here required to update to DB version 0.1.2 - // Create Many to Many Relationship tables for Assets, Contacts, Software and Vendors + mysqli_query($mysqli, "ALTER TABLE `contacts` CHANGE `contact_created_at` `contact_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `contact_updated_at` `contact_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - mysqli_query($mysqli, "CREATE TABLE `asset_documents` (`asset_id` int(11) NOT NULL,`document_id` int(11) NOT NULL, PRIMARY KEY (`asset_id`,`document_id`))"); - mysqli_query($mysqli, "CREATE TABLE `asset_logins` (`asset_id` int(11) NOT NULL,`login_id` int(11) NOT NULL, PRIMARY KEY (`asset_id`,`login_id`))"); - mysqli_query($mysqli, "CREATE TABLE `asset_files` (`asset_id` int(11) NOT NULL,`file_id` int(11) NOT NULL, PRIMARY KEY (`asset_id`,`file_id`))"); + mysqli_query($mysqli, "ALTER TABLE `contracts` CHANGE `contract_created_at` `contract_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `contract_updated_at` `contract_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - mysqli_query($mysqli, "CREATE TABLE `contact_documents` (`contact_id` int(11) NOT NULL,`document_id` int(11) NOT NULL, PRIMARY KEY (`contact_id`,`document_id`))"); - mysqli_query($mysqli, "CREATE TABLE `contact_logins` (`contact_id` int(11) NOT NULL,`login_id` int(11) NOT NULL, PRIMARY KEY (`contact_id`,`login_id`))"); - mysqli_query($mysqli, "CREATE TABLE `contact_files` (`contact_id` int(11) NOT NULL,`file_id` int(11) NOT NULL, PRIMARY KEY (`contact_id`,`file_id`))"); + mysqli_query($mysqli, "ALTER TABLE `custom_links` CHANGE `custom_link_created_at` `custom_link_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - mysqli_query($mysqli, "CREATE TABLE `software_documents` (`software_id` int(11) NOT NULL,`document_id` int(11) NOT NULL, PRIMARY KEY (`software_id`,`document_id`))"); - mysqli_query($mysqli, "CREATE TABLE `software_logins` (`software_id` int(11) NOT NULL,`login_id` int(11) NOT NULL, PRIMARY KEY (`software_id`,`login_id`))"); - mysqli_query($mysqli, "CREATE TABLE `software_files` (`software_id` int(11) NOT NULL,`file_id` int(11) NOT NULL, PRIMARY KEY (`software_id`,`file_id`))"); + mysqli_query($mysqli, "ALTER TABLE `departments` CHANGE `department_created_at` `department_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `department_updated_at` `department_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - mysqli_query($mysqli, "CREATE TABLE `vendor_documents` (`vendor_id` int(11) NOT NULL,`document_id` int(11) NOT NULL, PRIMARY KEY (`vendor_id`,`document_id`))"); - mysqli_query($mysqli, "CREATE TABLE `vendor_logins` (`vendor_id` int(11) NOT NULL,`login_id` int(11) NOT NULL, PRIMARY KEY (`vendor_id`,`login_id`))"); - mysqli_query($mysqli, "CREATE TABLE `vendor_files` (`vendor_id` int(11) NOT NULL,`file_id` int(11) NOT NULL, PRIMARY KEY (`vendor_id`,`file_id`))"); + mysqli_query($mysqli, "ALTER TABLE `documents` CHANGE `document_created_at` `document_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `document_updated_at` `document_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.2'"); - } + mysqli_query($mysqli, "ALTER TABLE `domains` CHANGE `domain_created_at` `domain_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `domain_updated_at` `domain_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - if(CURRENT_DATABASE_VERSION == '0.1.2'){ - // Insert queries here required to update to DB version 0.1.3 - mysqli_query($mysqli, "ALTER TABLE `logs` ADD `log_entity_id` INT NOT NULL DEFAULT '0' AFTER `log_user_id`"); + mysqli_query($mysqli, "ALTER TABLE `events` CHANGE `event_created_at` `event_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `event_updated_at` `event_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.3'"); - } + mysqli_query($mysqli, "ALTER TABLE `expenses` CHANGE `expense_created_at` `expense_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `expense_updated_at` `expense_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - if(CURRENT_DATABASE_VERSION == '0.1.3'){ - // Insert queries here required to update to DB version 0.1.4 - mysqli_query($mysqli, "ALTER TABLE assets ADD asset_status VARCHAR(200) NULL AFTER asset_mac"); + mysqli_query($mysqli, "ALTER TABLE `files` CHANGE `file_created_at` `file_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `file_updated_at` `file_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL;"); - ///Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.4'"); - } + mysqli_query($mysqli, "ALTER TABLE `history` CHANGE `history_created_at` `history_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - if(CURRENT_DATABASE_VERSION == '0.1.4'){ - // Insert queries here required to update to DB version 0.1.5 - mysqli_query($mysqli, "ALTER TABLE `domains` ADD `domain_txt` TEXT NULL DEFAULT NULL AFTER `domain_mail_servers`"); + mysqli_query($mysqli, "ALTER TABLE `invoices` CHANGE `invoice_created_at` `invoice_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `invoice_updated_at` `invoice_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.5'"); - } + mysqli_query($mysqli, "ALTER TABLE `invoice_items` CHANGE `item_created_at` `item_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `item_updated_at` `item_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - if(CURRENT_DATABASE_VERSION == '0.1.5'){ - // Insert queries here required to update to DB version 0.1.6 - // Remove Mailing List Tables - mysqli_query($mysqli, "DROP TABLE campaigns"); - mysqli_query($mysqli, "DROP TABLE campaign_messages"); + mysqli_query($mysqli, "ALTER TABLE `locations` CHANGE `location_created_at` `location_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `location_updated_at` `location_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.6'"); - } + mysqli_query($mysqli, "ALTER TABLE `logins` CHANGE `login_created_at` `login_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `login_updated_at` `login_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - if(CURRENT_DATABASE_VERSION == '0.1.6'){ - // Insert queries here required to update to DB version 0.1.7 - //Remove custom links - mysqli_query($mysqli, "DROP TABLE custom_links"); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.7'"); - } + mysqli_query($mysqli, "ALTER TABLE `logs` CHANGE `log_created_at` `log_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - if(CURRENT_DATABASE_VERSION == '0.1.7'){ - // Insert queries here required to update to DB version 0.1.8 - mysqli_query($mysqli, "ALTER TABLE `settings` DROP `config_backup_enable`"); - mysqli_query($mysqli, "ALTER TABLE `settings` DROP `config_backup_path`"); + mysqli_query($mysqli, "ALTER TABLE `networks` CHANGE `network_created_at` `network_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `network_updated_at` `network_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.8'"); - } + mysqli_query($mysqli, "ALTER TABLE `notifications` CHANGE `notification_timestamp` `notification_timestamp` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); - if(CURRENT_DATABASE_VERSION == '0.1.8'){ - // Insert queries here required to update to DB version 0.1.9 - mysqli_query($mysqli, "ALTER TABLE `settings` DROP `config_base_url`"); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.9'"); - } + mysqli_query($mysqli, "ALTER TABLE `payments` CHANGE `payment_created_at` `payment_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `payment_updated_at` `payment_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - if(CURRENT_DATABASE_VERSION == '0.1.9'){ - // Insert queries here required to update to DB version 0.2.0 - // Allow contacts to reset their portal password - mysqli_query($mysqli, "ALTER TABLE contacts ADD contact_password_reset_token VARCHAR(200) NULL DEFAULT NULL AFTER contact_password_hash"); + mysqli_query($mysqli, "ALTER TABLE `products` CHANGE `product_created_at` `product_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `product_updated_at` `product_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.0'"); - } + mysqli_query($mysqli, "ALTER TABLE `quotes` CHANGE `quote_created_at` `quote_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `quote_updated_at` `quote_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); - if(CURRENT_DATABASE_VERSION == '0.2.0'){ - //Insert queries here required to update to DB version 0.2.1 + mysqli_query($mysqli, "ALTER TABLE `records` CHANGE `record_created_at` `record_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `record_updated_at` `record_updated_at` DATETIME on update CURRENT_TIMESTAMP NOT NULL; "); - mysqli_query($mysqli, "ALTER TABLE `vendors` + mysqli_query($mysqli, "ALTER TABLE `recurring` CHANGE `recurring_created_at` `recurring_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `recurring_updated_at` `recurring_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `scheduled_tickets` CHANGE `scheduled_ticket_created_at` `scheduled_ticket_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `scheduled_ticket_updated_at` `scheduled_ticket_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `services` CHANGE `service_created_at` `service_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `service_updated_at` `service_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `shared_items` CHANGE `item_created_at` `item_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP; "); + + mysqli_query($mysqli, "ALTER TABLE `software` CHANGE `software_created_at` `software_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `software_updated_at` `software_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `tags` CHANGE `tag_created_at` `tag_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `tag_updated_at` `tag_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `taxes` CHANGE `tax_created_at` `tax_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `tax_updated_at` `tax_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `tickets` CHANGE `ticket_created_at` `ticket_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `ticket_updated_at` `ticket_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `ticket_replies` CHANGE `ticket_reply_created_at` `ticket_reply_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `ticket_reply_updated_at` `ticket_reply_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `transfers` CHANGE `transfer_created_at` `transfer_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `transfer_updated_at` `transfer_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `trips` CHANGE `trip_created_at` `trip_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `trip_updated_at` `trip_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `users` CHANGE `user_created_at` `user_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `user_updated_at` `user_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + mysqli_query($mysqli, "ALTER TABLE `vendors` CHANGE `vendor_created_at` `vendor_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `vendor_updated_at` `vendor_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE settings SET config_current_database_version = '0.0.4'"); + + } + + if(CURRENT_DATABASE_VERSION == '0.0.4'){ + // Queries here required to update to DB version 0.0.5 + + mysqli_query($mysqli, "ALTER TABLE `assets` DROP `asset_meshcentral_id`;"); + mysqli_query($mysqli, "ALTER TABLE `clients` DROP `client_meshcentral_group`;"); + mysqli_query($mysqli, "ALTER TABLE `settings` DROP `config_meshcentral_uri`, DROP `config_meshcentral_user`, DROP `config_meshcentral_secret`;"); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.5'"); + } + + if(CURRENT_DATABASE_VERSION == '0.0.5'){ + // Insert queries here required to update to DB version 0.0.6 + + mysqli_query($mysqli, "UPDATE documents SET document_folder_id = 0"); + + mysqli_query($mysqli, "DROP TABLE documents_tagged"); + mysqli_query($mysqli, "DROP TABLE document_tags"); + + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE settings SET config_current_database_version = '0.0.6'"); + } + + if(CURRENT_DATABASE_VERSION == '0.0.6'){ + // Insert queries here required to update to DB version 0.0.7 + mysqli_query($mysqli, "ALTER TABLE contacts ADD contact_department VARCHAR(200) NULL AFTER contact_title"); + mysqli_query($mysqli, "DROP TABLE departments"); + mysqli_query($mysqli, "ALTER TABLE contacts DROP contact_department_id"); + + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.7'"); + } + + if(CURRENT_DATABASE_VERSION == '0.0.7'){ + // Insert queries here required to update to DB version 0.0.8 + + // Add contact_department column to tables without it (fresh installs) - this will cause an error if it already exists so catch and discard it + try{ + mysqli_query($mysqli, "ALTER TABLE contacts ADD contact_department VARCHAR(200) NULL AFTER contact_title"); + } catch(Exception $e) { + // Nothing + } + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.8'"); + } + + if(CURRENT_DATABASE_VERSION == '0.0.8'){ + // Insert queries here required to update to DB version 0.0.9 + + mysqli_query($mysqli, "ALTER TABLE `revenues` CHANGE `revenue_created_at` `revenue_created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, CHANGE `revenue_updated_at` `revenue_updated_at` DATETIME on update CURRENT_TIMESTAMP NULL DEFAULT NULL; "); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.0.9'"); + } + + if(CURRENT_DATABASE_VERSION == '0.0.9'){ + // Insert queries here required to update to DB version 0.0.9 + // Remove unused tables + mysqli_query($mysqli, "DROP TABLE contracts"); + mysqli_query($mysqli, "DROP TABLE messages"); + mysqli_query($mysqli, "DROP TABLE roles"); + + //Remove updated at as API keys can only be added or revoked + mysqli_query($mysqli, "ALTER TABLE `api_keys` DROP `api_key_updated_at`"); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.0'"); + } + + if(CURRENT_DATABASE_VERSION == '0.1.0'){ + // Insert queries here required to update to DB version 0.1.1 + // Logs don't get archived + mysqli_query($mysqli, "ALTER TABLE `logs` DROP `log_archived_at`"); + + // Assets will eventualy have file associatons which could include a receipt. + mysqli_query($mysqli, "ALTER TABLE `assets` DROP `asset_reciept`"); + + mysqli_query($mysqli, "ALTER TABLE `campaign_messages` DROP `message_updated_at`"); + // This will be a seperate table eventually called contact_documents because contact can have several documents + mysqli_query($mysqli, "ALTER TABLE `documents` DROP `document_contact_id`"); + + mysqli_query($mysqli, "ALTER TABLE `expenses` DROP `expense_asset_id`"); + mysqli_query($mysqli, "ALTER TABLE `files` DROP `file_contact_id`"); + mysqli_query($mysqli, "ALTER TABLE `history` DROP `history_archived_at`"); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.1'"); + } + + if(CURRENT_DATABASE_VERSION == '0.1.1'){ + // Insert queries here required to update to DB version 0.1.2 + // Create Many to Many Relationship tables for Assets, Contacts, Software and Vendors + + mysqli_query($mysqli, "CREATE TABLE `asset_documents` (`asset_id` int(11) NOT NULL,`document_id` int(11) NOT NULL, PRIMARY KEY (`asset_id`,`document_id`))"); + mysqli_query($mysqli, "CREATE TABLE `asset_logins` (`asset_id` int(11) NOT NULL,`login_id` int(11) NOT NULL, PRIMARY KEY (`asset_id`,`login_id`))"); + mysqli_query($mysqli, "CREATE TABLE `asset_files` (`asset_id` int(11) NOT NULL,`file_id` int(11) NOT NULL, PRIMARY KEY (`asset_id`,`file_id`))"); + + mysqli_query($mysqli, "CREATE TABLE `contact_documents` (`contact_id` int(11) NOT NULL,`document_id` int(11) NOT NULL, PRIMARY KEY (`contact_id`,`document_id`))"); + mysqli_query($mysqli, "CREATE TABLE `contact_logins` (`contact_id` int(11) NOT NULL,`login_id` int(11) NOT NULL, PRIMARY KEY (`contact_id`,`login_id`))"); + mysqli_query($mysqli, "CREATE TABLE `contact_files` (`contact_id` int(11) NOT NULL,`file_id` int(11) NOT NULL, PRIMARY KEY (`contact_id`,`file_id`))"); + + mysqli_query($mysqli, "CREATE TABLE `software_documents` (`software_id` int(11) NOT NULL,`document_id` int(11) NOT NULL, PRIMARY KEY (`software_id`,`document_id`))"); + mysqli_query($mysqli, "CREATE TABLE `software_logins` (`software_id` int(11) NOT NULL,`login_id` int(11) NOT NULL, PRIMARY KEY (`software_id`,`login_id`))"); + mysqli_query($mysqli, "CREATE TABLE `software_files` (`software_id` int(11) NOT NULL,`file_id` int(11) NOT NULL, PRIMARY KEY (`software_id`,`file_id`))"); + + mysqli_query($mysqli, "CREATE TABLE `vendor_documents` (`vendor_id` int(11) NOT NULL,`document_id` int(11) NOT NULL, PRIMARY KEY (`vendor_id`,`document_id`))"); + mysqli_query($mysqli, "CREATE TABLE `vendor_logins` (`vendor_id` int(11) NOT NULL,`login_id` int(11) NOT NULL, PRIMARY KEY (`vendor_id`,`login_id`))"); + mysqli_query($mysqli, "CREATE TABLE `vendor_files` (`vendor_id` int(11) NOT NULL,`file_id` int(11) NOT NULL, PRIMARY KEY (`vendor_id`,`file_id`))"); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.2'"); + } + + if(CURRENT_DATABASE_VERSION == '0.1.2'){ + // Insert queries here required to update to DB version 0.1.3 + mysqli_query($mysqli, "ALTER TABLE `logs` ADD `log_entity_id` INT NOT NULL DEFAULT '0' AFTER `log_user_id`"); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.3'"); + } + + if(CURRENT_DATABASE_VERSION == '0.1.3'){ + // Insert queries here required to update to DB version 0.1.4 + mysqli_query($mysqli, "ALTER TABLE assets ADD asset_status VARCHAR(200) NULL AFTER asset_mac"); + + ///Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.4'"); + } + + if(CURRENT_DATABASE_VERSION == '0.1.4'){ + // Insert queries here required to update to DB version 0.1.5 + mysqli_query($mysqli, "ALTER TABLE `domains` ADD `domain_txt` TEXT NULL DEFAULT NULL AFTER `domain_mail_servers`"); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.5'"); + } + + if(CURRENT_DATABASE_VERSION == '0.1.5'){ + // Insert queries here required to update to DB version 0.1.6 + // Remove Mailing List Tables + mysqli_query($mysqli, "DROP TABLE campaigns"); + mysqli_query($mysqli, "DROP TABLE campaign_messages"); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.6'"); + } + + if(CURRENT_DATABASE_VERSION == '0.1.6'){ + // Insert queries here required to update to DB version 0.1.7 + //Remove custom links + mysqli_query($mysqli, "DROP TABLE custom_links"); + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.7'"); + } + + if(CURRENT_DATABASE_VERSION == '0.1.7'){ + // Insert queries here required to update to DB version 0.1.8 + mysqli_query($mysqli, "ALTER TABLE `settings` DROP `config_backup_enable`"); + mysqli_query($mysqli, "ALTER TABLE `settings` DROP `config_backup_path`"); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.8'"); + } + + if(CURRENT_DATABASE_VERSION == '0.1.8'){ + // Insert queries here required to update to DB version 0.1.9 + mysqli_query($mysqli, "ALTER TABLE `settings` DROP `config_base_url`"); + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.1.9'"); + } + + if(CURRENT_DATABASE_VERSION == '0.1.9'){ + // Insert queries here required to update to DB version 0.2.0 + // Allow contacts to reset their portal password + mysqli_query($mysqli, "ALTER TABLE contacts ADD contact_password_reset_token VARCHAR(200) NULL DEFAULT NULL AFTER contact_password_hash"); + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.0'"); + } + + if(CURRENT_DATABASE_VERSION == '0.2.0'){ + //Insert queries here required to update to DB version 0.2.1 + + mysqli_query($mysqli, "ALTER TABLE `vendors` ADD `vendor_hours` VARCHAR(200) NULL DEFAULT NULL AFTER `vendor_website`, ADD `vendor_sla` VARCHAR(200) NULL DEFAULT NULL AFTER `vendor_hours`, ADD `vendor_code` VARCHAR(200) NULL DEFAULT NULL AFTER `vendor_sla`, ADD `vendor_template_id` INT(11) DEFAULT 0 AFTER `vendor_archived_at` "); - mysqli_query($mysqli, "ALTER TABLE `vendors` + mysqli_query($mysqli, "ALTER TABLE `vendors` DROP `vendor_country`, DROP `vendor_address`, DROP `vendor_city`, @@ -351,8 +351,8 @@ if(LATEST_DATABASE_VERSION > CURRENT_DATABASE_VERSION){ DROP `vendor_global` "); - //Create New Vendor Templates Table - mysqli_query($mysqli, "CREATE TABLE `vendor_templates` (`vendor_template_id` int(11) AUTO_INCREMENT PRIMARY KEY, + //Create New Vendor Templates Table + mysqli_query($mysqli, "CREATE TABLE `vendor_templates` (`vendor_template_id` int(11) AUTO_INCREMENT PRIMARY KEY, `vendor_template_name` varchar(200) NOT NULL, `vendor_template_description` varchar(200) NULL DEFAULT NULL, `vendor_template_phone` varchar(200) NULL DEFAULT NULL, @@ -365,37 +365,37 @@ if(LATEST_DATABASE_VERSION > CURRENT_DATABASE_VERSION){ `company_id` int(11) NOT NULL )"); - //Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.1'"); - } - - if(CURRENT_DATABASE_VERSION == '0.2.1'){ - // Insert queries here required to update to DB version 0.2.2 - mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_ticket_email_parse` INT(1) NOT NULL DEFAULT '0' AFTER `config_ticket_from_email`"); - mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_imap_host` VARCHAR(200) NULL DEFAULT NULL AFTER `config_mail_from_name`, ADD `config_imap_port` INT(5) NULL DEFAULT NULL AFTER `config_imap_host`, ADD `config_imap_encryption` VARCHAR(200) NULL DEFAULT NULL AFTER `config_imap_port`;"); - - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.2'"); - } - - if(CURRENT_DATABASE_VERSION == '0.2.2'){ - // Insert queries here required to update to DB version 0.2.3 - - // Add contact_important field to those who don't have it (installed before March 2022) - try { - mysqli_query($mysqli, "ALTER TABLE `contacts` ADD `contact_important` tinyint(1) NOT NULL DEFAULT 0 AFTER contact_password_reset_token;"); - } catch (Exception $e) { - // Field already exists - that's fine + //Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.1'"); } - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.3'"); - } + if(CURRENT_DATABASE_VERSION == '0.2.1'){ + // Insert queries here required to update to DB version 0.2.2 + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_ticket_email_parse` INT(1) NOT NULL DEFAULT '0' AFTER `config_ticket_from_email`"); + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_imap_host` VARCHAR(200) NULL DEFAULT NULL AFTER `config_mail_from_name`, ADD `config_imap_port` INT(5) NULL DEFAULT NULL AFTER `config_imap_host`, ADD `config_imap_encryption` VARCHAR(200) NULL DEFAULT NULL AFTER `config_imap_port`;"); - if(CURRENT_DATABASE_VERSION == '0.2.3'){ - - //Create New interfaces Table - mysqli_query($mysqli, "CREATE TABLE `interfaces` (`interface_id` int(11) AUTO_INCREMENT PRIMARY KEY, + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.2'"); + } + + if(CURRENT_DATABASE_VERSION == '0.2.2'){ + // Insert queries here required to update to DB version 0.2.3 + + // Add contact_important field to those who don't have it (installed before March 2022) + try { + mysqli_query($mysqli, "ALTER TABLE `contacts` ADD `contact_important` tinyint(1) NOT NULL DEFAULT 0 AFTER contact_password_reset_token;"); + } catch (Exception $e) { + // Field already exists - that's fine + } + + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.3'"); + } + + if(CURRENT_DATABASE_VERSION == '0.2.3'){ + + //Create New interfaces Table + mysqli_query($mysqli, "CREATE TABLE `interfaces` (`interface_id` int(11) AUTO_INCREMENT PRIMARY KEY, `interface_number` int(11) NULL DEFAULT NULL, `interface_description` varchar(200) NULL DEFAULT NULL, `interface_connected_asset` varchar(200) NULL DEFAULT NULL, @@ -409,58 +409,65 @@ if(LATEST_DATABASE_VERSION > CURRENT_DATABASE_VERSION){ `company_id` int(11) NOT NULL )"); - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.4'"); - - } + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.4'"); - if(CURRENT_DATABASE_VERSION == '0.2.4'){ - mysqli_query($mysqli, "CREATE TABLE `contact_assets` (`contact_id` int(11) NOT NULL,`asset_id` int(11) NOT NULL, PRIMARY KEY (`contact_id`,`asset_id`))"); + } - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.5'"); - } + if(CURRENT_DATABASE_VERSION == '0.2.4'){ + mysqli_query($mysqli, "CREATE TABLE `contact_assets` (`contact_id` int(11) NOT NULL,`asset_id` int(11) NOT NULL, PRIMARY KEY (`contact_id`,`asset_id`))"); - if(CURRENT_DATABASE_VERSION == '0.2.5'){ - mysqli_query($mysqli, "ALTER TABLE `users` ADD `user_status` TINYINT(1) DEFAULT 1 AFTER `user_password`"); - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.6'"); - } + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.5'"); + } - if(CURRENT_DATABASE_VERSION == '0.2.6'){ - // Insert queries here required to update to DB version 0.2.7 - mysqli_query($mysqli, "ALTER TABLE `contacts` ADD `contact_token_expire` DATETIME NULL DEFAULT NULL AFTER `contact_password_reset_token`"); - - // Update config.php var with new version var for use with docker - file_put_contents("config.php", "\$repo_branch = 'master';" . PHP_EOL, FILE_APPEND); + if(CURRENT_DATABASE_VERSION == '0.2.5'){ + mysqli_query($mysqli, "ALTER TABLE `users` ADD `user_status` TINYINT(1) DEFAULT 1 AFTER `user_password`"); + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.6'"); + } + + if(CURRENT_DATABASE_VERSION == '0.2.6'){ + // Insert queries here required to update to DB version 0.2.7 + mysqli_query($mysqli, "ALTER TABLE `contacts` ADD `contact_token_expire` DATETIME NULL DEFAULT NULL AFTER `contact_password_reset_token`"); + + // Update config.php var with new version var for use with docker + file_put_contents("config.php", "\$repo_branch = 'master';" . PHP_EOL, FILE_APPEND); - // Then, update the database to the next sequential version - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.7'"); - } + // Then, update the database to the next sequential version + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.7'"); + } - if(CURRENT_DATABASE_VERSION == '0.2.7'){ - - mysqli_query($mysqli, "ALTER TABLE `vendors` ADD `vendor_template` TINYINT(1) DEFAULT 0 AFTER `vendor_notes`"); - mysqli_query($mysqli, "ALTER TABLE `software` ADD `software_template` TINYINT(1) DEFAULT 0 AFTER `software_notes`"); - mysqli_query($mysqli, "ALTER TABLE `vendors` DROP `vendor_template_id`"); - mysqli_query($mysqli, "DROP TABLE vendor_templates"); - - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.8'"); - } + if(CURRENT_DATABASE_VERSION == '0.2.7'){ - if(CURRENT_DATABASE_VERSION == '0.2.8'){ - - mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_theme` VARCHAR(200) DEFAULT 'blue' AFTER `config_module_enable_ticketing`"); - - mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.9'"); - } + mysqli_query($mysqli, "ALTER TABLE `vendors` ADD `vendor_template` TINYINT(1) DEFAULT 0 AFTER `vendor_notes`"); + mysqli_query($mysqli, "ALTER TABLE `software` ADD `software_template` TINYINT(1) DEFAULT 0 AFTER `software_notes`"); + mysqli_query($mysqli, "ALTER TABLE `vendors` DROP `vendor_template_id`"); + mysqli_query($mysqli, "DROP TABLE vendor_templates"); -//if(CURRENT_DATABASE_VERSION == '0.2.9'){ - // Insert queries here required to update to DB version 0.3.0 + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.8'"); + } - // Then, update the database to the next sequential version - // mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.3.0'"); - //} + if(CURRENT_DATABASE_VERSION == '0.2.8'){ + + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_theme` VARCHAR(200) DEFAULT 'blue' AFTER `config_module_enable_ticketing`"); + + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.2.9'"); + } + + if(CURRENT_DATABASE_VERSION == '0.2.9'){ + + mysqli_query($mysqli, "ALTER TABLE `settings` ADD `config_ticket_client_general_notifications` INT(1) NOT NULL DEFAULT '1' AFTER `config_ticket_email_parse`"); + + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.3.0'"); + } + + //if(CURRENT_DATABASE_VERSION == '0.3.0'){ + // Insert queries here required to update to DB version 0.3.1 + + // Then, update the database to the next sequential version + // mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '0.3.1'"); + //} }else{ - // Up-to-date + // Up-to-date } \ No newline at end of file diff --git a/database_version.php b/database_version.php index f8202a13..e6d0a18f 100644 --- a/database_version.php +++ b/database_version.php @@ -5,4 +5,4 @@ * It is used in conjunction with database_updates.php */ -DEFINE("LATEST_DATABASE_VERSION", "0.2.9"); \ No newline at end of file +DEFINE("LATEST_DATABASE_VERSION", "0.3.0"); \ No newline at end of file diff --git a/db.sql b/db.sql index 049f23b6..f68ea689 100644 --- a/db.sql +++ b/db.sql @@ -1066,6 +1066,7 @@ CREATE TABLE `settings` ( `config_ticket_from_name` varchar(200) DEFAULT NULL, `config_ticket_from_email` varchar(200) DEFAULT NULL, `config_ticket_email_parse` int(1) NOT NULL DEFAULT 0, + `config_ticket_client_general_notifications` int(1) NOT NULL DEFAULT 0, `config_enable_cron` tinyint(1) DEFAULT NULL, `config_recurring_auto_send_invoice` tinyint(1) DEFAULT NULL, `config_enable_alert_domain_expire` tinyint(1) DEFAULT NULL, diff --git a/get_settings.php b/get_settings.php index 0fb64176..513c57fc 100644 --- a/get_settings.php +++ b/get_settings.php @@ -58,6 +58,7 @@ $config_ticket_next_number = $row['config_ticket_next_number']; $config_ticket_from_name = $row['config_ticket_from_name']; $config_ticket_from_email = $row['config_ticket_from_email']; $config_ticket_email_parse = $row['config_ticket_email_parse']; +$config_ticket_client_general_notifications = $row['config_ticket_client_general_notifications']; // Alerts $config_enable_cron = $row['config_enable_cron']; diff --git a/login.php b/login.php index 0e88297b..e6c522a4 100644 --- a/login.php +++ b/login.php @@ -5,13 +5,41 @@ if(!file_exists('config.php')){ exit; } -include("config.php"); -include("functions.php"); +require_once("config.php"); +require_once("functions.php"); +require_once("rfc6238.php"); // IP & User Agent for logging $ip = strip_tags(mysqli_real_escape_string($mysqli,get_ip())); $user_agent = strip_tags(mysqli_real_escape_string($mysqli,$_SERVER['HTTP_USER_AGENT'])); +// Block brute force password attacks - check recent failed login attempts for this IP +// Block access if more than 15 failed login attempts have happened in the last 10 minutes +$row = mysqli_fetch_assoc(mysqli_query($mysqli,"SELECT COUNT(log_id) AS failed_login_count FROM logs WHERE log_ip = '$ip' AND log_type = 'Login' AND log_action = 'Failed' AND log_created_at > (NOW() - INTERVAL 10 MINUTE)")); +$failed_login_count = $row['failed_login_count']; + +if ($failed_login_count >= 15) { + + // Logging + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Blocked', log_description = '$ip was blocked access to login due to IP lockout', log_ip = '$ip', log_user_agent = '$user_agent'"); + + // Inform user & quit processing page + exit("

$config_app_name

Your IP address has been blocked due to repeated failed login attempts. Please try again later.

This action has been logged."); +} + +// Query Settings for "default" company (as companies are being removed shortly) +$sql_settings = mysqli_query($mysqli,"SELECT * FROM settings WHERE company_id = 1"); +$row = mysqli_fetch_array($sql_settings); + +// Mail +$config_smtp_host = $row['config_smtp_host']; +$config_smtp_port = $row['config_smtp_port']; +$config_smtp_encryption = $row['config_smtp_encryption']; +$config_smtp_username = $row['config_smtp_username']; +$config_smtp_password = $row['config_smtp_password']; +$config_mail_from_email = $row['config_mail_from_email']; +$config_mail_from_name = $row['config_mail_from_name']; + // HTTP-Only cookies ini_set("session.cookie_httponly", True); @@ -26,45 +54,67 @@ if (isset($_POST['login'])) { // Sessions should start after the user has POSTed data session_start(); - // Check recent failed login attempts for this IP (more than 10 failed logins in 5 mins) - $row = mysqli_fetch_assoc(mysqli_query($mysqli,"SELECT COUNT(log_id) AS failed_login_count FROM logs WHERE log_ip = '$ip' AND log_type = 'Login' AND log_action = 'Failed' AND log_created_at > (NOW() - INTERVAL 5 MINUTE)")); - $failed_login_count = $row['failed_login_count']; + // Passed login brute force check + $email = strip_tags(mysqli_real_escape_string($mysqli, $_POST['email'])); + $password = $_POST['password']; - // Login brute force check - if ($failed_login_count >= 10) { + $current_code = 0; // Default value + if (isset($_POST['current_code'])) { + $current_code = strip_tags(mysqli_real_escape_string($mysqli, $_POST['current_code'])); + } - // Logging - mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Failed', log_description = 'Failed login attempt due to IP lockout', log_ip = '$ip', log_user_agent = '$user_agent'"); + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM users LEFT JOIN user_settings on users.user_id = user_settings.user_id WHERE user_email = '$email' AND user_archived_at IS NULL AND user_status = 1")); - // Send an alert only count hits 10 to reduce flooding alerts (using 1 as "default" company) - if($failed_login_count == 10){ - mysqli_query($mysqli,"INSERT INTO notifications SET notification_type = 'Lockout', notification = '$ip was locked out for repeated failed login attempts.', notification_timestamp = NOW() company_id = '1'"); - } + // Check password + if ($row && password_verify($password, $row['user_password'])) { - // Inform user - $response = '
IP Lockout - Please try again later.
'; + // User password correct (partial login) - } else { - // Passed login brute force check - $email = strip_tags(mysqli_real_escape_string($mysqli, $_POST['email'])); - $password = $_POST['password']; - if (isset($_POST['current_code'])) { - $current_code = strip_tags(mysqli_real_escape_string($mysqli, $_POST['current_code'])); - } + // Set temporary user variables + $user_name = strip_tags(mysqli_real_escape_string($mysqli, $row['user_name'])); + $user_id = $row['user_id']; + $user_email = $row['user_email']; + $token = $row['user_token']; - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM users LEFT JOIN user_settings on users.user_id = user_settings.user_id WHERE user_email = '$email' AND user_archived_at IS NULL AND user_status = 1")); - if ($row && password_verify($password, $row['user_password'])) { + // Checking for user 2FA + if (empty($token) || TokenAuth6238::verify($token, $current_code)) { - // User variables - $token = $row['user_token']; - $user_name = strip_tags(mysqli_real_escape_string($mysqli, $row['user_name'])); - $user_id = $row['user_id']; + // FULL LOGIN SUCCESS - 2FA not configured or was successful + + // Check this login isn't suspicious + $sql_ip_prev_logins = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT(log_id) AS ip_previous_logins FROM logs WHERE log_type = 'Login' AND log_action = 'Success' AND log_ip = '$ip' AND log_user_id = '$user_id'")); + $ip_previous_logins = $sql_ip_prev_logins['ip_previous_logins']; + + $sql_ua_prev_logins = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT(log_id) AS ua_previous_logins FROM logs WHERE log_type = 'Login' AND log_action = 'Success' AND log_user_agent = '$user_agent' AND log_user_id = '$user_id'")); + $ua_prev_logins = $sql_ua_prev_logins['ua_previous_logins']; + + // Notify if both the user agent and IP are different + if (!empty($config_smtp_host) && $ip_previous_logins == 0 && $ua_prev_logins == 0) { + $subject = "$config_app_name new login for $user_name"; + $body = "Hi $user_name,

A recent successful login to your $config_app_name account was considered a little unusual. If this was you, you can safely ignore this email!

IP Address: $ip
User Agent: $user_agent

If you did not perform this login, your credentials may be compromised.

Thanks,
ITFlow"; + + $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, + $config_mail_from_email, $config_mail_from_name, + $user_email, $user_name, + $subject, $body); + } + + + // Determine whether 2FA was used (for logs) + $extended_log = ''; // Default value + if ($current_code !== 0 ) { + $extended_log = 'with 2FA'; + } + + // Logging successful login + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Success', log_description = '$user_name successfully logged in $extended_log', log_ip = '$ip', log_user_agent = '$user_agent', log_user_id = $user_id"); // Session info $_SESSION['user_id'] = $user_id; $_SESSION['user_name'] = $user_name; $_SESSION['user_role'] = $row['user_role']; $_SESSION['csrf_token'] = bin2hex(random_bytes(78)); + $_SESSION['logged'] = TRUE; // Setup encryption session key if (isset($row['user_specific_encryption_ciphertext']) && $row['user_role'] > 1) { @@ -84,67 +134,66 @@ if (isset($_POST['login'])) { } } - if (empty($token)) { - // Full Login successful - - $_SESSION['logged'] = TRUE; - mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Success', log_description = '$user_name successfully logged in', log_ip = '$ip', log_user_agent = '$user_agent', log_user_id = $user_id"); - - // Show start page/dashboard depending on role - if ($row['user_role'] == 2) { - header("Location: dashboard_technical.php"); - } else { - header("Location: dashboard_financial.php"); - } - + // Show start page/dashboard depending on role + if ($row['user_role'] == 2) { + header("Location: dashboard_technical.php"); } else { - // Prompt for MFA - - $token_field = "
- -
-
- -
-
-
"; - - require_once("rfc6238.php"); - - if (TokenAuth6238::verify($token, $current_code)) { - // Full login (with MFA) successful - $_SESSION['logged'] = TRUE; - mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login 2FA', log_action = 'Success', log_description = '$user_name successfully logged in using 2FA', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW(), log_user_id = $user_id"); - - // Show start page/dashboard depending on role - if ($row['user_role'] == 2) { - header("Location: dashboard_technical.php"); - } else { - header("Location: dashboard_financial.php"); - } - - } else { - mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = '2FA Failed', log_description = '$user_name failed 2FA', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW(), log_user_id = $user_id"); - - $response = " -
- Please Enter 2FA Key! - -
- "; - } + header("Location: dashboard_financial.php"); } - } else { - mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Failed', log_description = 'Failed login attempt using $email', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW()"); - $response = " -
- Incorrect username or password. - -
- "; + } else { + + // MFA is configured and needs to be confirmed, or was unsuccessful + + // HTML code for the token input field + $token_field = " +
+ +
+
+ +
+
+
"; + + // Log/notify if MFA was unsuccessful + if ($current_code !== 0) { + + // Logging + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = '2FA Failed', log_description = '$user_name failed 2FA', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW(), log_user_id = $user_id"); + + // Email the tech to advise their credentials may be compromised + if (!empty($config_smtp_host)) { + $subject = "Important: $config_app_name failed 2FA login attempt for $user_name"; + $body = "Hi $user_name,

A recent login to your $config_app_name account was unsuccessful due to an incorrect 2FA code. If you did not attempt this login, your credentials may be compromised.

Thanks,
ITFlow"; + + $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, + $config_mail_from_email, $config_mail_from_name, + $user_email, $user_name, + $subject, $body); + } + + // HTML feedback for incorrect 2FA code + $response = " +
+ Please Enter 2FA Key! + +
"; + } } + + } else { + + // Password incorrect or user doesn't exist - show generic error + + mysqli_query($mysqli, "INSERT INTO logs SET log_type = 'Login', log_action = 'Failed', log_description = 'Failed login attempt using $email', log_ip = '$ip', log_user_agent = '$user_agent', log_created_at = NOW()"); + + $response = " +
+ Incorrect username or password. + +
"; } } @@ -153,60 +202,60 @@ if (isset($_POST['login'])) { - - - <?php echo $config_app_name; ?> | Login - - - + + + <?php echo $config_app_name; ?> | Login + + + - - - - - - + + + + + +
- - - - diff --git a/post.php b/post.php index b95b627a..753c33ec 100644 --- a/post.php +++ b/post.php @@ -156,7 +156,9 @@ if(isset($_POST['edit_user'])){ $role = intval($_POST['role']); $existing_file_name = trim(strip_tags(mysqli_real_escape_string($mysqli,$_POST['existing_file_name']))); $extended_log_description = ''; - $two_fa = $_POST['2fa']; + if(!empty($_POST['2fa'])) { + $two_fa = $_POST['2fa']; + } if(!file_exists("uploads/users/$user_id/")) { mkdir("uploads/users/$user_id"); @@ -285,6 +287,32 @@ if(isset($_POST['edit_profile'])){ $logout = FALSE; $extended_log_description = ''; + // Email notification when password or email is changed + $user_old_email_sql = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT user_email FROM users WHERE user_id = $user_id")); + $user_old_email = $user_old_email_sql['user_email']; + + if (!empty($config_smtp_host) && (!empty($new_password) || $user_old_email !== $email)) { + + // Determine exactly what changed + if ($user_old_email !== $email && !empty($new_password)) { + $details = "Your e-mail address and password were changed. New email: $email."; + } + elseif ($user_old_email !== $email) { + $details = "Your email address was changed. New email: $email."; + } + elseif (!empty($new_password)) { + $details = "Your password was changed."; + } + + $subject = "$config_app_name account update confirmation for $name"; + $body = "Hi $name,

Your $config_app_name account has been updated, details below:

$details

If you did not perform this change, contact your $config_app_name administrator immediately.

Thanks,
ITFlow
$session_company_name"; + + $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, + $config_mail_from_email, $config_mail_from_name, + $user_old_email, $name, + $subject, $body); + } + //Check to see if a file is attached if($_FILES['file']['tmp_name'] != ''){ @@ -332,8 +360,6 @@ if(isset($_POST['edit_profile'])){ $_SESSION['alert_message'] = 'There was an error moving the file to upload directory. Please make sure the upload directory is writable by web server.'; } } - - mysqli_query($mysqli,"UPDATE users SET user_name = '$name', user_email = '$email' WHERE user_id = $user_id"); if(!empty($new_password)){ $new_password = password_hash($new_password, PASSWORD_DEFAULT); @@ -361,6 +387,8 @@ if(isset($_POST['edit_profile'])){ $extended_log_description .= ", extension access disabled"; } + mysqli_query($mysqli,"UPDATE users SET user_name = '$name', user_email = '$email' WHERE user_id = $user_id"); + //Logging mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'User Preferences', log_action = 'Modify', log_description = '$session_name modified their preferences$extended_log_description', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_user_id = $session_user_id, company_id = $session_company_id"); @@ -952,9 +980,9 @@ if(isset($_POST['edit_ticket_settings'])){ $config_ticket_from_email = trim(strip_tags(mysqli_real_escape_string($mysqli,$_POST['config_ticket_from_email']))); $config_ticket_from_name = trim(strip_tags(mysqli_real_escape_string($mysqli,$_POST['config_ticket_from_name']))); $config_ticket_email_parse = intval($_POST['config_ticket_email_parse']); + $config_ticket_client_general_notifications = intval($_POST['config_ticket_client_general_notifications']); - - mysqli_query($mysqli,"UPDATE settings SET config_ticket_prefix = '$config_ticket_prefix', config_ticket_next_number = $config_ticket_next_number, config_ticket_from_email = '$config_ticket_from_email', config_ticket_from_name = '$config_ticket_from_name', config_ticket_email_parse = '$config_ticket_email_parse' WHERE company_id = $session_company_id"); + mysqli_query($mysqli,"UPDATE settings SET config_ticket_prefix = '$config_ticket_prefix', config_ticket_next_number = $config_ticket_next_number, config_ticket_from_email = '$config_ticket_from_email', config_ticket_from_name = '$config_ticket_from_name', config_ticket_email_parse = '$config_ticket_email_parse', config_ticket_client_general_notifications = $config_ticket_client_general_notifications WHERE company_id = $session_company_id"); //Logging mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Settings', log_action = 'Modify', log_description = 'Ticket settings', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_user_id = $session_user_id, company_id = $session_company_id"); @@ -1108,6 +1136,17 @@ if(isset($_POST['disable_2fa'])){ //Logging mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'User Settings', log_action = 'Modify', log_description = '$session_name disabled 2FA on their account', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_user_id = $session_user_id, company_id = $session_company_id"); + // Email notification + if (!empty($config_smtp_host)) { + $subject = "$config_app_name account update confirmation for $session_name"; + $body = "Hi $session_name,

Your $config_app_name account has been updated, details below:

2FA was disabled.

If you did not perform this change, contact your $config_app_name administrator immediately.

Thanks,
ITFlow
$session_company_name"; + + $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, + $config_mail_from_email, $config_mail_from_name, + $session_email, $session_name, + $subject, $body); + } + $_SESSION['alert_message'] = "Two-factor authentication disabled"; header("Location: " . $_SERVER["HTTP_REFERER"]); @@ -5918,10 +5957,10 @@ if(isset($_POST['add_ticket'])){ $id = mysqli_insert_id($mysqli); // E-mail client - if (!empty($config_smtp_host)) { + if (!empty($config_smtp_host) && $config_ticket_client_general_notifications == 1) { // Get contact/ticket details - $sql = mysqli_query($mysqli,"SELECT contact_name, contact_email, ticket_prefix, ticket_number, company_phone FROM tickets + $sql = mysqli_query($mysqli,"SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_subject, company_phone FROM tickets LEFT JOIN clients ON ticket_client_id = client_id LEFT JOIN contacts ON ticket_contact_id = contact_id LEFT JOIN companies ON tickets.company_id = companies.company_id @@ -5932,13 +5971,14 @@ if(isset($_POST['add_ticket'])){ $contact_email = $row['contact_email']; $ticket_prefix = $row['ticket_prefix']; $ticket_number = $row['ticket_number']; + $ticket_subject = $row['ticket_subject']; $company_phone = formatPhoneNumber($row['company_phone']); // Verify contact email is valid if(filter_var($contact_email, FILTER_VALIDATE_EMAIL)){ - $subject = "Ticket created - [$ticket_prefix$ticket_number] - $subject"; - $body = "#--itflow--#

Hello, $contact_name

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

--------------------------------
$details--------------------------------

Ticket: $ticket_prefix$ticket_number
Subject: $subject
Status: Open
Portal: https://$config_base_url/portal/ticket.php?id=$id

~
$session_company_name
Support Department
$config_ticket_from_email
$company_phone"; + $subject = "Ticket created - [$ticket_prefix$ticket_number] - $ticket_subject"; + $body = "#--itflow--#

Hello, $contact_name

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

--------------------------------
$details--------------------------------

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

~
$session_company_name
Support Department
$config_ticket_from_email
$company_phone"; $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, $config_ticket_from_email, $config_ticket_from_name, @@ -6096,10 +6136,11 @@ if(isset($_POST['assign_ticket'])){ } else { // Get & verify assigned agent details - $agent_details_sql = mysqli_query($mysqli, "SELECT user_name FROM users LEFT JOIN user_settings ON users.user_id = user_settings.user_id WHERE users.user_id = '$assigned_to' AND user_settings.user_role > 1"); + $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 = '$assigned_to' AND user_settings.user_role > 1"); $agent_details = mysqli_fetch_array($agent_details_sql); $agent_name = $agent_details['user_name']; - $ticket_reply = "Ticket re-assigned to $agent_details[user_name]."; + $agent_email = $agent_details['user_email']; + $ticket_reply = "Ticket re-assigned to $agent_name."; if(!$agent_name){ $_SESSION['alert_type'] = "error"; @@ -6110,8 +6151,10 @@ if(isset($_POST['assign_ticket'])){ } // Get & verify ticket details - $ticket_details_sql = mysqli_query($mysqli, "SELECT ticket_subject FROM tickets WHERE ticket_id = '$ticket_id' AND ticket_status != 'Closed'"); + $ticket_details_sql = mysqli_query($mysqli, "SELECT ticket_prefix, ticket_number, ticket_subject FROM tickets WHERE ticket_id = '$ticket_id' AND ticket_status != 'Closed'"); $ticket_details = mysqli_fetch_array($ticket_details_sql); + $ticket_prefix = $ticket_details['ticket_prefix']; + $ticket_number = $ticket_details['ticket_number']; $ticket_subject = $ticket_details['ticket_subject']; if(!$ticket_subject){ @@ -6127,7 +6170,19 @@ if(isset($_POST['assign_ticket'])){ 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, company_id = $session_company_id") or die(mysqli_error($mysqli)); // Logging - mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Ticket', log_action = 'Modify', log_description = '$ticket_subject reassigned to $agent_name', log_ip = '$session_ip', log_user_agent = '$session_user_agent', company_id = $session_company_id, log_user_id = $session_user_id"); + mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Ticket', log_action = 'Modify', log_description = '$ticket_subject ($ticket_id) - $ticket_reply', log_ip = '$session_ip', log_user_agent = '$session_user_agent', company_id = $session_company_id, log_user_id = $session_user_id"); + + // Email notification + if (intval($session_user_id) !== $assigned_to) { + $subject = "$config_app_name ticket $ticket_prefix$ticket_number assigned to you"; + $body = "Hi $agent_name,

A ticket has been assigned to you!

ID: $ticket_prefix$ticket_number
Subject: $ticket_subject

Thanks,
$session_name
ITFlow"; + + $mail = sendSingleEmail($config_smtp_host, $config_smtp_username, $config_smtp_password, $config_smtp_encryption, $config_smtp_port, + $config_ticket_from_email, $config_ticket_from_name, + $agent_email, $agent_name, + $subject, $body); + } + $_SESSION['alert_message'] = "Ticket re-assigned"; @@ -6345,7 +6400,7 @@ if(isset($_GET['close_ticket'])){ mysqli_query($mysqli,"INSERT INTO logs SET log_type = 'Ticket', log_action = 'Closed', log_description = '$ticket_id Closed', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_user_id = $session_user_id, company_id = $session_company_id"); // Client notification email - if (!empty($config_smtp_host)) { + if (!empty($config_smtp_host) && $config_ticket_client_general_notifications == 1) { // Get details $ticket_sql = mysqli_query($mysqli,"SELECT contact_name, contact_email, ticket_prefix, ticket_number, ticket_subject, company_phone FROM tickets diff --git a/settings_ticket.php b/settings_ticket.php index 308b411f..a4c44b23 100644 --- a/settings_ticket.php +++ b/settings_ticket.php @@ -1,64 +1,69 @@ -
-
-

Ticket Settings

-
-
-
- -
- -
-
- -
- +
+
+

Ticket Settings

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