From 227b87b1cb6a065e9c8a4cd065a147ef9026eba5 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Sat, 25 Jan 2025 19:53:00 -0500 Subject: [PATCH 01/32] Fix Show OTP on hover in asset and contact details logins section --- client_asset_details.php | 4 +++- client_contact_details.php | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/client_asset_details.php b/client_asset_details.php index 40252074..df8334f3 100644 --- a/client_asset_details.php +++ b/client_asset_details.php @@ -485,7 +485,7 @@ if (isset($_GET['asset_id'])) { if (empty($login_otp_secret)) { $otp_display = "-"; } else { - $otp_display = " Hover.."; + $otp_display = " Hover.."; } $login_note = nullable_htmlentities($row['login_note']); $login_important = intval($row['login_important']); @@ -926,6 +926,8 @@ if (isset($_GET['asset_id'])) { + + Hover.."; + $otp_display = " Hover.."; } $login_note = nullable_htmlentities($row['login_note']); $login_important = intval($row['login_important']); @@ -1129,6 +1129,8 @@ if (isset($_GET['contact_id'])) { + + Date: Sat, 25 Jan 2025 21:30:23 -0500 Subject: [PATCH 02/32] Remove cron key from setup --- setup.php | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/setup.php b/setup.php index b27e0d93..dd955461 100644 --- a/setup.php +++ b/setup.php @@ -243,21 +243,9 @@ if (isset($_POST['add_company_settings'])) { } } - - $latest_database_version = LATEST_DATABASE_VERSION; mysqli_query($mysqli,"INSERT INTO settings SET company_id = 1, config_current_database_version = '$latest_database_version', config_invoice_prefix = 'INV-', config_invoice_next_number = 1, config_recurring_prefix = 'REC-', config_recurring_next_number = 1, config_invoice_overdue_reminders = '1,3,7', config_quote_prefix = 'QUO-', config_quote_next_number = 1, config_default_net_terms = 30, config_ticket_next_number = 1, config_ticket_prefix = 'TCK-'"); - # Used only for the install script to grab the generated cronkey and insert into the db - if (file_exists("uploads/tmp/cronkey.php")) { - include "uploads/tmp/cronkey.php"; - - - mysqli_query($mysqli,"UPDATE settings SET config_cron_key = '$itflow_install_script_generated_cronkey'"); - - unlink('uploads/tmp/cronkey.php'); - } - // Create Categories // Expense Categories Examples mysqli_query($mysqli,"INSERT INTO categories SET category_name = 'Office Supplies', category_type = 'Expense', category_color = 'blue'"); From d5a03d3afc34ce10d988702e43ad362a354284af Mon Sep 17 00:00:00 2001 From: johnnyq Date: Sat, 25 Jan 2025 21:44:46 -0500 Subject: [PATCH 03/32] remove cron key from the code and remove old cron script and setup and update cli scripts as they now reside in scripts directory --- admin_settings_notification.php | 13 - cron.php | 1014 -------------------- cron_certificate_refresher.php | 69 -- cron_domain_refresher.php | 82 -- cron_mail_queue.php | 228 ----- cron_ticket_email_parser.php | 560 ----------- database_updates.php | 13 +- get_settings.php | 2 - includes/database_version.php | 2 +- post/admin/admin_settings_notification.php | 16 - setup_cli.php | 389 -------- update_cli.php | 130 --- 12 files changed, 11 insertions(+), 2507 deletions(-) delete mode 100644 cron.php delete mode 100644 cron_certificate_refresher.php delete mode 100644 cron_domain_refresher.php delete mode 100644 cron_mail_queue.php delete mode 100644 cron_ticket_email_parser.php delete mode 100644 setup_cli.php delete mode 100644 update_cli.php diff --git a/admin_settings_notification.php b/admin_settings_notification.php index 8a23f630..1abc0982 100644 --- a/admin_settings_notification.php +++ b/admin_settings_notification.php @@ -19,19 +19,6 @@ require_once "includes/inc_all_admin.php"; -
- -
-
- -
- - -
-
- diff --git a/cron.php b/cron.php deleted file mode 100644 index 40d5312e..00000000 --- a/cron.php +++ /dev/null @@ -1,1014 +0,0 @@ - 0) { - - appNotify("Pending Tickets", "There are $tickets_pending_assignment new tickets pending assignment", "tickets.php?status=New"); - - // Logging - logApp("Cron", "info", "Cron created notifications for new tickets that are pending assignment"); -} - -// Recurring (Scheduled) tickets - -// Get recurring tickets for today -$sql_scheduled_tickets = mysqli_query($mysqli, "SELECT * FROM scheduled_tickets WHERE scheduled_ticket_next_run = CURDATE()"); - -if (mysqli_num_rows($sql_scheduled_tickets) > 0) { - while ($row = mysqli_fetch_array($sql_scheduled_tickets)) { - - $schedule_id = intval($row['scheduled_ticket_id']); - $subject = sanitizeInput($row['scheduled_ticket_subject']); - $details = mysqli_real_escape_string($mysqli, $row['scheduled_ticket_details']); - $priority = sanitizeInput($row['scheduled_ticket_priority']); - $frequency = sanitizeInput(strtolower($row['scheduled_ticket_frequency'])); - $billable = intval($row['scheduled_ticket_billable']); - $created_id = intval($row['scheduled_ticket_created_by']); - $assigned_id = intval($row['scheduled_ticket_assigned_to']); - $client_id = intval($row['scheduled_ticket_client_id']); - $contact_id = intval($row['scheduled_ticket_contact_id']); - $asset_id = intval($row['scheduled_ticket_asset_id']); - - $ticket_status = 1; // Default - if ($assigned_id > 0) { - $ticket_status = 2; // Set to open if we've auto-assigned an agent - } - - // Assign this new ticket the next ticket number - $ticket_number_sql = mysqli_fetch_array(mysqli_query($mysqli, "SELECT config_ticket_next_number FROM settings WHERE company_id = 1")); - $ticket_number = intval($ticket_number_sql['config_ticket_next_number']); - - // Increment config_ticket_next_number by 1 (for the next ticket) - $new_config_ticket_next_number = $ticket_number + 1; - mysqli_query($mysqli, "UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = 1"); - - // 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 = '$ticket_status', ticket_billable = $billable, ticket_created_by = $created_id, ticket_assigned_to = $assigned_id, ticket_contact_id = $contact_id, ticket_client_id = $client_id, ticket_asset_id = $asset_id"); - $id = mysqli_insert_id($mysqli); - - // Logging - logAction("Ticket", "Create", "Cron created recurring scheduled $frequency ticket - $subject", $client_id, $id); - - customAction('ticket_create', $id); - - // Notifications - - // Get client/contact/ticket details - $sql = mysqli_query( - $mysqli, - "SELECT client_name, contact_name, contact_email, ticket_prefix, ticket_number, ticket_priority, ticket_subject, ticket_details FROM tickets - LEFT JOIN clients ON ticket_client_id = client_id - LEFT JOIN contacts ON ticket_contact_id = contact_id - WHERE ticket_id = $id" - ); - $row = mysqli_fetch_array($sql); - - $contact_name = sanitizeInput($row['contact_name']); - $contact_email = sanitizeInput($row['contact_email']); - $client_name = sanitizeInput($row['client_name']); - $contact_name = sanitizeInput($row['contact_name']); - $contact_email = sanitizeInput($row['contact_email']); - $ticket_prefix = sanitizeInput($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_priority = sanitizeInput($row['ticket_priority']); - $ticket_subject = sanitizeInput($row['ticket_subject']); - $ticket_details = mysqli_real_escape_string($mysqli, $row['ticket_details']); - - $data = []; - - // Notify client by email their ticket has been raised, if general notifications are turned on & there is a valid contact email - if (!empty($config_smtp_host) && $config_ticket_client_general_notifications == 1 && filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { - - $email_subject = "Ticket created - [$ticket_prefix$ticket_number] - $ticket_subject (scheduled)"; - $email_body = "##- Please type your reply above this line -##

Hello $contact_name,

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

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

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

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - - $email = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $email_subject, - 'body' => $email_body - ]; - - $data[] = $email; - - } - - // Notify agent's via the DL address of the new ticket, if it's populated with a valid email - if (filter_var($config_ticket_new_ticket_notification_email, FILTER_VALIDATE_EMAIL)) { - - $email_subject = "ITFlow - New Recurring Ticket - $client_name: $ticket_subject"; - $email_body = "Hello,

This is a notification that a recurring (scheduled) ticket has been raised in ITFlow.
Ticket: $ticket_prefix$ticket_number
Client: $client_name
Priority: $priority
Link: https://$config_base_url/ticket.php?ticket_id=$id

--------------------------------

$ticket_subject
$ticket_details"; - - $email = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $config_ticket_new_ticket_notification_email, - 'recipient_name' => $config_ticket_from_name, - 'subject' => $email_subject, - 'body' => $email_body - ]; - - $data[] = $email; - } - - // Add to the mail queue - addToMailQueue($data); - - // 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"); - - } -} - -// Logging -// logAction("Cron", "Task", "Cron created sent out recurring tickets"); - - -// TICKET RESOLUTION/CLOSURE PROCESS -// Changes tickets status from 'Resolved' >> 'Closed' after a defined interval - -$sql_resolved_tickets_to_close = mysqli_query( - $mysqli, - "SELECT * FROM tickets - WHERE ticket_status = 4 - AND ticket_updated_at < NOW() - INTERVAL $config_ticket_autoclose_hours HOUR" -); - -while ($row = mysqli_fetch_array($sql_resolved_tickets_to_close)) { - - $ticket_id = $row['ticket_id']; - $ticket_prefix = sanitizeInput($row['ticket_prefix']); - $ticket_number = intval($row['ticket_number']); - $ticket_subject = sanitizeInput($row['ticket_subject']); - $ticket_status = sanitizeInput($row['ticket_status']); - $ticket_assigned_to = sanitizeInput($row['ticket_assigned_to']); - $client_id = intval($row['ticket_client_id']); - - mysqli_query($mysqli,"UPDATE tickets SET ticket_status = 5, ticket_closed_at = NOW(), ticket_closed_by = $ticket_assigned_to WHERE ticket_id = $ticket_id"); - - //Logging - logAction("Ticket", "Closed", "$ticket_prefix$ticket_number auto closed", $client_id, $ticket_id); - - customAction('ticket_close', $ticket_id); - - //TODO: Add client notifs if $config_ticket_client_general_notifications is on -} - -if ($config_send_invoice_reminders == 1) { - - // 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,650,680,710,740]; - - foreach ($invoiceAlertArray as $day) { - - $sql = mysqli_query( - $mysqli, - "SELECT * FROM invoices - LEFT JOIN clients ON invoice_client_id = client_id - LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1 - WHERE invoice_status != 'Draft' - AND invoice_status != 'Paid' - AND invoice_status != 'Cancelled' - AND invoice_status != 'Non-Billable' - AND DATE_ADD(invoice_due, INTERVAL $day DAY) = CURDATE() - ORDER BY invoice_number DESC" - ); - - while ($row = mysqli_fetch_array($sql)) { - $invoice_id = intval($row['invoice_id']); - $invoice_prefix = sanitizeInput($row['invoice_prefix']); - $invoice_number = intval($row['invoice_number']); - $invoice_status = sanitizeInput($row['invoice_status']); - $invoice_date = sanitizeInput($row['invoice_date']); - $invoice_due = sanitizeInput($row['invoice_due']); - $invoice_url_key = sanitizeInput($row['invoice_url_key']); - $invoice_amount = floatval($row['invoice_amount']); - $invoice_currency_code = sanitizeInput($row['invoice_currency_code']); - $client_id = intval($row['client_id']); - $client_name = sanitizeInput($row['client_name']); - $contact_name = sanitizeInput($row['contact_name']); - $contact_email = sanitizeInput($row['contact_email']); - - // Late Charges - - if ($config_invoice_late_fee_enable == 1) { - - $todays_date = date('Y-m-d'); - $late_fee_amount = ($invoice_amount * $config_invoice_late_fee_percent) / 100; - $new_invoice_amount = $invoice_amount + $late_fee_amount; - - mysqli_query($mysqli, "UPDATE invoices SET invoice_amount = $new_invoice_amount WHERE invoice_id = $invoice_id"); - - //Insert Items into New Invoice - mysqli_query($mysqli, "INSERT INTO invoice_items SET item_name = 'Late Fee', item_description = '$config_invoice_late_fee_percent% late fee applied on $todays_date', item_quantity = 1, item_price = $late_fee_amount, item_total = $late_fee_amount, item_order = 998, item_invoice_id = $invoice_id"); - - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron applied a late fee of $late_fee_amount', history_invoice_id = $invoice_id"); - - appNotify("Invoice Late Charge", "Invoice $invoice_prefix$invoice_number for $client_name in the amount of $invoice_amount was charged a late fee of $late_fee_amount", "invoice.php?invoice_id=$invoice_id", $client_id); - - } - - appNotify("Invoice Overdue", "Invoice $invoice_prefix$invoice_number for $client_name in the amount of $invoice_amount is overdue by $day days", "invoice.php?invoice_id=$invoice_id", $client_id); - - $subject = "Overdue Invoice $invoice_prefix$invoice_number"; - $body = "Hello $contact_name,

Our records indicate that we have not yet received payment for the invoice $invoice_prefix$invoice_number. We kindly request that you submit your payment as soon as possible. If you have any questions or concerns, please do not hesitate to contact us at $company_email or $company_phone. -

- Kindly review the invoice details mentioned 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
Over Due By: $day Days


To view your invoice, please click here.


--
$company_name - Billing
$config_invoice_from_email
$company_phone"; - - $mail = addToMailQueue([ - [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ] - ]); - - if ($mail === true) { - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Emailed Overdue Invoice', history_invoice_id = $invoice_id"); - } else { - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Failed to send Overdue Invoice', history_invoice_id = $invoice_id"); - - appNotify("Mail", "Failed to send email to $contact_email"); - - // Logging - logApp("Mail", "error", "Failed to send email to $contact_email regarding $subject. $mail"); - } - - } - - } -} -// Logging -// logAction("Cron", "Task", "Cron created notifications for past due invoices and sent out notifications to the primary and billing contacts email"); - -// 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 recurring_payments ON recurring_id = recurring_payment_recurring_invoice_id - LEFT JOIN clients ON client_id = recurring_client_id - WHERE recurring_next_date = CURDATE() - AND recurring_status = 1 -"); - -while ($row = mysqli_fetch_array($sql_recurring)) { - $recurring_id = intval($row['recurring_id']); - $recurring_scope = sanitizeInput($row['recurring_scope']); - $recurring_frequency = sanitizeInput($row['recurring_frequency']); - $recurring_status = sanitizeInput($row['recurring_status']); - $recurring_last_sent = sanitizeInput($row['recurring_last_sent']); - $recurring_next_date = sanitizeInput($row['recurring_next_date']); - $recurring_discount_amount = floatval($row['recurring_discount_amount']); - $recurring_amount = floatval($row['recurring_amount']); - $recurring_currency_code = sanitizeInput($row['recurring_currency_code']); - $recurring_note = sanitizeInput($row['recurring_note']); - $recurring_invoice_email_notify = intval($row['recurring_invoice_email_notify']); - $category_id = intval($row['recurring_category_id']); - $client_id = intval($row['recurring_client_id']); - $client_name = sanitizeInput($row['client_name']); - $client_net_terms = intval($row['client_net_terms']); - - $recurring_payment_recurring_invoice_id = intval($row['recurring_payment_recurring_invoice_id']); - $recurring_payment_currency_code = sanitizeInput($row['recurring_payment_currency_code']); - $recurring_payment_method = sanitizeInput($row['recurring_payment_method']); - $recurring_payment_account_id = intval($row['recurring_payment_account_id']); - - // 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 = 1"); - $row = mysqli_fetch_array($sql_invoice_number); - $config_invoice_next_number = intval($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 = 1"); - - //Generate a unique URL key for clients to access - $url_key = randomString(156); - - 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_discount_amount = $recurring_discount_amount, 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_client_id = $client_id"); - - $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"); - - while ($row = mysqli_fetch_array($sql_invoice_items)) { - $item_id = intval($row['item_id']); - $item_name = sanitizeInput($row['item_name']); //SQL Escape incase of , - $item_description = sanitizeInput($row['item_description']); //SQL Escape incase of , - $item_quantity = floatval($row['item_quantity']); - $item_price = floatval($row['item_price']); - $item_subtotal = floatval($row['item_subtotal']); - $item_tax = floatval($row['item_tax']); - $item_total = floatval($row['item_total']); - $item_order = intval($row['item_order']); - $tax_id = intval($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_order = $item_order, item_tax_id = $tax_id, item_invoice_id = $new_invoice_id"); - - } - - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Invoice Generated from Recurring!', history_invoice_id = $new_invoice_id"); - - appNotify("Recurring Sent", "Recurring Invoice $config_invoice_prefix$new_invoice_number for $client_name Sent", "invoice.php?invoice_id=$new_invoice_id", $client_id); - - customAction('invoice_create', $new_invoice_id); - - //Update recurring dates - - mysqli_query($mysqli, "UPDATE recurring SET recurring_last_sent = CURDATE(), recurring_next_date = DATE_ADD(CURDATE(), INTERVAL 1 $recurring_frequency) WHERE recurring_id = $recurring_id"); - - if ($config_recurring_auto_send_invoice == 1 && $recurring_invoice_email_notify == 1) { - $sql = mysqli_query( - $mysqli, - "SELECT * FROM invoices - LEFT JOIN clients ON invoice_client_id = client_id - LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1 - WHERE invoice_id = $new_invoice_id" - ); - - $row = mysqli_fetch_array($sql); - $invoice_prefix = sanitizeInput($row['invoice_prefix']); - $invoice_number = intval($row['invoice_number']); - $invoice_scope = sanitizeInput($row['invoice_scope']); - $invoice_date = sanitizeInput($row['invoice_date']); - $invoice_due = sanitizeInput($row['invoice_due']); - $invoice_amount = floatval($row['invoice_amount']); - $invoice_url_key = sanitizeInput($row['invoice_url_key']); - $client_id = intval($row['client_id']); - $client_name = sanitizeInput($row['client_name']); - $contact_name = sanitizeInput($row['contact_name']); - $contact_email = sanitizeInput($row['contact_email']); - - $subject = "Invoice $invoice_prefix$invoice_number"; - $body = "Hello $contact_name,

An invoice regarding \"$invoice_scope\" has been generated. Please view the details 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, please click here.


--
$company_name - Billing
$config_invoice_from_email
$company_phone"; - - $mail = addToMailQueue([ - [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject, - 'body' => $body - ] - ]); - - if ($mail === true) { - mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Emailed Invoice!', history_invoice_id = $new_invoice_id"); - mysqli_query($mysqli, "UPDATE invoices SET invoice_status = 'Sent', 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_invoice_id = $new_invoice_id"); - - appNotify("Mail", "Failed to send email to $contact_email"); - - // Logging - logApp("Mail", "error", "Failed to send email to $contact_email regarding $subject. $mail"); - - } - - // Send copies of the invoice to any additional billing contacts - $sql_billing_contacts = mysqli_query($mysqli, "SELECT contact_name, contact_email FROM contacts - WHERE contact_billing = 1 - AND contact_email != '$contact_email' - AND contact_client_id = $client_id" - ); - - while ($billing_contact = mysqli_fetch_array($sql_billing_contacts)) { - $billing_contact_name = sanitizeInput($billing_contact['contact_name']); - $billing_contact_email = sanitizeInput($billing_contact['contact_email']); - - $data = [ - [ - 'from' => $config_invoice_from_email, - 'from_name' => $config_invoice_from_name, - 'recipient' => $billing_contact_email, - 'recipient_name' => $billing_contact_name, - 'subject' => $subject, - 'body' => $body - ] - ]; - - addToMailQueue($data); - } - - } //End if Autosend is on - - // Create Payment from Auto Payment - if ($recurring_payment_recurring_invoice_id) { - mysqli_query($mysqli,"INSERT INTO payments SET payment_date = CURDATE(), payment_amount = $recurring_amount, payment_currency_code = '$recurring_payment_currency_code', payment_account_id = $recurring_payment_account_id, payment_method = '$recurring_payment_method', payment_reference = 'Paid via AutoPay', payment_invoice_id = $new_invoice_id"); - - // Get Payment ID for reference - $payment_id = mysqli_insert_id($mysqli); - - // Update Invoice Status - mysqli_query($mysqli,"UPDATE invoices SET invoice_status = 'Paid' WHERE invoice_id = $new_invoice_id"); - - //Add Payment to History - mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Paid', history_description = 'Payment added via Auto Pay', history_invoice_id = $new_invoice_id"); - - // Logging - logAction("Invoice", "Payment", "Auto Payment amount of " . numfmt_format_currency($currency_format, $recurring_amount, $recurring_payment_currency_code) . " added to invoice $invoice_prefix$invoice_number", $client_id, $new_invoice_id); - } //End Auto Payment - -} //End Recurring Invoices Loop - -// Logging -// logAction("Cron", "Task", "Cron created invoices from recurring invoices and sent emails out"); - -// Recurring Expenses -// Loop through all recurring expenses that match today's date and is active -$sql_recurring_expenses = mysqli_query($mysqli, "SELECT * FROM recurring_expenses WHERE recurring_expense_next_date = CURDATE() AND recurring_expense_status = 1"); - -while ($row = mysqli_fetch_array($sql_recurring_expenses)) { - $recurring_expense_id = intval($row['recurring_expense_id']); - $recurring_expense_frequency = intval($row['recurring_expense_frequency']); - $recurring_expense_month = intval($row['recurring_expense_month']); - $recurring_expense_day = intval($row['recurring_expense_day']); - $recurring_expense_description = sanitizeInput($row['recurring_expense_description']); - $recurring_expense_amount = floatval($row['recurring_expense_amount']); - $recurring_expense_payment_method = sanitizeInput($row['recurring_expense_payment_method']); - $recurring_expense_reference = sanitizeInput($row['recurring_expense_reference']); - $recurring_expense_currency_code = sanitizeInput($row['recurring_expense_currency_code']); - $recurring_expense_vendor_id = intval($row['recurring_expense_vendor_id']); - $recurring_expense_category_id = intval($row['recurring_expense_category_id']); - $recurring_expense_account_id = intval($row['recurring_expense_account_id']); - $recurring_expense_client_id = intval($row['recurring_expense_client_id']); - - // Calculate next billing date based on frequency - if ($recurring_expense_frequency == 1) { // Monthly - $next_date_query = "DATE_ADD(CURDATE(), INTERVAL 1 MONTH)"; - } elseif ($recurring_expense_frequency == 2) { // Yearly - $next_date_query = "DATE(CONCAT(YEAR(CURDATE()) + 1, '-', $recurring_expense_month, '-', $recurring_expense_day))"; - } else { - // Handle unexpected frequency values. For now, just use current date. - $next_date_query = "CURDATE()"; - } - - mysqli_query($mysqli,"INSERT INTO expenses SET expense_date = CURDATE(), expense_amount = $recurring_expense_amount, expense_currency_code = '$recurring_expense_currency_code', expense_account_id = $recurring_expense_account_id, expense_vendor_id = $recurring_expense_vendor_id, expense_client_id = $recurring_expense_client_id, expense_category_id = $recurring_expense_category_id, expense_description = '$recurring_expense_description', expense_reference = '$recurring_expense_reference'"); - - $expense_id = mysqli_insert_id($mysqli); - - appNotify("Expense Created", "Expense $recurring_expense_description created from recurring expenses", "expenses.php", $recurring_expense_client_id); - - // Update recurring dates using calculated next billing date - - mysqli_query($mysqli, "UPDATE recurring_expenses SET recurring_expense_last_sent = CURDATE(), recurring_expense_next_date = $next_date_query WHERE recurring_expense_id = $recurring_expense_id"); - - -} //End Recurring Invoices Loop - -// Logging -logApp("Cron", "info", "Cron created expenses from recurring expenses"); - -// TELEMETRY - -if ($config_telemetry > 0 || $config_telemetry == 2) { - - $current_version = exec("git rev-parse HEAD"); - - // Client Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('client_id') AS num FROM clients")); - $client_count = $row['num']; - - // Ticket Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('recurring_id') AS num FROM tickets")); - $ticket_count = $row['num']; - - // Recurring (Scheduled) Ticket Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('scheduled_ticket_id') AS num FROM scheduled_tickets")); - $scheduled_ticket_count = $row['num']; - - // Calendar Event Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('event_id') AS num FROM events")); - $calendar_event_count = $row['num']; - - // Quote Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('quote_id') AS num FROM quotes")); - $quote_count = $row['num']; - - // Invoice Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('invoice_id') AS num FROM invoices")); - $invoice_count = $row['num']; - - // Revenue Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('revenue_id') AS num FROM revenues")); - $revenue_count = $row['num']; - - // Recurring Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('recurring_id') AS num FROM recurring")); - $recurring_count = $row['num']; - - // Account Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('account_id') AS num FROM accounts")); - $account_count = $row['num']; - - // Tax Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('tax_id') AS num FROM taxes")); - $tax_count = $row['num']; - - // Product Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('product_id') AS num FROM products")); - $product_count = $row['num']; - - // Payment Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('payment_id') AS num FROM payments WHERE payment_invoice_id > 0")); - $payment_count = $row['num']; - - // Company Vendor Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('vendor_id') AS num FROM vendors WHERE vendor_template = 0 AND vendor_client_id = 0")); - $company_vendor_count = $row['num']; - - // Expense Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('expense_id') AS num FROM expenses WHERE expense_vendor_id > 0")); - $expense_count = $row['num']; - - // Trip Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('trip_id') AS num FROM trips")); - $trip_count = $row['num']; - - // Transfer Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('transfer_id') AS num FROM transfers")); - $transfer_count = $row['num']; - - // Contact Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('contact_id') AS num FROM contacts")); - $contact_count = $row['num']; - - // Location Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('location_id') AS num FROM locations")); - $location_count = $row['num']; - - // Asset Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('asset_id') AS num FROM assets")); - $asset_count = $row['num']; - - // Software Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('software_id') AS num FROM software WHERE software_template = 0")); - $software_count = $row['num']; - - // Software Template Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('software_id') AS num FROM software WHERE software_template = 1")); - $software_template_count = $row['num']; - - // Password Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('login_id') AS num FROM logins")); - $password_count = $row['num']; - - // Network Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('network_id') AS num FROM networks")); - $network_count = $row['num']; - - // Certificate Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('certificate_id') AS num FROM certificates")); - $certificate_count = $row['num']; - - // Domain Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('domain_id') AS num FROM domains")); - $domain_count = $row['num']; - - // Service Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('service_id') AS num FROM services")); - $service_count = $row['num']; - - // Client Vendor Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('vendor_id') AS num FROM vendors WHERE vendor_template = 0 AND vendor_client_id > 0")); - $client_vendor_count = $row['num']; - - // Vendor Template Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('vendor_id') AS num FROM vendors WHERE vendor_template = 1")); - $vendor_template_count = $row['num']; - - // File Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('file_id') AS num FROM files")); - $file_count = $row['num']; - - // Document Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('document_id') AS num FROM documents WHERE document_template = 0")); - $document_count = $row['num']; - - // Document Template Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('document_id') AS num FROM documents WHERE document_template = 1")); - $document_template_count = $row['num']; - - // Shared Item Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('item_id') AS num FROM shared_items")); - $shared_item_count = $row['num']; - - // Company Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('company_id') AS num FROM companies")); - $company_count = $row['num']; - - // User Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('user_id') AS num FROM users")); - $user_count = $row['num']; - - // Category Expense Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('category_id') AS num FROM categories WHERE category_type = 'Expense'")); - $category_expense_count = $row['num']; - - // Category Income Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('category_id') AS num FROM categories WHERE category_type = 'Income'")); - $category_income_count = $row['num']; - - // Category Referral Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('category_id') AS num FROM categories WHERE category_type = 'Referral'")); - $category_referral_count = $row['num']; - - // Category Payment Method Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('category_id') AS num FROM categories WHERE category_type = 'Payment Method'")); - $category_payment_method_count = $row['num']; - - // Tag Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('tag_id') AS num FROM tags")); - $tag_count = $row['num']; - - // API Key Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('api_key_id') AS num FROM api_keys")); - $api_key_count = $row['num']; - - // Log Count - $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('log_id') AS num FROM logs")); - $log_count = $row['num']; - - $postdata = http_build_query( - array( - 'installation_id' => "$installation_id", - 'version' => "$current_version", - 'company_name' => "$company_name", - 'website' => "$company_website", - 'city' => "$company_city", - 'state' => "$company_state", - 'country' => "$company_country", - 'currency' => "$company_currency", - 'client_count' => $client_count, - 'ticket_count' => $ticket_count, - 'scheduled_ticket_count' => $scheduled_ticket_count, - 'calendar_event_count' => $calendar_event_count, - 'quote_count' => $quote_count, - 'invoice_count' => $invoice_count, - 'revenue_count' => $revenue_count, - 'recurring_count' => $recurring_count, - 'account_count' => $account_count, - 'tax_count' => $tax_count, - 'product_count' => $product_count, - 'payment_count' => $payment_count, - 'company_vendor_count' => $company_vendor_count, - 'expense_count' => $expense_count, - 'trip_count' => $trip_count, - 'transfer_count' => $transfer_count, - 'contact_count' => $contact_count, - 'location_count' => $location_count, - 'asset_count' => $asset_count, - 'software_count' => $software_count, - 'software_template_count' => $software_template_count, - 'password_count' => $password_count, - 'network_count' => $network_count, - 'certificate_count' => $certificate_count, - 'domain_count' => $domain_count, - 'service_count' => $service_count, - 'client_vendor_count' => $client_vendor_count, - 'vendor_template_count' => $vendor_template_count, - 'file_count' => $file_count, - 'document_count' => $document_count, - 'document_template_count' => $document_template_count, - 'shared_item_count' => $shared_item_count, - 'company_count' => $company_count, - 'user_count' => $user_count, - 'category_expense_count' => $category_expense_count, - 'category_income_count' => $category_income_count, - 'category_referral_count' => $category_referral_count, - 'category_payment_method_count' => $category_payment_method_count, - 'tag_count' => $tag_count, - 'api_key_count' => $api_key_count, - 'log_count' => $log_count, - 'config_theme' => "$config_theme", - 'config_enable_cron' => $config_enable_cron, - 'config_ticket_email_parse' => $config_ticket_email_parse, - 'config_module_enable_itdoc' => $config_module_enable_itdoc, - 'config_module_enable_ticketing' => $config_module_enable_ticketing, - 'config_module_enable_accounting' => $config_module_enable_accounting, - 'config_telemetry' => $config_telemetry, - 'collection_method' => 3 - ) - ); - - $opts = array('http' => - array( - 'method' => 'POST', - 'header' => 'Content-type: application/x-www-form-urlencoded', - 'content' => $postdata - ) - ); - - $context = stream_context_create($opts); - - $result = file_get_contents('https://telemetry.itflow.org', false, $context); - - // Logging - // logAction("Cron", "Task", "Cron sent telemetry results to ITFlow Developers"); - -} - - -// Fetch Updates -$updates = fetchUpdates(); - -$update_message = $updates->update_message; - -if ($updates->current_version !== $updates->latest_version) { - // Send Alert to inform Updates Available - appNotify("Update", "$update_message", "admin_update.php"); -} - - - -/* - * ############################################################################################################### - * FINISH UP - * ############################################################################################################### - */ - -// Alert we're using the old cron path -appNotify("Cron", "Cron ran OK, but paths need updating - cron scripts are now in the scripts subfolder", "admin_audit_log.php"); - -// Logging -logApp("Cron", "info", "Cron executed successfully"); -logApp("Cron", "warning", "Cron ran using an old script path"); \ No newline at end of file diff --git a/cron_certificate_refresher.php b/cron_certificate_refresher.php deleted file mode 100644 index e7ffb1c4..00000000 --- a/cron_certificate_refresher.php +++ /dev/null @@ -1,69 +0,0 @@ - 600) { - - unlink($lock_file_path); - // Logging - logAction("Cron-Mail-Queue", "Delete", "Cron Mail Queuer detected a lock file was present but was over 10 minutes old so it removed it."); - - } else { - - // Logging - logAction("Cron-Mail-Queue", "Locked", "Cron Mail Queuer attempted to execute but was already executing so instead it terminated."); - - exit("Script is already running. Exiting."); - } -} - -// Create a lock file -file_put_contents($lock_file_path, "Locked"); - -// Process Mail Queue - -// Email Status: -// 0 Queued -// 1 Sending -// 2 Failed -// 3 Sent - -/* - * ############################################################################################################### - * Initial email send - * ############################################################################################################### - */ -// Get Mail Queue that has status of Queued and send it to the function sendSingleEmail() located in functions.php -$sql_queue = mysqli_query($mysqli, "SELECT * FROM email_queue WHERE email_status = 0 AND email_queued_at <= NOW()"); - -if (mysqli_num_rows($sql_queue) > 0) { - while ($row = mysqli_fetch_array($sql_queue)) { - $email_id = intval($row['email_id']); - $email_from = $row['email_from']; - $email_from_name = $row['email_from_name']; - $email_recipient = $row['email_recipient']; - $email_recipient_name = $row['email_recipient_name']; - $email_subject = $row['email_subject']; - $email_content = $row['email_content']; - $email_queued_at = $row['email_queued_at']; - $email_sent_at = $row['email_sent_at']; - $email_ics_str = $row['email_cal_str']; - - // First, validate the sender email address - if (filter_var($email_from, FILTER_VALIDATE_EMAIL)) { - - // Sanitized Input - $email_recipient_logging = sanitizeInput($row['email_recipient']); - $email_subject_logging = sanitizeInput($row['email_subject']); - - // Update the status to sending - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id"); - - // Next, verify recipient email is valid - if (filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) { - - $mail = sendSingleEmail( - $config_smtp_host, - $config_smtp_username, - $config_smtp_password, - $config_smtp_encryption, - $config_smtp_port, - $email_from, - $email_from_name, - $email_recipient, - $email_recipient_name, - $email_subject, - $email_content, - $email_ics_str - ); - - if ($mail !== true) { - // Update Message - Failure - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = 1 WHERE email_id = $email_id"); - - appNotify("Cron-Mail-Queue", "Failed to send email #$email_id to $email_recipient_logging"); - - // Logging - logAction("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_recipient_logging regarding $email_subject_logging. $mail"); - } else { - // Update Message - Success - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = 1 WHERE email_id = $email_id"); - } - - } else { - - // Recipient email isn't valid, mark as failed and log the error - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99 WHERE email_id = $email_id"); - - // Logging - logAction("Cron-Mail-Queue", "Error", "Failed to send email: $email_id due to invalid recipient address. Email subject was: $email_subject_logging"); - } - - } else { - error_log("Failed to send email due to invalid sender address (' $email_from ') - check configuration in settings."); - - $email_from_logging = sanitizeInput($row['email_from']); - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99 WHERE email_id = $email_id"); - - // Logging - logAction("Cron-Mail-Queue", "Error", "Failed to send email #$email_id due to invalid sender address: $email_from_logging - check configuration in settings."); - - appNotify("Mail", "Failed to send email #$email_id due to invalid sender address"); - - } - - } -} - - -/* - * ############################################################################################################### - * Retries - * ############################################################################################################### - */ -// Get Mail that failed to send and attempt to send Failed Mail up to 4 times every 30 mins -$sql_failed_queue = mysqli_query($mysqli, "SELECT * FROM email_queue WHERE email_status = 2 AND email_attempts < 4 AND email_failed_at < NOW() + INTERVAL 30 MINUTE"); - -if (mysqli_num_rows($sql_failed_queue) > 0) { - while ($row = mysqli_fetch_array($sql_failed_queue)) { - $email_id = intval($row['email_id']); - $email_from = $row['email_from']; - $email_from_name = $row['email_from_name']; - $email_recipient = $row['email_recipient']; - $email_recipient_name = $row['email_recipient_name']; - $email_subject = $row['email_subject']; - $email_content = $row['email_content']; - $email_queued_at = $row['email_queued_at']; - $email_sent_at = $row['email_sent_at']; - $email_ics_str = $row['email_cal_str']; - // Increment the attempts - $email_attempts = intval($row['email_attempts']) + 1; - - // Sanitized Input - $email_recipient_logging = sanitizeInput($row['email_recipient']); - $email_subject_logging = sanitizeInput($row['email_subject']); - - // Update the status to sending before actually sending - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id"); - - // Verify recipient email is valid - if (filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) { - - $mail = sendSingleEmail( - $config_smtp_host, - $config_smtp_username, - $config_smtp_password, - $config_smtp_encryption, - $config_smtp_port, - $email_from, - $email_from_name, - $email_recipient, - $email_recipient_name, - $email_subject, - $email_content, - $email_ics_str - ); - - if ($mail !== true) { - // Update Message - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = $email_attempts WHERE email_id = $email_id"); - - // Logging - logAction("Cron-Mail-Queue", "Error", "Failed to re-send email #$email_id to $email_recipient_logging regarding $email_subject_logging. $mail"); - - } else { - - // Update Message - mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = $email_attempts WHERE email_id = $email_id"); - - } - } - } -} - -// Remove the lock file once mail has finished processing -unlink($lock_file_path); diff --git a/cron_ticket_email_parser.php b/cron_ticket_email_parser.php deleted file mode 100644 index 61bcca50..00000000 --- a/cron_ticket_email_parser.php +++ /dev/null @@ -1,560 +0,0 @@ - Ticketing > Email-to-ticket parsing. See https://docs.itflow.org/ticket_email_parse -- Quitting.."); -} - -$argv = $_SERVER['argv']; - -// Check Cron Key -if ($argv[1] !== $config_cron_key) { - exit("Cron Key invalid -- Quitting.."); -} - -// Get system temp directory -$temp_dir = sys_get_temp_dir(); - -// Create the path for the lock file using the temp directory -$lock_file_path = "{$temp_dir}/itflow_email_parser_{$installation_id}.lock"; - -// Check for lock file to prevent concurrent script runs -if (file_exists($lock_file_path)) { - $file_age = time() - filemtime($lock_file_path); - - // If file is older than 5 minutes (300 seconds), delete and continue - if ($file_age > 300) { - unlink($lock_file_path); - - // Logging - logApp("Cron-Email-Parser", "warning", "Cron Email Parser detected a lock file was present but was over 5 minutes old so it removed it."); - - } else { - - // Logging - logApp("Cron-Email-Parser", "warning", "Lock file present. Cron Email Parser attempted to execute but was already executing, so instead it terminated."); - - exit("Script is already running. Exiting."); - } -} - -// Create a lock file -file_put_contents($lock_file_path, "Locked"); - -// PHP Mail Parser -use PhpMimeMailParser\Parser; -require_once "plugins/php-mime-mail-parser/Contracts/CharsetManager.php"; -require_once "plugins/php-mime-mail-parser/Contracts/Middleware.php"; -require_once "plugins/php-mime-mail-parser/Attachment.php"; -require_once "plugins/php-mime-mail-parser/Charset.php"; -require_once "plugins/php-mime-mail-parser/Exception.php"; -require_once "plugins/php-mime-mail-parser/Middleware.php"; -require_once "plugins/php-mime-mail-parser/MiddlewareStack.php"; -require_once "plugins/php-mime-mail-parser/MimePart.php"; -require_once "plugins/php-mime-mail-parser/Parser.php"; - -// Allowed attachment extensions -$allowed_extensions = array('jpg', 'jpeg', 'gif', 'png', 'webp', 'pdf', 'txt', 'md', 'doc', 'docx', 'csv', 'xls', 'xlsx', 'xlsm', 'zip', 'tar', 'gz'); - -// Function to raise a new ticket for a given contact and email them confirmation (if configured) -function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file) { - global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_ticket_client_general_notifications, $config_ticket_new_ticket_notification_email, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $allowed_extensions; - - $ticket_number_sql = mysqli_fetch_array(mysqli_query($mysqli, "SELECT config_ticket_next_number FROM settings WHERE company_id = 1")); - $ticket_number = intval($ticket_number_sql['config_ticket_next_number']); - $new_config_ticket_next_number = $ticket_number + 1; - mysqli_query($mysqli, "UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = 1"); - - // Clean up the message - $message = trim($message); // Remove leading/trailing whitespace - $message = preg_replace('/\s+/', ' ', $message); // Replace multiple spaces with a single space - $message = nl2br($message); // Convert newlines to
- - // Wrap the message in a div with controlled line height - $message = "Email from: $contact_name <$contact_email> at $date:-

$message
"; - - $ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix); - $message_esc = mysqli_real_escape_string($mysqli, $message); - $contact_email_esc = mysqli_real_escape_string($mysqli, $contact_email); - $client_id = intval($client_id); - - //Generate a unique URL key for clients to access - $url_key = randomString(156); - - mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$ticket_prefix_esc', ticket_number = $ticket_number, ticket_subject = '$subject', ticket_details = '$message_esc', ticket_priority = 'Low', ticket_status = 1, ticket_created_by = 0, ticket_contact_id = $contact_id, ticket_url_key = '$url_key', ticket_client_id = $client_id"); - $id = mysqli_insert_id($mysqli); - - // Logging - logAction("Ticket", "Create", "Email parser: Client contact $contact_email_esc created ticket $ticket_prefix_esc$ticket_number ($subject) ($id)", $client_id, $id); - - mkdirMissing('uploads/tickets/'); - $att_dir = "uploads/tickets/" . $id . "/"; - mkdirMissing($att_dir); - - rename("uploads/tmp/{$original_message_file}", "{$att_dir}/{$original_message_file}"); - $original_message_file_esc = mysqli_real_escape_string($mysqli, $original_message_file); - mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = 'Original-parsed-email.eml', ticket_attachment_reference_name = '$original_message_file_esc', ticket_attachment_ticket_id = $id"); - - foreach ($attachments as $attachment) { - $att_name = $attachment->getFilename(); - $att_extarr = explode('.', $att_name); - $att_extension = strtolower(end($att_extarr)); - - if (in_array($att_extension, $allowed_extensions)) { - $att_saved_filename = md5(uniqid(rand(), true)) . '.' . $att_extension; - $att_saved_path = $att_dir . $att_saved_filename; - file_put_contents($att_saved_path, $attachment->getContent()); - - $ticket_attachment_name = sanitizeInput($att_name); - $ticket_attachment_reference_name = sanitizeInput($att_saved_filename); - - $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_name); - $ticket_attachment_reference_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_reference_name); - mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_ticket_id = $id"); - } else { - $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name); - logAction("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $contact_email_esc for ticket $ticket_prefix_esc$ticket_number", $client_id, $id); - } - } - - // Guest ticket watchers - if ($client_id == 0) { - mysqli_query($mysqli, "INSERT INTO ticket_watchers SET watcher_email = '$contact_email_esc', watcher_ticket_id = $id"); - } - - $data = []; - if ($config_ticket_client_general_notifications == 1) { - $subject_email = "Ticket created - [$config_ticket_prefix$ticket_number] - $subject"; - $body = "##- Please type your reply above this line -##

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: New
https://$config_base_url/client/ticket.php?id=$id

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $contact_email, - 'recipient_name' => $contact_name, - 'subject' => $subject_email, - 'body' => mysqli_real_escape_string($mysqli, $body) - ]; - } - - if ($config_ticket_new_ticket_notification_email) { - if ($client_id == 0) { - $client_name = "Guest"; - } else { - $client_sql = mysqli_query($mysqli, "SELECT client_name FROM clients WHERE client_id = $client_id"); - $client_row = mysqli_fetch_array($client_sql); - $client_name = sanitizeInput($client_row['client_name']); - } - $email_subject = "$config_app_name - New Ticket - $client_name: $subject"; - $email_body = "Hello,

This is a notification that a new ticket has been raised in ITFlow.
Client: $client_name
Priority: Low (email parsed)
Link: https://$config_base_url/ticket.php?ticket_id=$id

--------------------------------

$subject
$message"; - - $data[] = [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $config_ticket_new_ticket_notification_email, - 'recipient_name' => $config_ticket_from_name, - 'subject' => $email_subject, - 'body' => mysqli_real_escape_string($mysqli, $email_body) - ]; - } - - addToMailQueue($data); - - // Custom action/notif handler - customAction('ticket_create', $id); - - return true; -} - -// Add Reply Function -function addReply($from_email, $date, $subject, $ticket_number, $message, $attachments) { - global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $allowed_extensions; - - $ticket_reply_type = 'Client'; - // Clean up the message - $message_parts = explode("##- Please type your reply above this line -##", $message); - $message_body = $message_parts[0]; - $message_body = trim($message_body); // Remove leading/trailing whitespace - $message_body = preg_replace('/\r\n|\r|\n/', ' ', $message_body); // Replace newlines with a space - $message_body = nl2br($message_body); // Convert remaining newlines to
- - // Wrap the message in a div with controlled line height - $message = "Email from: $from_email at $date:-

$message_body
"; - - $ticket_number_esc = intval($ticket_number); - $message_esc = mysqli_real_escape_string($mysqli, $message); - $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); - - $row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT ticket_id, ticket_subject, ticket_status, ticket_contact_id, ticket_client_id, contact_email, client_name - FROM tickets - LEFT JOIN contacts on tickets.ticket_contact_id = contacts.contact_id - LEFT JOIN clients on tickets.ticket_client_id = clients.client_id - WHERE ticket_number = $ticket_number_esc LIMIT 1")); - - if ($row) { - $ticket_id = intval($row['ticket_id']); - $ticket_subject = sanitizeInput($row['ticket_subject']); - $ticket_status = sanitizeInput($row['ticket_status']); - $ticket_reply_contact = intval($row['ticket_contact_id']); - $ticket_contact_email = sanitizeInput($row['contact_email']); - $client_id = intval($row['ticket_client_id']); - $client_name = sanitizeInput($row['client_name']); - - if ($ticket_status == 5) { - $config_ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix); - $ticket_number_esc = mysqli_real_escape_string($mysqli, $ticket_number); - - appNotify("Ticket", "Email parser: $from_email attempted to re-open ticket $config_ticket_prefix_esc$ticket_number_esc (ID $ticket_id) - check inbox manually to see email", "ticket.php?ticket_id=$ticket_id", $client_id); - - $email_subject = "Action required: This ticket is already closed"; - $email_body = "Hi there,

You've tried to reply to a ticket that is closed - we won't see your response.

Please raise a new ticket by sending a new e-mail to our support address below.

--
$company_name - Support
$config_ticket_from_email
$company_phone"; - - $data = [ - [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $from_email, - 'recipient_name' => $from_email, - 'subject' => $email_subject, - 'body' => mysqli_real_escape_string($mysqli, $email_body) - ] - ]; - - addToMailQueue($data); - - return true; - } - - if (empty($ticket_contact_email) || $ticket_contact_email !== $from_email) { - $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); - $row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE contact_email = '$from_email_esc' AND contact_client_id = $client_id LIMIT 1")); - if ($row) { - $ticket_reply_contact = intval($row['contact_id']); - } else { - $ticket_reply_type = 'Internal'; - $ticket_reply_contact = '0'; - $message = "WARNING: Contact email mismatch
$message"; - $message_esc = mysqli_real_escape_string($mysqli, $message); - } - } - - mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$message_esc', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $ticket_reply_contact, ticket_reply_ticket_id = $ticket_id"); - $reply_id = mysqli_insert_id($mysqli); - - mkdirMissing('uploads/tickets/'); - foreach ($attachments as $attachment) { - $att_name = $attachment->getFilename(); - $att_extarr = explode('.', $att_name); - $att_extension = strtolower(end($att_extarr)); - - if (in_array($att_extension, $allowed_extensions)) { - $att_saved_filename = md5(uniqid(rand(), true)) . '.' . $att_extension; - $att_saved_path = "uploads/tickets/" . $ticket_id . "/" . $att_saved_filename; - file_put_contents($att_saved_path, $attachment->getContent()); - - $ticket_attachment_name = sanitizeInput($att_name); - $ticket_attachment_reference_name = sanitizeInput($att_saved_filename); - - $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_name); - $ticket_attachment_reference_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_reference_name); - mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id"); - } else { - $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name); - logAction("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $from_email_esc for ticket $config_ticket_prefix$ticket_number_esc", $client_id, $ticket_id); - } - } - - $ticket_assigned_to_sql = mysqli_query($mysqli, "SELECT ticket_assigned_to FROM tickets WHERE ticket_id = $ticket_id LIMIT 1"); - - if ($ticket_assigned_to_sql) { - $row = mysqli_fetch_array($ticket_assigned_to_sql); - $ticket_assigned_to = intval($row['ticket_assigned_to']); - - if ($ticket_assigned_to) { - $tech_sql = mysqli_query($mysqli, "SELECT user_email, user_name FROM users WHERE user_id = $ticket_assigned_to LIMIT 1"); - $tech_row = mysqli_fetch_array($tech_sql); - $tech_email = sanitizeInput($tech_row['user_email']); - $tech_name = sanitizeInput($tech_row['user_name']); - - $email_subject = "$config_app_name - Ticket updated - [$config_ticket_prefix$ticket_number] $ticket_subject"; - $email_body = "Hello $tech_name,

A new reply has been added to the below ticket, check ITFlow for full details.

Client: $client_name
Ticket: $config_ticket_prefix$ticket_number
Subject: $ticket_subject

https://$config_base_url/ticket.php?ticket_id=$ticket_id"; - - $data = [ - [ - 'from' => $config_ticket_from_email, - 'from_name' => $config_ticket_from_name, - 'recipient' => $tech_email, - 'recipient_name' => $tech_name, - 'subject' => mysqli_real_escape_string($mysqli, $email_subject), - 'body' => mysqli_real_escape_string($mysqli, $email_body) - ] - ]; - - addToMailQueue($data); - } - } - - mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 2, ticket_resolved_at = NULL WHERE ticket_id = $ticket_id AND ticket_client_id = $client_id LIMIT 1"); - - logAction("Ticket", "Edit", "Email parser: Client contact $from_email_esc updated ticket $config_ticket_prefix$ticket_number_esc ($subject)", $client_id, $ticket_id); - - customAction('ticket_reply_client', $ticket_id); - - return true; - - } else { - return false; - } -} - -// Function to create a folder in the mailbox if it doesn't exist -function createMailboxFolder($imap, $mailbox, $folderName) { - $folders = imap_list($imap, $mailbox, '*'); - $folderExists = false; - if ($folders !== false) { - foreach ($folders as $folder) { - $folder = str_replace($mailbox, '', $folder); - if ($folder == $folderName) { - $folderExists = true; - break; - } - } - } - if (!$folderExists) { - imap_createmailbox($imap, $mailbox . imap_utf7_encode($folderName)); - imap_subscribe($imap, $mailbox . $folderName); - } -} - -// Initialize IMAP connection -$validate_cert = true; // or false based on your configuration - -$imap_encryption = $config_imap_encryption; // e.g., 'ssl', 'tls', or '' (empty string) for none - -// Start building the mailbox string -$mailbox = '{' . $config_imap_host . ':' . $config_imap_port; - -// Only add the encryption part if $imap_encryption is not empty -if (!empty($imap_encryption)) { - $mailbox .= '/' . $imap_encryption; -} - -// Add the certificate validation part -if ($validate_cert) { - $mailbox .= '/validate-cert'; -} else { - $mailbox .= '/novalidate-cert'; -} - -$mailbox .= '}'; - -// Append 'INBOX' to specify the mailbox folder -$inbox_mailbox = $mailbox . 'INBOX'; - -// Open the IMAP connection -$imap = imap_open($inbox_mailbox, $config_imap_username, $config_imap_password); - -if ($imap === false) { - echo "Error connecting to IMAP server: " . imap_last_error(); - exit; -} - -// Create the "ITFlow" mailbox folder if it doesn't exist -createMailboxFolder($imap, $mailbox, 'ITFlow'); - -// Search for unseen messages and get UIDs -$emails = imap_search($imap, 'UNSEEN', SE_UID); - -// Set Processed and Unprocessed Email count to 0 -$processed_count = 0; -$unprocessed_count = 0; - -if ($emails !== false) { - foreach ($emails as $email_uid) { - $email_processed = false; - - // Save original message - mkdirMissing('uploads/tmp/'); - $original_message_file = "processed-eml-" . randomString(200) . ".eml"; - - $raw_message = imap_fetchheader($imap, $email_uid, FT_UID) . imap_body($imap, $email_uid, FT_UID); - file_put_contents("uploads/tmp/{$original_message_file}", $raw_message); - - // Parse the message using php-mime-mail-parser - $parser = new \PhpMimeMailParser\Parser(); - $parser->setText($raw_message); - - // Get from address - $from_addresses = $parser->getAddresses('from'); - $from_email = sanitizeInput($from_addresses[0]['address'] ?? 'itflow-guest@example.com'); - $from_name = sanitizeInput($from_addresses[0]['display'] ?? 'Unknown'); - - $from_domain = explode("@", $from_email); - $from_domain = sanitizeInput(end($from_domain)); - - // Get subject - $subject = sanitizeInput($parser->getHeader('subject') ?? 'No Subject'); - - // Get date - $date = sanitizeInput($parser->getHeader('date') ?? date('Y-m-d H:i:s')); - - // Get message body - $message_body_html = $parser->getMessageBody('html'); - $message_body_text = $parser->getMessageBody('text'); - $message_body = $message_body_html ?: nl2br(htmlspecialchars($message_body_text)); - - // Handle inline images - $attachments = $parser->getAttachments(); - $inline_attachments = []; - foreach ($attachments as $attachment) { - if ($attachment->getContentDisposition() === 'inline' && $attachment->getContentID()) { - $cid = trim($attachment->getContentID(), '<>'); - $data = base64_encode($attachment->getContent()); - $mime = $attachment->getContentType(); - $dataUri = "data:$mime;base64,$data"; - $message_body = str_replace("cid:$cid", $dataUri, $message_body); - } else { - $inline_attachments[] = $attachment; - } - } - $attachments = $inline_attachments; - - // Process the email - if (preg_match("/\[$config_ticket_prefix(\d+)\]/", $subject, $ticket_number_matches)) { - $ticket_number = intval($ticket_number_matches[1]); - - if (addReply($from_email, $date, $subject, $ticket_number, $message_body, $attachments)) { - $email_processed = true; - } - } else { - // Check if the sender is a known contact - $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); - $any_contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from_email_esc' LIMIT 1"); - $row = mysqli_fetch_array($any_contact_sql); - - if ($row) { - $contact_name = sanitizeInput($row['contact_name']); - $contact_id = intval($row['contact_id']); - $contact_email = sanitizeInput($row['contact_email']); - $client_id = intval($row['contact_client_id']); - - if (addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file)) { - $email_processed = true; - } - } else { - // Check if the domain is associated with a client - $from_domain_esc = mysqli_real_escape_string($mysqli, $from_domain); - $domain_sql = mysqli_query($mysqli, "SELECT * FROM domains WHERE domain_name = '$from_domain_esc' LIMIT 1"); - $row = mysqli_fetch_assoc($domain_sql); - - if ($row && $from_domain == $row['domain_name']) { - $client_id = intval($row['domain_client_id']); - - // Create a new contact - $contact_name = $from_name; - $contact_email = $from_email; - mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '".mysqli_real_escape_string($mysqli, $contact_name)."', contact_email = '".mysqli_real_escape_string($mysqli, $contact_email)."', contact_notes = 'Added automatically via email parsing.', contact_client_id = $client_id"); - $contact_id = mysqli_insert_id($mysqli); - - // Logging - logAction("Contact", "Create", "Email parser: created contact " . mysqli_real_escape_string($mysqli, $contact_name) . "", $client_id, $contact_id); - customAction('contact_create', $contact_id); - - if (addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file)) { - $email_processed = true; - } - } elseif ($config_ticket_email_parse_unknown_senders) { - // Parse even if the sender is unknown - $bad_from_pattern = "/daemon|postmaster/i"; - if (!(preg_match($bad_from_pattern, $from_email))) { - if (addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file)) { - $email_processed = true; - } - } - } - } - } - - if ($email_processed) { - // Mark the message as seen - imap_setflag_full($imap, $email_uid, "\\Seen", ST_UID); - // Move the message to the 'ITFlow' folder - imap_mail_move($imap, $email_uid, 'ITFlow', CP_UID); - // Get a Processed Email Count - $processed_count++; - } else { - // Flag the message for manual review without marking it as read - imap_setflag_full($imap, $email_uid, "\\Flagged", ST_UID); - // Clear the Seen flag to ensure the email remains unread - imap_clearflag_full($imap, $email_uid, "\\Seen", ST_UID); - // Get an Unprocessed email count - $unprocessed_count++; - } - - // Delete the temporary message file - if (file_exists("uploads/tmp/{$original_message_file}")) { - unlink("uploads/tmp/{$original_message_file}"); - } - } -} - -// Expunge deleted mails -imap_expunge($imap); - -// Close the IMAP connection -imap_close($imap); - -// Calculate the total execution time -uncomment the code below to get exec time -$script_end_time = microtime(true); -$execution_time = $script_end_time - $script_start_time; -$execution_time_formatted = number_format($execution_time, 2); - -// Insert a log entry into the logs table -$processed_info = "Processed: $processed_count email(s), Unprocessed: $unprocessed_count email(s)"; -// Remove Comment below for Troubleshooting - -//logAction("Cron-Email-Parser", "Execution", "Cron Email Parser executed in $execution_time_formatted seconds. $processed_info"); - -// END Calculate execution time - -// Remove the lock file -unlink($lock_file_path); - -// DEBUG -echo "\nLock File Path: $lock_file_path\n"; -if (file_exists($lock_file_path)) { - echo "\nLock is present\n\n"; -} -echo "Processed Emails into tickets: $processed_count\n"; -echo "Unprocessed Emails: $unprocessed_count\n"; - -?> diff --git a/database_updates.php b/database_updates.php index 0cabb96d..8ee3abf5 100644 --- a/database_updates.php +++ b/database_updates.php @@ -2462,10 +2462,17 @@ if (LATEST_DATABASE_VERSION > CURRENT_DATABASE_VERSION) { mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '1.7.9'"); } - // if (CURRENT_DATABASE_VERSION == '1.7.9') { - // // Insert queries here required to update to DB version 1.8.0 + if (CURRENT_DATABASE_VERSION == '1.7.9') { + + mysqli_query($mysqli, "ALTER TABLE `settings` DROP `config_cron_key`"); + + mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '1.8.0'"); + } + + // if (CURRENT_DATABASE_VERSION == '1.8.0') { + // // Insert queries here required to update to DB version 1.8.1 // // Then, update the database to the next sequential version - // mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '1.8.0'"); + // mysqli_query($mysqli, "UPDATE `settings` SET `config_current_database_version` = '1.8.1'"); // } } else { diff --git a/get_settings.php b/get_settings.php index fda6c074..0ccf34ef 100644 --- a/get_settings.php +++ b/get_settings.php @@ -76,10 +76,8 @@ $config_ticket_autoclose_hours = intval($row['config_ticket_autoclose_hours']); $config_ticket_new_ticket_notification_email = $row['config_ticket_new_ticket_notification_email']; $config_ticket_default_billable = intval($row['config_ticket_default_billable']); - // Cron $config_enable_cron = intval($row['config_enable_cron']); -$config_cron_key = $row['config_cron_key']; // Alerts & Notifications $config_recurring_auto_send_invoice = intval($row['config_recurring_auto_send_invoice']); diff --git a/includes/database_version.php b/includes/database_version.php index 3627c05e..c1d450cd 100644 --- a/includes/database_version.php +++ b/includes/database_version.php @@ -5,4 +5,4 @@ * It is used in conjunction with database_updates.php */ -DEFINE("LATEST_DATABASE_VERSION", "1.7.9"); +DEFINE("LATEST_DATABASE_VERSION", "1.8.0"); diff --git a/post/admin/admin_settings_notification.php b/post/admin/admin_settings_notification.php index 429a0328..cf025793 100644 --- a/post/admin/admin_settings_notification.php +++ b/post/admin/admin_settings_notification.php @@ -7,7 +7,6 @@ if (isset($_POST['edit_notification_settings'])) { validateCSRFToken($_POST['csrf_token']); $config_enable_cron = intval($_POST['config_enable_cron'] ?? 0); - $config_cron_key = sanitizeInput($_POST['config_cron_key']); $config_enable_alert_domain_expire = intval($_POST['config_enable_alert_domain_expire'] ?? 0); $config_send_invoice_reminders = intval($_POST['config_send_invoice_reminders'] ?? 0); $config_recurring_auto_send_invoice = intval($_POST['config_recurring_auto_send_invoice'] ?? 0); @@ -23,18 +22,3 @@ if (isset($_POST['edit_notification_settings'])) { header("Location: " . $_SERVER["HTTP_REFERER"]); } - -if (isset($_GET['generate_cron_key'])) { - - $key = randomString(32); - - mysqli_query($mysqli,"UPDATE settings SET config_cron_key = '$key' WHERE company_id = 1"); - - // Logging - logAction("Settings", "Edit", "$session_name regenerated the cron key"); - - $_SESSION['alert_message'] = "Cron key regenerated"; - - header("Location: " . $_SERVER["HTTP_REFERER"]); - -} diff --git a/setup_cli.php b/setup_cli.php deleted file mode 100644 index 1152e9a5..00000000 --- a/setup_cli.php +++ /dev/null @@ -1,389 +0,0 @@ -#!/usr/bin/env php - 'Database host', - 'username' => 'Database username', - 'password' => 'Database password', - 'database' => 'Database name', - 'base-url' => 'Base URL (without protocol, e.g. example.com/itflow)', - 'locale' => 'Locale (e.g. en_US)', - 'timezone' => 'Timezone (e.g. UTC)', - 'currency' => 'Currency code (e.g. USD)', - 'company-name' => 'Company name', - 'country' => 'Company country (e.g. United States)', - 'user-name' => 'Admin user full name', - 'user-email' => 'Admin user email', - 'user-password'=> 'Admin user password (min 8 chars)' -]; - -// Additional optional arguments -// address, city, state, zip, phone, company-email, website -// These are optional and don't need error checks if missing. -$optional_args = [ - 'address' => 'Company address (optional)', - 'city' => 'Company city (optional)', - 'state' => 'Company state (optional)', - 'zip' => 'Company postal code (optional)', - 'phone' => 'Company phone (optional)', - 'company-email' => 'Company email (optional)', - 'website' => 'Company website (optional)' -]; - -// Parse command line options -$shortopts = ""; -$longopts = [ - "help", - "host:", - "username:", - "password:", - "database:", - "base-url:", - "locale:", - "timezone:", - "currency:", - "company-name:", - "country:", - "address::", - "city::", - "state::", - "zip::", - "phone::", - "company-email::", - "website::", - "user-name:", - "user-email:", - "user-password:", - "non-interactive" -]; - -$options = getopt($shortopts, $longopts); - -// If --help is set, print usage and exit -if (isset($options['help'])) { - echo "ITFlow CLI Setup Script\n\n"; - echo "Usage:\n"; - echo " php setup_cli.php [options]\n\n"; - echo "Options:\n"; - foreach ($required_args as $arg => $desc) { - echo " --$arg\t$desc (required)\n"; - } - foreach ($optional_args as $arg => $desc) { - echo " --$arg\t$desc\n"; - } - echo " --non-interactive\tRun in non-interactive mode (fail if required args missing)\n"; - echo " --help\t\tShow this help message\n\n"; - echo "If running interactively (without --non-interactive), any missing required arguments will be prompted.\n"; - echo "If running non-interactively, all required arguments must be provided.\n\n"; - exit(0); -} - -if (file_exists("config.php")) { - include "config.php"; -} - -include "functions.php"; -include "includes/database_version.php"; - -if (!isset($config_enable_setup)) { - $config_enable_setup = 1; -} - -if ($config_enable_setup == 0) { - echo "Setup is disabled. Please delete or modify config.php if you need to re-run the setup.\n"; - exit; -} - -$errorLog = ini_get('error_log') ?: "/var/log/apache2/error.log"; - -$timezones = DateTimeZone::listIdentifiers(); - -function prompt($message) { - echo $message . ": "; - return trim(fgets(STDIN)); -} - -$non_interactive = isset($options['non-interactive']); - -function getOptionOrPrompt($key, $promptMessage, $required = false, $default = '', $optionsGlobal = []) { - global $options, $non_interactive; - if (isset($options[$key])) { - return $options[$key]; - } else { - if ($non_interactive && $required) { - die("Missing required argument: --$key\n"); - } - $val = prompt($promptMessage . (strlen($default) ? " [$default]" : '')); - if (empty($val) && !empty($default)) { - $val = $default; - } - if ($required && empty($val)) { - die("Error: $promptMessage is required.\n"); - } - return $val; - } -} - -// Start setup -echo "Welcome to the ITFlow CLI Setup.\n"; - -// If config exists, abort -if (file_exists('config.php')) { - echo "Database is already configured in config.php.\n"; - echo "To re-run the setup, remove config.php and run this script again.\n"; - exit; -} - -// If non-interactive is set, ensure all required arguments are present -if ($non_interactive) { - foreach (array_keys($required_args) as $arg) { - if (!isset($options[$arg])) { - die("Missing required argument: --$arg\n"); - } - } -} - -// Database Setup -echo "\n=== Database Setup ===\n"; -$database = getOptionOrPrompt('database', "Enter the database name", true); -$host = getOptionOrPrompt('host', "Enter the database host", true, 'localhost'); -if (empty($host)) $host = "localhost"; -$username = getOptionOrPrompt('username', "Enter the database username", true); -$password = getOptionOrPrompt('password', "Enter the database password", true); - -// Base URL -$base_url = getOptionOrPrompt('base-url', "Enter the base URL (e.g. example.com/itflow)", true); -$base_url = rtrim($base_url, '/'); - -// Locale, Timezone, Currency -echo "\n=== Localization ===\n"; -$locale = getOptionOrPrompt('locale', "Enter the locale (e.g. en_US)", true); -$timezone = getOptionOrPrompt('timezone', "Enter the timezone (e.g. UTC or America/New_York)", true); -$currency_code = getOptionOrPrompt('currency', "Enter the currency code (e.g. USD)", true); - -// Company Details -echo "\n=== Company Details ===\n"; -$company_name = getOptionOrPrompt('company-name', "Company Name", true); -$country = getOptionOrPrompt('country', "Country (e.g. United States)", true); -$address = getOptionOrPrompt('address', "Address (optional)", false); -$city = getOptionOrPrompt('city', "City (optional)", false); -$state = getOptionOrPrompt('state', "State/Province (optional)", false); -$zip = getOptionOrPrompt('zip', "Postal Code (optional)", false); -$phone = getOptionOrPrompt('phone', "Phone (optional)", false); -$phone = preg_replace("/[^0-9]/", '', $phone); -$company_email = getOptionOrPrompt('company-email', "Company Email (optional)", false); -$website = getOptionOrPrompt('website', "Website (optional)", false); - -// User Setup -echo "\n=== Create First User ===\n"; -$user_name = getOptionOrPrompt('user-name', "Full Name", true); -$user_email = getOptionOrPrompt('user-email', "Email Address", true); -while (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) { - echo "Invalid email.\n"; - if ($non_interactive) { - die("Invalid email address: $user_email\n"); - } - $user_email = prompt("Email Address"); -} -$user_password_plain = getOptionOrPrompt('user-password', "Password (at least 8 chars)", true); -if (strlen($user_password_plain) < 8) { - if ($non_interactive) { - die("Password must be at least 8 characters.\n"); - } - while (strlen($user_password_plain) < 8) { - echo "Password too short. Try again.\n"; - $user_password_plain = prompt("Password"); - } -} - -if (!preg_match('/^[a-zA-Z0-9.\-\/]+$/', $host)) { - die("Invalid host format.\n"); -} - -// Test Database -$conn = @mysqli_connect($host, $username, $password, $database); -if (!$conn) { - die("Database connection failed - " . mysqli_connect_error() . "\n"); -} - -$installation_id = randomString(32); - -$new_config = " "$installation_id", - 'company_name' => "$company_name_db", - 'website' => "$website_db", - 'city' => "$city_db", - 'state' => "$state_db", - 'country' => "$country_db", - 'currency' => "$currency_db", - 'comments' => "$comments", - 'collection_method' => 1 - ]); - - $opts = ['http' => - [ - 'method' => 'POST', - 'header' => 'Content-type: application/x-www-form-urlencoded', - 'content' => $postdata - ] - ]; - - $context = stream_context_create($opts); - $result = @file_get_contents('https://telemetry.itflow.org', false, $context); - echo "Telemetry response: $result\n"; - } -} - -// finalize config -$myfile = fopen("config.php", "a"); -$txt = "\$config_enable_setup = 0;\n\n"; -fwrite($myfile, $txt); -fclose($myfile); - -echo "\nSetup complete!\n"; -echo "You can now log in with the user you created at: https://$base_url/login.php\n"; - -exit(0); diff --git a/update_cli.php b/update_cli.php deleted file mode 100644 index c8a19f70..00000000 --- a/update_cli.php +++ /dev/null @@ -1,130 +0,0 @@ -#!/usr/bin/env php -&1", $output, $return_var); - exec("git reset --hard origin/master 2>&1", $output2, $return_var2); - echo implode("\n", $output) . "\n" . implode("\n", $output2) . "\n"; - } else { - // Perform a standard update (git pull) - exec("git pull 2>&1", $output, $return_var); - - // Check if the repository is already up to date - if (strpos(implode("\n", $output), 'Already up to date.') === false) { - echo implode("\n", $output) . "\n"; - echo "Update successful\n"; - } else { - // If already up-to-date, don't show the update success message - echo implode("\n", $output) . "\n"; - } - } -} - -// If "update_db" is requested -if (isset($options['update_db'])) { - require_once('includes/database_version.php'); - - $latest_db_version = LATEST_DATABASE_VERSION; - - // Fetch the current version from the database - $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings LIMIT 1"); - $row = mysqli_fetch_assoc($result); - DEFINE("CURRENT_DATABASE_VERSION", $row['config_current_database_version']); - $old_db_version = $row['config_current_database_version']; - - // Now include the update logic - require_once('database_updates.php'); - - // After database_updates.php has done its job, fetch the updated current DB version again - $result = mysqli_query($mysqli, "SELECT config_current_database_version FROM settings LIMIT 1"); - $row = mysqli_fetch_assoc($result); - $new_db_version = $row['config_current_database_version']; - - if ($old_db_version !== $latest_db_version) { - echo "Database updated from version $old_db_version to $new_db_version.\n"; - echo "The latest database version is $latest_db_version.\n"; - } else { - echo "Database is already at the latest version ($latest_db_version). No updates were applied.\n"; - } -} From 96809c7f85e4ad8bd0582a66c56b4ee53230535e Mon Sep 17 00:00:00 2001 From: johnnyq Date: Sat, 25 Jan 2025 21:47:24 -0500 Subject: [PATCH 04/32] Update db.sql --- db.sql | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/db.sql b/db.sql index 48aaa273..31f409e0 100644 --- a/db.sql +++ b/db.sql @@ -1705,7 +1705,6 @@ CREATE TABLE `settings` ( `config_ticket_new_ticket_notification_email` varchar(200) DEFAULT NULL, `config_ticket_default_billable` tinyint(1) NOT NULL DEFAULT 0, `config_enable_cron` tinyint(1) NOT NULL DEFAULT 0, - `config_cron_key` varchar(255) DEFAULT NULL, `config_recurring_auto_send_invoice` tinyint(1) NOT NULL DEFAULT 1, `config_enable_alert_domain_expire` tinyint(1) NOT NULL DEFAULT 1, `config_send_invoice_reminders` tinyint(1) NOT NULL DEFAULT 1, @@ -2343,4 +2342,4 @@ CREATE TABLE `vendors` ( /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2025-01-18 13:03:55 +-- Dump completed on 2025-01-25 21:47:06 From ab7273bf3965c189a045c56bc6f8151e05d86d12 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Mon, 27 Jan 2025 11:15:43 -0500 Subject: [PATCH 05/32] Reduce Global Ticket view padding by not displaying contact's email --- tickets.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tickets.php b/tickets.php index 43e93ebc..4b508a4d 100644 --- a/tickets.php +++ b/tickets.php @@ -418,7 +418,7 @@ $user_active_assigned_tickets = intval($row['total_tickets_assigned']); if (empty($contact_name)) { $contact_display = "-"; } else { - $contact_display = "$contact_name
$contact_email"; + $contact_display = "$contact_name"; } // Get who last updated the ticket - to be shown in the last Response column From 8221ef2927b2fd7b9b95fd6da589e66d1b88c379 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Mon, 27 Jan 2025 11:20:24 -0500 Subject: [PATCH 06/32] Global Ticket View make contact secondary text in table header and remove tasks from the table header --- tickets.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tickets.php b/tickets.php index 4b508a4d..02c5c77a 100644 --- a/tickets.php +++ b/tickets.php @@ -316,12 +316,12 @@ $user_active_assigned_tickets = intval($row['total_tickets_assigned']);
From 39adab734b969ba91071c86e929d96557bd20e47 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Mon, 27 Jan 2025 23:26:10 -0500 Subject: [PATCH 07/32] Enhanced the MFA Setup Flow --- modals/user_mfa_modal.php | 50 ++++++++++++++++++++++++++++ post/user/profile.php | 70 +++++++++++++++++++++++++++++++++++++++ user_security.php | 63 +++++------------------------------ 3 files changed, 129 insertions(+), 54 deletions(-) create mode 100644 modals/user_mfa_modal.php diff --git a/modals/user_mfa_modal.php b/modals/user_mfa_modal.php new file mode 100644 index 00000000..a5f9987b --- /dev/null +++ b/modals/user_mfa_modal.php @@ -0,0 +1,50 @@ + + + diff --git a/post/user/profile.php b/post/user/profile.php index 0ff38f49..79fdb22b 100644 --- a/post/user/profile.php +++ b/post/user/profile.php @@ -208,6 +208,76 @@ if (isset($_POST['verify'])) { } +if (isset($_POST['enable_mfa'])) { + + validateCSRFToken($_POST['csrf_token']); + + require_once "plugins/totp/totp.php"; + + $verify_code = intval($_POST['verify_code']); //code to validate, for example received from device + $token = sanitizeInput($_POST['token']); + + if (TokenAuth6238::verify($token, $verify_code)) { + + mysqli_query($mysqli,"UPDATE users SET user_token = '$token' WHERE user_id = $session_user_id"); + + // Delete any existing 2FA tokens - these browsers should be re-validated + mysqli_query($mysqli, "DELETE FROM remember_tokens WHERE remember_token_user_id = $session_user_id"); + + // Logging + logAction("User Account", "Edit", "$session_name enabled MFA on their account"); + + $_SESSION['alert_message'] = "Multi-Factor authentication enabled"; + + } else { + $_SESSION['alert_type'] = "error"; + $_SESSION['alert_message'] = "Verification Code Invalid, Multi-Factor Authenticaion not enabled, Try again!"; + } + + header("Location: user_security.php"); + +} + +if (isset($_GET['disable_mfa'])){ + + // CSRF Check + validateCSRFToken($_GET['csrf_token']); + + mysqli_query($mysqli,"UPDATE users SET user_token = '' WHERE user_id = $session_user_id"); + + // Sanitize Config Vars from get_settings.php and Session Vars from check_login.php + $config_mail_from_name = sanitizeInput($config_mail_from_name); + $config_mail_from_email = sanitizeInput($config_mail_from_email); + $config_app_name = sanitizeInput($config_app_name); + + // 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"; + + $data = [ + [ + 'from' => $config_mail_from_email, + 'from_name' => $config_mail_from_name, + 'recipient' => $session_email, + 'recipient_name' => $session_name, + 'subject' => $subject, + 'body' => $body + ] + ]; + $mail = addToMailQueue($data); + } + + // Logging + logAction("User Account", "Edit", "$session_name disabled MFA on their account"); + + $_SESSION['alert_type'] = "error"; + $_SESSION['alert_message'] = "Multi-Factor authentication disabled"; + + header("Location: " . $_SERVER["HTTP_REFERER"]); + +} + if (isset($_POST['enable_2fa']) || isset($_GET['enable_2fa_force'])) { // CSRF Check diff --git a/user_security.php b/user_security.php index 7c26d3c6..0dd10d84 100644 --- a/user_security.php +++ b/user_security.php @@ -31,65 +31,20 @@ $remember_token_count = mysqli_num_rows($sql_remember_tokens); - - - -
-
-

Mult-Factor Authentication

-
-
-
- +
- + + + + -

You have set up 2FA. Your QR code is below.

- + Disable Multi-Factor Authentication +
-
- "; - - echo "

$session_token

"; - - } - - ?> -
- - - - - - -
-
-
-
- -
- -
- -
-
-
- - -
From 071352e32fbf84c4e171eb54f82d5587e5f18281 Mon Sep 17 00:00:00 2001 From: wrongecho Date: Tue, 28 Jan 2025 11:19:56 +0000 Subject: [PATCH 08/32] Autopay - Stripe wasn't showing as an option in the modal - Show the current payment method at the top of the recurring invoice --- CHANGELOG.md | 5 +++++ modals/recurring_payment_add_modal.php | 3 +++ post/user/invoice.php | 3 --- recurring_invoice.php | 5 +++-- 4 files changed, 11 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dcddde35..7927fa5c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ This file documents all notable changes made to ITFlow. +## [UNRELEASED] + +### Fixed +- Stripe now shows as a payment option in the add recurring payment modal + ## [25.01] ### Added / Changed diff --git a/modals/recurring_payment_add_modal.php b/modals/recurring_payment_add_modal.php index f7126329..7366c390 100644 --- a/modals/recurring_payment_add_modal.php +++ b/modals/recurring_payment_add_modal.php @@ -48,6 +48,9 @@ 1 AND user_type = 1 - AND user_archived_at IS NULL + AND user_archived_at IS NULL ORDER BY user_name DESC" ); while ($row = mysqli_fetch_array($sql_users_select)) { diff --git a/tickets.php b/tickets.php index 02c5c77a..b1d4f494 100644 --- a/tickets.php +++ b/tickets.php @@ -280,7 +280,7 @@ $user_active_assigned_tickets = intval($row['total_tickets_assigned']); Date: Tue, 28 Jan 2025 12:31:09 +0000 Subject: [PATCH 11/32] Bulk mail - only show active clients Bulk mail shouldn't show archived clients --- admin_bulk_mail.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/admin_bulk_mail.php b/admin_bulk_mail.php index 8ede4dd8..0d68f27f 100644 --- a/admin_bulk_mail.php +++ b/admin_bulk_mail.php @@ -4,7 +4,8 @@ require_once "includes/inc_all_admin.php"; $sql = mysqli_query($mysqli, "SELECT * FROM contacts LEFT JOIN clients ON client_id = contact_client_id - WHERE contact_archived_at IS NULL + WHERE client_archived_at IS NULL + AND contact_archived_at IS NULL AND contact_email != '' AND (contact_primary = 1 OR contact_important = 1 OR @@ -22,7 +23,7 @@ $sql = mysqli_query($mysqli, "SELECT * FROM contacts

Bulk Mail

From c150fb02bb2bcb4fd10c086d85ccafc3b4383779 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 28 Jan 2025 15:06:43 -0500 Subject: [PATCH 12/32] Fix Profit and Loss Report getting the wrong total expense amount for Quarter 2 April - June due to wrong var being used this does not affect actual expense data and will show correctly after update and also does not affect total expense for all 4 quarters --- report_profit_loss.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/report_profit_loss.php b/report_profit_loss.php index 74c46c8b..95532d90 100644 --- a/report_profit_loss.php +++ b/report_profit_loss.php @@ -377,7 +377,7 @@ $sql_categories_expense = mysqli_query($mysqli, "SELECT * FROM categories WHERE ?> -
+ Date: Tue, 28 Jan 2025 16:34:07 -0500 Subject: [PATCH 13/32] Further improve the MFA process, now when verification fails the modal will stay open and the secret remain the same --- modals/user_mfa_modal.php | 13 ++++++++----- post/user/profile.php | 23 ++++++++++++++++++++--- user_security.php | 21 +++++++++++++++++++++ 3 files changed, 49 insertions(+), 8 deletions(-) diff --git a/modals/user_mfa_modal.php b/modals/user_mfa_modal.php index a5f9987b..7808299d 100644 --- a/modals/user_mfa_modal.php +++ b/modals/user_mfa_modal.php @@ -1,8 +1,12 @@ "; + // Clear it so it doesn't persist on refresh + unset($_SESSION['alert_type']); + unset($_SESSION['alert_message']); +} + +// If the user just failed a TOTP verification, auto-open the modal: +if (!empty($_SESSION['show_mfa_modal'])) { + echo " + "; + unset($_SESSION['show_mfa_modal']); +} + require_once "includes/footer.php"; From a4c9b4efa4b7c6713283be1d6375eb477024186b Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 28 Jan 2025 16:55:47 -0500 Subject: [PATCH 14/32] fix right margin on forms in user details when in mobile response --- user_details.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/user_details.php b/user_details.php index 496c8834..b28300b8 100644 --- a/user_details.php +++ b/user_details.php @@ -24,7 +24,7 @@ require_once "includes/inc_all_user.php"; -
+
From 706a77c5d3875200ad8460d08a3fb9c01b3bcdba Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 28 Jan 2025 17:14:47 -0500 Subject: [PATCH 15/32] Added btn-responsive style class to define buttons to go full block level while in mobile and to stay defined size in non mobile response --- includes/header.php | 24 ++++++++++++++++++++++++ user_details.php | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/includes/header.php b/includes/header.php index ac886ac6..e530bb28 100644 --- a/includes/header.php +++ b/includes/header.php @@ -39,6 +39,30 @@ header("X-Frame-Options: DENY"); + + diff --git a/user_details.php b/user_details.php index b28300b8..a8f60fa5 100644 --- a/user_details.php +++ b/user_details.php @@ -56,7 +56,7 @@ require_once "includes/inc_all_user.php";
- +
From c282e22228d42289eb0b0f95dcd13ed5c1002fc5 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 28 Jan 2025 17:29:15 -0500 Subject: [PATCH 16/32] Updated Changelog --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7927fa5c..1d9e1c89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,14 @@ This file documents all notable changes made to ITFlow. ## [UNRELEASED] +### Added / Changed +- Greatly Improved MFA Setup Flow UI/UX +- Fixed Client Portal redirect whgen login key is enabled + ### Fixed - Stripe now shows as a payment option in the add recurring payment modal +- Fixed Inaccurate Quarter 2 results in Profit & Loss Report +- Fixed OTP not showing on hover when in contact or asset details section ## [25.01] From 677bb6b400125a6210d34270a462cfdefa3c898e Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 28 Jan 2025 17:32:27 -0500 Subject: [PATCH 17/32] Updated Changelog removed crons and cron key --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d9e1c89..7df989c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,9 @@ This file documents all notable changes made to ITFlow. - Fixed Inaccurate Quarter 2 results in Profit & Loss Report - Fixed OTP not showing on hover when in contact or asset details section +### BREAKING CHANGES +- Completely removed old cron scripts along with cron key, new cron scripts are located in /scripts/ directory, no cron key rrequired. + ## [25.01] ### Added / Changed From 52ad2ba3225417f17fd3d05d11a2360cc9cbcaac Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 28 Jan 2025 18:57:04 -0500 Subject: [PATCH 18/32] Reworked the MFA Enforcement --- check_login.php | 7 +- login.php | 6 +- mfa_enforcement.php | 196 ++++++++++++++++++++++++++++++++++++++++++ post/user/profile.php | 119 ++++++------------------- 4 files changed, 227 insertions(+), 101 deletions(-) create mode 100644 mfa_enforcement.php diff --git a/check_login.php b/check_login.php index bd9570df..36cd2b34 100644 --- a/check_login.php +++ b/check_login.php @@ -54,7 +54,7 @@ $row = mysqli_fetch_array($sql); $session_name = sanitizeInput($row['user_name']); $session_email = $row['user_email']; $session_avatar = $row['user_avatar']; -$session_token = $row['user_token']; +$session_token = $row['user_token']; // MFA Token $session_user_role = intval($row['user_role']); $session_user_role_display = sanitizeInput($row['user_role_name']); if (isset($row['user_role_is_admin']) && $row['user_role_is_admin'] == 1) { @@ -128,8 +128,3 @@ $session_mobile = isMobile(); $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('notification_id') AS num FROM notifications WHERE (notification_user_id = $session_user_id OR notification_user_id = 0) AND notification_dismissed_at IS NULL")); $num_notifications = $row['num']; - -// FORCE MFA Setup -//if ($session_user_config_force_mfa == 1 && $session_token == NULL) { -// header("Location: force_mfa.php"); -//} diff --git a/login.php b/login.php index 901ccab0..89d6a673 100644 --- a/login.php +++ b/login.php @@ -145,7 +145,7 @@ if (isset($_POST['login'])) { // Validate MFA code if (!empty($current_code) && TokenAuth6238::verify($token, $current_code)) { $mfa_is_complete = true; - $extended_log = 'with 2FA'; + $extended_log = 'with MFA'; } if ($mfa_is_complete) { @@ -201,8 +201,8 @@ if (isset($_POST['login'])) { // Forcing MFA if ($force_mfa == 1 && $token == NULL) { - $secretMFA = key32gen(); - $config_start_page = "post.php?enable_2fa_force&token=$secretMFA&csrf_token=$_SESSION[csrf_token]"; + //$secretMFA = key32gen(); + $config_start_page = "mfa_enforcement.php"; } // Setup encryption session key diff --git a/mfa_enforcement.php b/mfa_enforcement.php new file mode 100644 index 00000000..d0ad779c --- /dev/null +++ b/mfa_enforcement.php @@ -0,0 +1,196 @@ + + + + + + + + + + + MFA Enforcement | <?php echo $session_company_name; ?> + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + +
+
+

Multi-Factor Authentication Enforcement

+ + +
+
+ + + +
+

Scan this code into your app

+ +
Can't Scan? Copy and paste the secret below +
+
+

Secret: + +

+
+ +
+ +
+
+
+ +
+ +
+ +
+
+
+ +
+
+
+
+ + + + + + + + + + + + + + + + + + diff --git a/post/user/profile.php b/post/user/profile.php index 5f5b51f6..e5c14de4 100644 --- a/post/user/profile.php +++ b/post/user/profile.php @@ -190,24 +190,6 @@ if (isset($_POST['edit_your_user_preferences'])) { header("Location: " . $_SERVER["HTTP_REFERER"]); } - -if (isset($_POST['verify'])) { - - require_once "plugins/totp/totp.php"; - - $currentcode = intval($_POST['code']); //code to validate, for example received from device - - if (TokenAuth6238::verify($session_token, $currentcode)) { - $_SESSION['alert_message'] = "VALID!"; - }else{ - $_SESSION['alert_type'] = "error"; - $_SESSION['alert_message'] = "IN-VALID!"; - } - - header("Location: " . $_SERVER["HTTP_REFERER"]); - -} - if (isset($_POST['enable_mfa'])) { validateCSRFToken($_POST['csrf_token']); @@ -230,7 +212,7 @@ if (isset($_POST['enable_mfa'])) { // SUCCESS mysqli_query($mysqli,"UPDATE users SET user_token = '$token' WHERE user_id = $session_user_id"); - // Delete any existing 2FA tokens - these browsers should be re-validated + // Delete any existing MFA tokens - these browsers should be re-validated mysqli_query($mysqli, "DELETE FROM remember_tokens WHERE remember_token_user_id = $session_user_id"); // Logging @@ -241,6 +223,16 @@ if (isset($_POST['enable_mfa'])) { // Clear the mfa_token from the session to avoid re-use. unset($_SESSION['mfa_token']); + // Check if the previous page is mfa_enforcement.php + if (isset($_SERVER['HTTP_REFERER'])) { + $previousPage = basename(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH)); + if ($previousPage === 'mfa_enforcement.php') { + // Redirect back to mfa_enforcement.php + header("Location: $config_start_page"); + exit; + } + } + } else { // FAILURE $_SESSION['alert_type'] = "error"; @@ -248,7 +240,19 @@ if (isset($_POST['enable_mfa'])) { // Set a flag to automatically open the MFA modal again $_SESSION['show_mfa_modal'] = true; - } + + // Check if the previous page is mfa_enforcement.php + if (isset($_SERVER['HTTP_REFERER'])) { + $previousPage = basename(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH)); + if ($previousPage === 'mfa_enforcement.php') { + // Redirect back to mfa_enforcement.php + header("Location: " . $_SERVER['HTTP_REFERER']); + exit; + } + } + } + + header("Location: user_security.php"); exit; @@ -262,6 +266,9 @@ if (isset($_GET['disable_mfa'])){ mysqli_query($mysqli,"UPDATE users SET user_token = '' WHERE user_id = $session_user_id"); + // Delete any existing MFA tokens - these browsers should be re-validated + mysqli_query($mysqli, "DELETE FROM remember_tokens WHERE remember_token_user_id = $session_user_id"); + // Sanitize Config Vars from get_settings.php and Session Vars from check_login.php $config_mail_from_name = sanitizeInput($config_mail_from_name); $config_mail_from_email = sanitizeInput($config_mail_from_email); @@ -295,78 +302,6 @@ if (isset($_GET['disable_mfa'])){ } -if (isset($_POST['enable_2fa']) || isset($_GET['enable_2fa_force'])) { - - // CSRF Check - if ($_SERVER['REQUEST_METHOD'] === 'POST') { - validateCSRFToken($_POST['csrf_token']); - - $extended_log_description = ""; - $token = sanitizeInput($_POST['token']); - } else { - // If this is a GET request then we forced MFA as part of login - validateCSRFToken($_GET['csrf_token']); - - $extended_log_description = "(forced)"; - $token = sanitizeInput($_GET['token']); - } - - - - mysqli_query($mysqli,"UPDATE users SET user_token = '$token' WHERE user_id = $session_user_id"); - - // Delete any existing 2FA tokens - these browsers should be re-validated - mysqli_query($mysqli, "DELETE FROM remember_tokens WHERE remember_token_user_id = $session_user_id"); - - // Logging - logAction("User Account", "Edit", "$session_name enabled MFA on their account $extended_log_description"); - - $_SESSION['alert_message'] = "Two-factor authentication enabled $extended_log_description"; - - header("Location: user_security.php"); - -} - -if (isset($_POST['disable_2fa'])){ - - // CSRF Check - validateCSRFToken($_POST['csrf_token']); - - mysqli_query($mysqli,"UPDATE users SET user_token = '' WHERE user_id = $session_user_id"); - - // Sanitize Config Vars from get_settings.php and Session Vars from check_login.php - $config_mail_from_name = sanitizeInput($config_mail_from_name); - $config_mail_from_email = sanitizeInput($config_mail_from_email); - $config_app_name = sanitizeInput($config_app_name); - - // 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"; - - $data = [ - [ - 'from' => $config_mail_from_email, - 'from_name' => $config_mail_from_name, - 'recipient' => $session_email, - 'recipient_name' => $session_name, - 'subject' => $subject, - 'body' => $body - ] - ]; - $mail = addToMailQueue($data); - } - - // Logging - logAction("User Account", "Edit", "$session_name disabled MFA on their account"); - - $_SESSION['alert_type'] = "error"; - $_SESSION['alert_message'] = "Two-factor authentication disabled"; - - header("Location: " . $_SERVER["HTTP_REFERER"]); - -} - if (isset($_POST['revoke_your_2fa_remember_tokens'])) { // CSRF From 02fdc66af9d8a4118d3c8391e2d27d452d4de3df Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 28 Jan 2025 19:23:25 -0500 Subject: [PATCH 19/32] Updated UI / UX MFA enforcement --- mfa_enforcement.php | 56 ++++----------------------------------------- 1 file changed, 4 insertions(+), 52 deletions(-) diff --git a/mfa_enforcement.php b/mfa_enforcement.php index d0ad779c..6d57db08 100644 --- a/mfa_enforcement.php +++ b/mfa_enforcement.php @@ -40,53 +40,22 @@ $data = "otpauth://totp/ITFlow:$session_email?secret=$token"; - - - - +
-
-

Multi-Factor Authentication Enforcement

- - +
+

Multi-Factor Authentication Enforcement

@@ -112,7 +81,7 @@ $data = "otpauth://totp/ITFlow:$session_email?secret=$token";
- +
@@ -131,17 +100,8 @@ $data = "otpauth://totp/ITFlow:$session_email?secret=$token"; - - - - From 033a5d1f4f1e6d90ebd5cde1ab6229b8b530afa6 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 28 Jan 2025 19:25:29 -0500 Subject: [PATCH 20/32] Remove comment --- login.php | 1 - 1 file changed, 1 deletion(-) diff --git a/login.php b/login.php index 89d6a673..0bbf227e 100644 --- a/login.php +++ b/login.php @@ -201,7 +201,6 @@ if (isset($_POST['login'])) { // Forcing MFA if ($force_mfa == 1 && $token == NULL) { - //$secretMFA = key32gen(); $config_start_page = "mfa_enforcement.php"; } From 6cbd4ffebe513bbe19cc77ffea9e8c4e01962d5f Mon Sep 17 00:00:00 2001 From: johnnyq Date: Tue, 28 Jan 2025 20:03:23 -0500 Subject: [PATCH 21/32] Add members column in roles and other UI tidying --- admin_role.php | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/admin_role.php b/admin_role.php index db315d07..d59c2c4e 100644 --- a/admin_role.php +++ b/admin_role.php @@ -21,7 +21,7 @@ $sql = mysqli_query( $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); ?> -
Roles are still in development. Permissions may not be fully enforced.
+
Roles are still in development. Permissions may not be fully enforced.
@@ -54,22 +54,15 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()"));
- + - @@ -87,16 +80,32 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); $sql_role_user_count = mysqli_query($mysqli, "SELECT COUNT(users.user_id) FROM users LEFT JOIN user_settings on users.user_id = user_settings.user_id WHERE user_role = $role_id AND user_archived_at IS NULL"); $role_user_count = mysqli_fetch_row($sql_role_user_count)[0]; + $sql_users = mysqli_query($mysqli, "SELECT * FROM users LEFT JOIN user_settings on users.user_id = user_settings.user_id WHERE user_role = $role_id AND user_archived_at IS NULL"); + // Initialize an empty array to hold user names + $user_names = []; + + // Fetch each row and store the user_name in the array + while($row = mysqli_fetch_assoc($sql_users)) { + $user_names[] = nullable_htmlentities($row['user_name']); + } + + // Convert the array of user names to a comma-separated string + $user_names_string = implode(",", $user_names) ; + + if (empty($user_names_string)) { + $user_names_string = "-"; + } + ?> - + - - - + @@ -175,14 +170,13 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); - -
- Subject / Tasks + Subject - Client / Contact + Client / Contact
- Name - - - - Description + Role Members Admin - User count - Action
- -
+
+ +
diff --git a/mfa_enforcement.php b/mfa_enforcement.php index 6d57db08..2368c7c0 100644 --- a/mfa_enforcement.php +++ b/mfa_enforcement.php @@ -47,50 +47,55 @@ $data = "otpauth://totp/ITFlow:$session_email?secret=$token"; - -
-
- - - -
-
-

Multi-Factor Authentication Enforcement

-
-
-
- - -
-

Scan this code into your app

- -
Can't Scan? Copy and paste the secret below -
-
-

Secret: - -

-
- -
- -
-
-
- -
- -
- -
-
-
-
-
-
+ + + + +
+ + +
+
+ @@ -143,6 +148,5 @@ clipboard.on('error', function(e) { }); - From 5b32127de24447d7b7b59c015e6a7defaf517759 Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 29 Jan 2025 11:41:37 -0500 Subject: [PATCH 23/32] Add Tooltips on hover to better explain what to do with the MFA enformcement info --- mfa_enforcement.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/mfa_enforcement.php b/mfa_enforcement.php index 2368c7c0..2b45bc13 100644 --- a/mfa_enforcement.php +++ b/mfa_enforcement.php @@ -69,10 +69,10 @@ $data = "otpauth://totp/ITFlow:$session_email?secret=$token";
- +

- +

@@ -147,6 +147,11 @@ clipboard.on('error', function(e) { hideTooltip(e.trigger); }); +// Enable Popovers +$(function () { + $('[data-toggle="popover"]').popover() +}); + From 34b94af965bfb8cf2adf30d62b7135ff9de77f3a Mon Sep 17 00:00:00 2001 From: johnnyq Date: Wed, 29 Jan 2025 12:32:45 -0500 Subject: [PATCH 24/32] Copied the cron scripts from /script dir back to / and updated all require pathes --- cron.php | 1168 ++++++++++++++++++++++++++++++++ cron_certificate_refresher.php | 68 ++ cron_domain_refresher.php | 117 ++++ cron_mail_queue.php | 225 ++++++ cron_ticket_email_parser.php | 556 +++++++++++++++ mfa_enforcement.php | 22 +- 6 files changed, 2145 insertions(+), 11 deletions(-) create mode 100644 cron.php create mode 100644 cron_certificate_refresher.php create mode 100644 cron_domain_refresher.php create mode 100644 cron_mail_queue.php create mode 100644 cron_ticket_email_parser.php diff --git a/cron.php b/cron.php new file mode 100644 index 00000000..37decdc7 --- /dev/null +++ b/cron.php @@ -0,0 +1,1168 @@ + 0) { + + appNotify("Pending Tickets", "There are $tickets_pending_assignment new tickets pending assignment", "tickets.php?status=New"); + + // Logging + logApp("Cron", "info", "Cron created notifications for new tickets that are pending assignment"); +} + +// Recurring (Scheduled) tickets + +// Get recurring tickets for today +$sql_scheduled_tickets = mysqli_query($mysqli, "SELECT * FROM scheduled_tickets WHERE scheduled_ticket_next_run = CURDATE()"); + +if (mysqli_num_rows($sql_scheduled_tickets) > 0) { + while ($row = mysqli_fetch_array($sql_scheduled_tickets)) { + + $schedule_id = intval($row['scheduled_ticket_id']); + $subject = sanitizeInput($row['scheduled_ticket_subject']); + $details = mysqli_real_escape_string($mysqli, $row['scheduled_ticket_details']); + $priority = sanitizeInput($row['scheduled_ticket_priority']); + $frequency = sanitizeInput(strtolower($row['scheduled_ticket_frequency'])); + $billable = intval($row['scheduled_ticket_billable']); + $created_id = intval($row['scheduled_ticket_created_by']); + $assigned_id = intval($row['scheduled_ticket_assigned_to']); + $client_id = intval($row['scheduled_ticket_client_id']); + $contact_id = intval($row['scheduled_ticket_contact_id']); + $asset_id = intval($row['scheduled_ticket_asset_id']); + + $ticket_status = 1; // Default + if ($assigned_id > 0) { + $ticket_status = 2; // Set to open if we've auto-assigned an agent + } + + // Assign this new ticket the next ticket number + $ticket_number_sql = mysqli_fetch_array(mysqli_query($mysqli, "SELECT config_ticket_next_number FROM settings WHERE company_id = 1")); + $ticket_number = intval($ticket_number_sql['config_ticket_next_number']); + + // Increment config_ticket_next_number by 1 (for the next ticket) + $new_config_ticket_next_number = $ticket_number + 1; + mysqli_query($mysqli, "UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = 1"); + + // 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 = '$ticket_status', ticket_billable = $billable, ticket_created_by = $created_id, ticket_assigned_to = $assigned_id, ticket_contact_id = $contact_id, ticket_client_id = $client_id, ticket_asset_id = $asset_id"); + $id = mysqli_insert_id($mysqli); + + // Logging + logAction("Ticket", "Create", "Cron created recurring scheduled $frequency ticket - $subject", $client_id, $id); + + customAction('ticket_create', $id); + + // Notifications + + // Get client/contact/ticket details + $sql = mysqli_query( + $mysqli, + "SELECT client_name, contact_name, contact_email, ticket_prefix, ticket_number, ticket_priority, ticket_subject, ticket_details FROM tickets + LEFT JOIN clients ON ticket_client_id = client_id + LEFT JOIN contacts ON ticket_contact_id = contact_id + WHERE ticket_id = $id" + ); + $row = mysqli_fetch_array($sql); + + $contact_name = sanitizeInput($row['contact_name']); + $contact_email = sanitizeInput($row['contact_email']); + $client_name = sanitizeInput($row['client_name']); + $contact_name = sanitizeInput($row['contact_name']); + $contact_email = sanitizeInput($row['contact_email']); + $ticket_prefix = sanitizeInput($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_priority = sanitizeInput($row['ticket_priority']); + $ticket_subject = sanitizeInput($row['ticket_subject']); + $ticket_details = mysqli_real_escape_string($mysqli, $row['ticket_details']); + + $data = []; + + // Notify client by email their ticket has been raised, if general notifications are turned on & there is a valid contact email + if (!empty($config_smtp_host) && $config_ticket_client_general_notifications == 1 && filter_var($contact_email, FILTER_VALIDATE_EMAIL)) { + + $email_subject = "Ticket created - [$ticket_prefix$ticket_number] - $ticket_subject (scheduled)"; + $email_body = "##- Please type your reply above this line -##

Hello $contact_name,

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

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

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

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + + $email = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $email_subject, + 'body' => $email_body + ]; + + $data[] = $email; + + } + + // Notify agent's via the DL address of the new ticket, if it's populated with a valid email + if (filter_var($config_ticket_new_ticket_notification_email, FILTER_VALIDATE_EMAIL)) { + + $email_subject = "ITFlow - New Recurring Ticket - $client_name: $ticket_subject"; + $email_body = "Hello,

This is a notification that a recurring (scheduled) ticket has been raised in ITFlow.
Ticket: $ticket_prefix$ticket_number
Client: $client_name
Priority: $priority
Link: https://$config_base_url/ticket.php?ticket_id=$id

--------------------------------

$ticket_subject
$ticket_details"; + + $email = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $config_ticket_new_ticket_notification_email, + 'recipient_name' => $config_ticket_from_name, + 'subject' => $email_subject, + 'body' => $email_body + ]; + + $data[] = $email; + } + + // Add to the mail queue + addToMailQueue($data); + + // 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"); + + } +} + +// Logging +// logAction("Cron", "Task", "Cron created sent out recurring tickets"); + + +// TICKET RESOLUTION/CLOSURE PROCESS +// Changes tickets status from 'Resolved' >> 'Closed' after a defined interval + +$sql_resolved_tickets_to_close = mysqli_query( + $mysqli, + "SELECT * FROM tickets + WHERE ticket_status = 4 + AND ticket_updated_at < NOW() - INTERVAL $config_ticket_autoclose_hours HOUR" +); + +while ($row = mysqli_fetch_array($sql_resolved_tickets_to_close)) { + + $ticket_id = $row['ticket_id']; + $ticket_prefix = sanitizeInput($row['ticket_prefix']); + $ticket_number = intval($row['ticket_number']); + $ticket_subject = sanitizeInput($row['ticket_subject']); + $ticket_status = sanitizeInput($row['ticket_status']); + $ticket_assigned_to = sanitizeInput($row['ticket_assigned_to']); + $client_id = intval($row['ticket_client_id']); + + mysqli_query($mysqli,"UPDATE tickets SET ticket_status = 5, ticket_closed_at = NOW(), ticket_closed_by = $ticket_assigned_to WHERE ticket_id = $ticket_id"); + + //Logging + logAction("Ticket", "Closed", "$ticket_prefix$ticket_number auto closed", $client_id, $ticket_id); + + customAction('ticket_close', $ticket_id); + + //TODO: Add client notifs if $config_ticket_client_general_notifications is on +} + +if ($config_send_invoice_reminders == 1) { + + // 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,650,680,710,740]; + + foreach ($invoiceAlertArray as $day) { + + $sql = mysqli_query( + $mysqli, + "SELECT * FROM invoices + LEFT JOIN clients ON invoice_client_id = client_id + LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1 + WHERE invoice_status != 'Draft' + AND invoice_status != 'Paid' + AND invoice_status != 'Cancelled' + AND invoice_status != 'Non-Billable' + AND DATE_ADD(invoice_due, INTERVAL $day DAY) = CURDATE() + ORDER BY invoice_number DESC" + ); + + while ($row = mysqli_fetch_array($sql)) { + $invoice_id = intval($row['invoice_id']); + $invoice_prefix = sanitizeInput($row['invoice_prefix']); + $invoice_number = intval($row['invoice_number']); + $invoice_status = sanitizeInput($row['invoice_status']); + $invoice_date = sanitizeInput($row['invoice_date']); + $invoice_due = sanitizeInput($row['invoice_due']); + $invoice_url_key = sanitizeInput($row['invoice_url_key']); + $invoice_amount = floatval($row['invoice_amount']); + $invoice_currency_code = sanitizeInput($row['invoice_currency_code']); + $client_id = intval($row['client_id']); + $client_name = sanitizeInput($row['client_name']); + $contact_name = sanitizeInput($row['contact_name']); + $contact_email = sanitizeInput($row['contact_email']); + + // Late Charges + + if ($config_invoice_late_fee_enable == 1) { + + $todays_date = date('Y-m-d'); + $late_fee_amount = ($invoice_amount * $config_invoice_late_fee_percent) / 100; + $new_invoice_amount = $invoice_amount + $late_fee_amount; + + mysqli_query($mysqli, "UPDATE invoices SET invoice_amount = $new_invoice_amount WHERE invoice_id = $invoice_id"); + + //Insert Items into New Invoice + mysqli_query($mysqli, "INSERT INTO invoice_items SET item_name = 'Late Fee', item_description = '$config_invoice_late_fee_percent% late fee applied on $todays_date', item_quantity = 1, item_price = $late_fee_amount, item_total = $late_fee_amount, item_order = 998, item_invoice_id = $invoice_id"); + + mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron applied a late fee of $late_fee_amount', history_invoice_id = $invoice_id"); + + appNotify("Invoice Late Charge", "Invoice $invoice_prefix$invoice_number for $client_name in the amount of $invoice_amount was charged a late fee of $late_fee_amount", "invoice.php?invoice_id=$invoice_id", $client_id); + + } + + appNotify("Invoice Overdue", "Invoice $invoice_prefix$invoice_number for $client_name in the amount of $invoice_amount is overdue by $day days", "invoice.php?invoice_id=$invoice_id", $client_id); + + $subject = "Overdue Invoice $invoice_prefix$invoice_number"; + $body = "Hello $contact_name,

Our records indicate that we have not yet received payment for the invoice $invoice_prefix$invoice_number. We kindly request that you submit your payment as soon as possible. If you have any questions or concerns, please do not hesitate to contact us at $company_email or $company_phone. +

+ Kindly review the invoice details mentioned 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
Over Due By: $day Days


To view your invoice, please click here.


--
$company_name - Billing
$config_invoice_from_email
$company_phone"; + + $mail = addToMailQueue([ + [ + 'from' => $config_invoice_from_email, + 'from_name' => $config_invoice_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body + ] + ]); + + if ($mail === true) { + mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Emailed Overdue Invoice', history_invoice_id = $invoice_id"); + } else { + mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Failed to send Overdue Invoice', history_invoice_id = $invoice_id"); + + appNotify("Mail", "Failed to send email to $contact_email"); + + // Logging + logApp("Mail", "error", "Failed to send email to $contact_email regarding $subject. $mail"); + } + + } + + } +} +// Logging +// logAction("Cron", "Task", "Cron created notifications for past due invoices and sent out notifications to the primary and billing contacts email"); + +// 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 recurring_payments ON recurring_id = recurring_payment_recurring_invoice_id + LEFT JOIN clients ON client_id = recurring_client_id + WHERE recurring_next_date = CURDATE() + AND recurring_status = 1 +"); + +while ($row = mysqli_fetch_array($sql_recurring)) { + $recurring_id = intval($row['recurring_id']); + $recurring_scope = sanitizeInput($row['recurring_scope']); + $recurring_frequency = sanitizeInput($row['recurring_frequency']); + $recurring_status = sanitizeInput($row['recurring_status']); + $recurring_last_sent = sanitizeInput($row['recurring_last_sent']); + $recurring_next_date = sanitizeInput($row['recurring_next_date']); + $recurring_discount_amount = floatval($row['recurring_discount_amount']); + $recurring_amount = floatval($row['recurring_amount']); + $recurring_currency_code = sanitizeInput($row['recurring_currency_code']); + $recurring_note = sanitizeInput($row['recurring_note']); + $recurring_invoice_email_notify = intval($row['recurring_invoice_email_notify']); + $category_id = intval($row['recurring_category_id']); + $client_id = intval($row['recurring_client_id']); + $client_name = sanitizeInput($row['client_name']); + $client_net_terms = intval($row['client_net_terms']); + + $recurring_payment_recurring_invoice_id = intval($row['recurring_payment_recurring_invoice_id']); + $recurring_payment_currency_code = sanitizeInput($row['recurring_payment_currency_code']); + $recurring_payment_method = sanitizeInput($row['recurring_payment_method']); + $recurring_payment_account_id = intval($row['recurring_payment_account_id']); + + // 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 = 1"); + $row = mysqli_fetch_array($sql_invoice_number); + $config_invoice_next_number = intval($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 = 1"); + + //Generate a unique URL key for clients to access + $url_key = randomString(156); + + 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_discount_amount = $recurring_discount_amount, 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_client_id = $client_id"); + + $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"); + + while ($row = mysqli_fetch_array($sql_invoice_items)) { + $item_id = intval($row['item_id']); + $item_name = sanitizeInput($row['item_name']); //SQL Escape incase of , + $item_description = sanitizeInput($row['item_description']); //SQL Escape incase of , + $item_quantity = floatval($row['item_quantity']); + $item_price = floatval($row['item_price']); + $item_subtotal = floatval($row['item_subtotal']); + $item_tax = floatval($row['item_tax']); + $item_total = floatval($row['item_total']); + $item_order = intval($row['item_order']); + $tax_id = intval($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_order = $item_order, item_tax_id = $tax_id, item_invoice_id = $new_invoice_id"); + + } + + mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Invoice Generated from Recurring!', history_invoice_id = $new_invoice_id"); + + appNotify("Recurring Sent", "Recurring Invoice $config_invoice_prefix$new_invoice_number for $client_name Sent", "invoice.php?invoice_id=$new_invoice_id", $client_id); + + customAction('invoice_create', $new_invoice_id); + + //Update recurring dates + + mysqli_query($mysqli, "UPDATE recurring SET recurring_last_sent = CURDATE(), recurring_next_date = DATE_ADD(CURDATE(), INTERVAL 1 $recurring_frequency) WHERE recurring_id = $recurring_id"); + + // Get details of the newly generated invoice + $sql = mysqli_query( + $mysqli, + "SELECT * FROM invoices + LEFT JOIN clients ON invoice_client_id = client_id + LEFT JOIN contacts ON clients.client_id = contacts.contact_client_id AND contact_primary = 1 + WHERE invoice_id = $new_invoice_id" + ); + $row = mysqli_fetch_array($sql); + $invoice_prefix = sanitizeInput($row['invoice_prefix']); + $invoice_number = intval($row['invoice_number']); + $invoice_scope = sanitizeInput($row['invoice_scope']); + $invoice_date = sanitizeInput($row['invoice_date']); + $invoice_due = sanitizeInput($row['invoice_due']); + $invoice_amount = floatval($row['invoice_amount']); + $invoice_url_key = sanitizeInput($row['invoice_url_key']); + $client_id = intval($row['client_id']); + $client_name = sanitizeInput($row['client_name']); + $contact_name = sanitizeInput($row['contact_name']); + $contact_email = sanitizeInput($row['contact_email']); + + if ($config_recurring_auto_send_invoice == 1 && $recurring_invoice_email_notify == 1) { + + $subject = "Invoice $invoice_prefix$invoice_number"; + $body = "Hello $contact_name,

An invoice regarding \"$invoice_scope\" has been generated. Please view the details 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, please click here.


--
$company_name - Billing
$config_invoice_from_email
$company_phone"; + + $mail = addToMailQueue([ + [ + 'from' => $config_invoice_from_email, + 'from_name' => $config_invoice_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body + ] + ]); + + if ($mail === true) { + mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Sent', history_description = 'Cron Emailed Invoice!', history_invoice_id = $new_invoice_id"); + mysqli_query($mysqli, "UPDATE invoices SET invoice_status = 'Sent', 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_invoice_id = $new_invoice_id"); + + appNotify("Mail", "Failed to send email to $contact_email"); + + // Logging + logApp("Mail", "error", "Failed to send email to $contact_email regarding $subject. $mail"); + + } + + // Send copies of the invoice to any additional billing contacts + $sql_billing_contacts = mysqli_query($mysqli, "SELECT contact_name, contact_email FROM contacts + WHERE contact_billing = 1 + AND contact_email != '$contact_email' + AND contact_client_id = $client_id" + ); + + while ($billing_contact = mysqli_fetch_array($sql_billing_contacts)) { + $billing_contact_name = sanitizeInput($billing_contact['contact_name']); + $billing_contact_email = sanitizeInput($billing_contact['contact_email']); + + $data = [ + [ + 'from' => $config_invoice_from_email, + 'from_name' => $config_invoice_from_name, + 'recipient' => $billing_contact_email, + 'recipient_name' => $billing_contact_name, + 'subject' => $subject, + 'body' => $body + ] + ]; + + addToMailQueue($data); + } + + } //End if Autosend is on + + // Create Payment from Auto Payment + if ($recurring_payment_recurring_invoice_id) { + + if ($recurring_payment_method == "Stripe") { + // Stripe payment + + // Get Stripe info for client + $stripe_client_details = mysqli_fetch_array(mysqli_query($mysqli, "SELECT * FROM client_stripe WHERE client_id = $client_id LIMIT 1")); + $stripe_id = sanitizeInput($stripe_client_details['stripe_id']); + $stripe_pm = sanitizeInput($stripe_client_details['stripe_pm']); + + if ($config_stripe_enable && $stripe_id && $stripe_pm) { + + // Initialize + require_once __DIR__ . '/plugins/stripe-php/init.php'; + $stripe = new \Stripe\StripeClient($config_stripe_secret); + + $balance_to_pay = round($invoice_amount, 2); + $pi_description = "ITFlow: $client_name payment of $recurring_payment_currency_code $balance_to_pay for $invoice_prefix$invoice_number"; + + // Create a payment intent + try { + $payment_intent = $stripe->paymentIntents->create([ + 'amount' => intval($balance_to_pay * 100), // Times by 100 as Stripe expects values in cents + 'currency' => $recurring_payment_currency_code, + 'customer' => $stripe_id, + 'payment_method' => $stripe_pm, + 'off_session' => true, + 'confirm' => true, + 'description' => $pi_description, + 'metadata' => [ + 'itflow_client_id' => $client_id, + 'itflow_client_name' => $client_name, + 'itflow_invoice_number' => $invoice_prefix . $invoice_number, + 'itflow_invoice_id' => $new_invoice_id, + ] + ]); + + // Get details from PI + $pi_id = sanitizeInput($payment_intent->id); + $pi_date = date('Y-m-d', $payment_intent->created); + $pi_amount_paid = floatval(($payment_intent->amount_received / 100)); + $pi_currency = strtoupper(sanitizeInput($payment_intent->currency)); + $pi_livemode = $payment_intent->livemode; + + } catch (Exception $e) { + $error = $e->getMessage(); + error_log("Stripe payment error - encountered exception during payment intent for invoice ID $new_invoice_id / $invoice_prefix$invoice_number: $error"); + logApp("Stripe", "error", "Exception during PI for invoice ID $new_invoice_id: $error"); + echo $error; + } + + if ($payment_intent->status == "succeeded" && intval($balance_to_pay) == intval($pi_amount_paid)) { + + // Update Invoice Status + mysqli_query($mysqli, "UPDATE invoices SET invoice_status = 'Paid' WHERE invoice_id = $new_invoice_id"); + + // Add Payment to History + mysqli_query($mysqli, "INSERT INTO payments SET payment_date = '$pi_date', payment_amount = $pi_amount_paid, payment_currency_code = '$pi_currency', payment_account_id = $recurring_payment_account_id, payment_method = 'Stripe', payment_reference = 'Stripe - $pi_id', payment_invoice_id = $new_invoice_id"); + mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Paid', history_description = 'Online Payment added (autopay)', history_invoice_id = $new_invoice_id"); + + // Email receipt + if (!empty($config_smtp_host)) { + $subject = "Payment Received - Invoice $invoice_prefix$invoice_number"; + $body = "Hello $contact_name,

We have received online payment for the amount of " . numfmt_format_currency($currency_format, $invoice_amount, $recurring_payment_currency_code) . " for invoice $invoice_prefix$invoice_number. Please keep this email as a receipt for your records.

Amount Paid: " . numfmt_format_currency($currency_format, $invoice_amount, $recurring_payment_currency_code) . "

Thank you for your business!


--
$company_name - Billing Department
$config_invoice_from_email
$company_phone"; + + // Queue Mail + $data = [ + [ + 'from' => $config_invoice_from_email, + 'from_name' => $config_invoice_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body, + ] + ]; + + // Email the internal notification address too + if (!empty($config_invoice_paid_notification_email)) { + $subject = "Payment Received - $client_name - Invoice $invoice_prefix$invoice_number"; + $body = "Hello,

This is a notification that an invoice has been paid in ITFlow. Below is a copy of the receipt sent to the client:-

--------

Hello $contact_name,

We have received online payment for the amount of " . numfmt_format_currency($currency_format, $invoice_amount, $recurring_payment_currency_code) . " for invoice $invoice_prefix$invoice_number. Please keep this email as a receipt for your records.

Amount Paid: " . numfmt_format_currency($currency_format, $invoice_amount, $recurring_payment_currency_code) . "

Thank you for your business!


--
$company_name - Billing Department
$config_invoice_from_email
$company_phone"; + + $data[] = [ + 'from' => $config_invoice_from_email, + 'from_name' => $config_invoice_from_name, + 'recipient' => $config_invoice_paid_notification_email, + 'recipient_name' => $contact_name, + 'subject' => $subject, + 'body' => $body, + ]; + } + + $mail = addToMailQueue($data); + + // Email Logging + $email_id = mysqli_insert_id($mysqli); + mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Sent', history_description = 'Payment Receipt sent to mail queue ID: $email_id!', history_invoice_id = $new_invoice_id"); + logAction("Invoice", "Payment", "Payment receipt for invoice $invoice_prefix$invoice_number queued to $contact_email Email ID: $email_id", $client_id, $new_invoice_id); + } + + // Log info + $extended_log_desc = ''; + if (!$pi_livemode) { + $extended_log_desc = '(DEV MODE)'; + } + + // Create Stripe payment gateway fee as an expense (if configured) + if ($config_stripe_expense_vendor > 0 && $config_stripe_expense_category > 0) { + $gateway_fee = round($invoice_amount * $config_stripe_percentage_fee + $config_stripe_flat_fee, 2); + mysqli_query($mysqli,"INSERT INTO expenses SET expense_date = '$pi_date', expense_amount = $gateway_fee, expense_currency_code = '$company_currency', expense_account_id = $config_stripe_account, expense_vendor_id = $config_stripe_expense_vendor, expense_client_id = $client_id, expense_category_id = $config_stripe_expense_category, expense_description = 'Stripe Transaction for Invoice $invoice_prefix$invoice_number In the Amount of $balance_to_pay', expense_reference = 'Stripe - $pi_id $extended_log_desc'"); + } + + // Notify/log + appNotify("Invoice Paid", "Invoice $invoice_prefix$invoice_number automatically paid", "invoice.php?invoice_id=$new_invoice_id", $client_id); + logAction("Invoice", "Payment", "Auto Stripe payment amount of " . numfmt_format_currency($currency_format, $recurring_amount, $recurring_payment_currency_code) . " added to invoice $invoice_prefix$invoice_number - $pi_id $extended_log_desc", $client_id, $new_invoice_id); + customAction('invoice_pay', $new_invoice_id); + + } else { + mysqli_query($mysqli, "INSERT INTO history SET history_status = 'Payment failed', history_description = 'Stripe autopay failed due to payment error', history_invoice_id = $new_invoice_id"); + logAction("Invoice", "Payment", "Failed auto Payment amount of invoice $invoice_prefix$invoice_number due to Stripe payment error", $client_id, $new_invoice_id); + } + + } else { + logAction("Invoice", "Payment", "Failed auto Payment amount of invoice $invoice_prefix$invoice_number due to Stripe configuration error", $client_id, $new_invoice_id); + } + + } else { + // Else: Cash/Bank payment + + //TODO: Should we send a receipt for auto bank payments, even when nobody actually confirms receipt? + + mysqli_query($mysqli,"INSERT INTO payments SET payment_date = CURDATE(), payment_amount = $recurring_amount, payment_currency_code = '$recurring_payment_currency_code', payment_account_id = $recurring_payment_account_id, payment_method = '$recurring_payment_method', payment_reference = 'Paid via AutoPay', payment_invoice_id = $new_invoice_id"); + + // Get Payment ID for reference + $payment_id = mysqli_insert_id($mysqli); + + // Update Invoice Status + mysqli_query($mysqli,"UPDATE invoices SET invoice_status = 'Paid' WHERE invoice_id = $new_invoice_id"); + + //Add Payment to History + mysqli_query($mysqli,"INSERT INTO history SET history_status = 'Paid', history_description = 'Payment added via Auto Pay', history_invoice_id = $new_invoice_id"); + + // Logging + logAction("Invoice", "Payment", "Auto Payment amount of " . numfmt_format_currency($currency_format, $recurring_amount, $recurring_payment_currency_code) . " added to invoice $invoice_prefix$invoice_number", $client_id, $new_invoice_id); + } + + } //End Auto Payment + +} //End Recurring Invoices Loop + +// Logging +// logAction("Cron", "Task", "Cron created invoices from recurring invoices and sent emails out"); + +// Recurring Expenses +// Loop through all recurring expenses that match today's date and is active +$sql_recurring_expenses = mysqli_query($mysqli, "SELECT * FROM recurring_expenses WHERE recurring_expense_next_date = CURDATE() AND recurring_expense_status = 1"); + +while ($row = mysqli_fetch_array($sql_recurring_expenses)) { + $recurring_expense_id = intval($row['recurring_expense_id']); + $recurring_expense_frequency = intval($row['recurring_expense_frequency']); + $recurring_expense_month = intval($row['recurring_expense_month']); + $recurring_expense_day = intval($row['recurring_expense_day']); + $recurring_expense_description = sanitizeInput($row['recurring_expense_description']); + $recurring_expense_amount = floatval($row['recurring_expense_amount']); + $recurring_expense_payment_method = sanitizeInput($row['recurring_expense_payment_method']); + $recurring_expense_reference = sanitizeInput($row['recurring_expense_reference']); + $recurring_expense_currency_code = sanitizeInput($row['recurring_expense_currency_code']); + $recurring_expense_vendor_id = intval($row['recurring_expense_vendor_id']); + $recurring_expense_category_id = intval($row['recurring_expense_category_id']); + $recurring_expense_account_id = intval($row['recurring_expense_account_id']); + $recurring_expense_client_id = intval($row['recurring_expense_client_id']); + + // Calculate next billing date based on frequency + if ($recurring_expense_frequency == 1) { // Monthly + $next_date_query = "DATE_ADD(CURDATE(), INTERVAL 1 MONTH)"; + } elseif ($recurring_expense_frequency == 2) { // Yearly + $next_date_query = "DATE(CONCAT(YEAR(CURDATE()) + 1, '-', $recurring_expense_month, '-', $recurring_expense_day))"; + } else { + // Handle unexpected frequency values. For now, just use current date. + $next_date_query = "CURDATE()"; + } + + mysqli_query($mysqli,"INSERT INTO expenses SET expense_date = CURDATE(), expense_amount = $recurring_expense_amount, expense_currency_code = '$recurring_expense_currency_code', expense_account_id = $recurring_expense_account_id, expense_vendor_id = $recurring_expense_vendor_id, expense_client_id = $recurring_expense_client_id, expense_category_id = $recurring_expense_category_id, expense_description = '$recurring_expense_description', expense_reference = '$recurring_expense_reference'"); + + $expense_id = mysqli_insert_id($mysqli); + + appNotify("Expense Created", "Expense $recurring_expense_description created from recurring expenses", "expenses.php", $recurring_expense_client_id); + + // Update recurring dates using calculated next billing date + + mysqli_query($mysqli, "UPDATE recurring_expenses SET recurring_expense_last_sent = CURDATE(), recurring_expense_next_date = $next_date_query WHERE recurring_expense_id = $recurring_expense_id"); + + +} //End Recurring Invoices Loop + +// Logging +logApp("Cron", "info", "Cron created expenses from recurring expenses"); + +// TELEMETRY + +if ($config_telemetry > 0 || $config_telemetry == 2) { + + $current_version = exec("git rev-parse HEAD"); + + // Client Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('client_id') AS num FROM clients")); + $client_count = $row['num']; + + // Ticket Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('recurring_id') AS num FROM tickets")); + $ticket_count = $row['num']; + + // Recurring (Scheduled) Ticket Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('scheduled_ticket_id') AS num FROM scheduled_tickets")); + $scheduled_ticket_count = $row['num']; + + // Calendar Event Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('event_id') AS num FROM events")); + $calendar_event_count = $row['num']; + + // Quote Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('quote_id') AS num FROM quotes")); + $quote_count = $row['num']; + + // Invoice Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('invoice_id') AS num FROM invoices")); + $invoice_count = $row['num']; + + // Revenue Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('revenue_id') AS num FROM revenues")); + $revenue_count = $row['num']; + + // Recurring Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('recurring_id') AS num FROM recurring")); + $recurring_count = $row['num']; + + // Account Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('account_id') AS num FROM accounts")); + $account_count = $row['num']; + + // Tax Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('tax_id') AS num FROM taxes")); + $tax_count = $row['num']; + + // Product Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('product_id') AS num FROM products")); + $product_count = $row['num']; + + // Payment Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('payment_id') AS num FROM payments WHERE payment_invoice_id > 0")); + $payment_count = $row['num']; + + // Company Vendor Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('vendor_id') AS num FROM vendors WHERE vendor_template = 0 AND vendor_client_id = 0")); + $company_vendor_count = $row['num']; + + // Expense Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('expense_id') AS num FROM expenses WHERE expense_vendor_id > 0")); + $expense_count = $row['num']; + + // Trip Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('trip_id') AS num FROM trips")); + $trip_count = $row['num']; + + // Transfer Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('transfer_id') AS num FROM transfers")); + $transfer_count = $row['num']; + + // Contact Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('contact_id') AS num FROM contacts")); + $contact_count = $row['num']; + + // Location Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('location_id') AS num FROM locations")); + $location_count = $row['num']; + + // Asset Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('asset_id') AS num FROM assets")); + $asset_count = $row['num']; + + // Software Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('software_id') AS num FROM software WHERE software_template = 0")); + $software_count = $row['num']; + + // Software Template Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('software_id') AS num FROM software WHERE software_template = 1")); + $software_template_count = $row['num']; + + // Password Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('login_id') AS num FROM logins")); + $password_count = $row['num']; + + // Network Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('network_id') AS num FROM networks")); + $network_count = $row['num']; + + // Certificate Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('certificate_id') AS num FROM certificates")); + $certificate_count = $row['num']; + + // Domain Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('domain_id') AS num FROM domains")); + $domain_count = $row['num']; + + // Service Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('service_id') AS num FROM services")); + $service_count = $row['num']; + + // Client Vendor Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('vendor_id') AS num FROM vendors WHERE vendor_template = 0 AND vendor_client_id > 0")); + $client_vendor_count = $row['num']; + + // Vendor Template Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('vendor_id') AS num FROM vendors WHERE vendor_template = 1")); + $vendor_template_count = $row['num']; + + // File Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('file_id') AS num FROM files")); + $file_count = $row['num']; + + // Document Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('document_id') AS num FROM documents WHERE document_template = 0")); + $document_count = $row['num']; + + // Document Template Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('document_id') AS num FROM documents WHERE document_template = 1")); + $document_template_count = $row['num']; + + // Shared Item Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('item_id') AS num FROM shared_items")); + $shared_item_count = $row['num']; + + // Company Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('company_id') AS num FROM companies")); + $company_count = $row['num']; + + // User Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('user_id') AS num FROM users")); + $user_count = $row['num']; + + // Category Expense Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('category_id') AS num FROM categories WHERE category_type = 'Expense'")); + $category_expense_count = $row['num']; + + // Category Income Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('category_id') AS num FROM categories WHERE category_type = 'Income'")); + $category_income_count = $row['num']; + + // Category Referral Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('category_id') AS num FROM categories WHERE category_type = 'Referral'")); + $category_referral_count = $row['num']; + + // Category Payment Method Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('category_id') AS num FROM categories WHERE category_type = 'Payment Method'")); + $category_payment_method_count = $row['num']; + + // Tag Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('tag_id') AS num FROM tags")); + $tag_count = $row['num']; + + // API Key Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('api_key_id') AS num FROM api_keys")); + $api_key_count = $row['num']; + + // Log Count + $row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT COUNT('log_id') AS num FROM logs")); + $log_count = $row['num']; + + $postdata = http_build_query( + array( + 'installation_id' => "$installation_id", + 'version' => "$current_version", + 'company_name' => "$company_name", + 'website' => "$company_website", + 'city' => "$company_city", + 'state' => "$company_state", + 'country' => "$company_country", + 'currency' => "$company_currency", + 'client_count' => $client_count, + 'ticket_count' => $ticket_count, + 'scheduled_ticket_count' => $scheduled_ticket_count, + 'calendar_event_count' => $calendar_event_count, + 'quote_count' => $quote_count, + 'invoice_count' => $invoice_count, + 'revenue_count' => $revenue_count, + 'recurring_count' => $recurring_count, + 'account_count' => $account_count, + 'tax_count' => $tax_count, + 'product_count' => $product_count, + 'payment_count' => $payment_count, + 'company_vendor_count' => $company_vendor_count, + 'expense_count' => $expense_count, + 'trip_count' => $trip_count, + 'transfer_count' => $transfer_count, + 'contact_count' => $contact_count, + 'location_count' => $location_count, + 'asset_count' => $asset_count, + 'software_count' => $software_count, + 'software_template_count' => $software_template_count, + 'password_count' => $password_count, + 'network_count' => $network_count, + 'certificate_count' => $certificate_count, + 'domain_count' => $domain_count, + 'service_count' => $service_count, + 'client_vendor_count' => $client_vendor_count, + 'vendor_template_count' => $vendor_template_count, + 'file_count' => $file_count, + 'document_count' => $document_count, + 'document_template_count' => $document_template_count, + 'shared_item_count' => $shared_item_count, + 'company_count' => $company_count, + 'user_count' => $user_count, + 'category_expense_count' => $category_expense_count, + 'category_income_count' => $category_income_count, + 'category_referral_count' => $category_referral_count, + 'category_payment_method_count' => $category_payment_method_count, + 'tag_count' => $tag_count, + 'api_key_count' => $api_key_count, + 'log_count' => $log_count, + 'config_theme' => "$config_theme", + 'config_enable_cron' => $config_enable_cron, + 'config_ticket_email_parse' => $config_ticket_email_parse, + 'config_module_enable_itdoc' => $config_module_enable_itdoc, + 'config_module_enable_ticketing' => $config_module_enable_ticketing, + 'config_module_enable_accounting' => $config_module_enable_accounting, + 'config_telemetry' => $config_telemetry, + 'collection_method' => 3 + ) + ); + + $opts = array('http' => + array( + 'method' => 'POST', + 'header' => 'Content-type: application/x-www-form-urlencoded', + 'content' => $postdata + ) + ); + + $context = stream_context_create($opts); + + $result = file_get_contents('https://telemetry.itflow.org', false, $context); + + // Logging + // logAction("Cron", "Task", "Cron sent telemetry results to ITFlow Developers"); + +} + + +// Fetch Updates +$updates = fetchUpdates(); + +$update_message = $updates->update_message; + +if ($updates->current_version !== $updates->latest_version) { + // Send Alert to inform Updates Available + appNotify("Update", "$update_message", "admin_update.php"); +} + + + +/* + * ############################################################################################################### + * FINISH UP + * ############################################################################################################### + */ + +// Send Alert to inform Cron was run +appNotify("Cron", "Cron successfully executed", "admin_audit_log.php"); + +// Logging +logApp("Cron", "info", "Cron executed successfully"); diff --git a/cron_certificate_refresher.php b/cron_certificate_refresher.php new file mode 100644 index 00000000..a922551f --- /dev/null +++ b/cron_certificate_refresher.php @@ -0,0 +1,68 @@ + $old_value) { + $new_value = $new_domain_info[$column]; + if ($old_value != $new_value && !in_array($column, $ignored_columns)) { + $column = sanitizeInput($column); + $old_value = sanitizeInput($old_value); + $new_value = sanitizeInput($new_value); + mysqli_query($mysqli,"INSERT INTO domain_history SET domain_history_column = '$column', domain_history_old_value = '$old_value', domain_history_new_value = '$new_value', domain_history_domain_id = $domain_id"); + } + } + +} diff --git a/cron_mail_queue.php b/cron_mail_queue.php new file mode 100644 index 00000000..d7a8ca78 --- /dev/null +++ b/cron_mail_queue.php @@ -0,0 +1,225 @@ + 600) { + + unlink($lock_file_path); + // Logging + logAction("Cron-Mail-Queue", "Delete", "Cron Mail Queuer detected a lock file was present but was over 10 minutes old so it removed it."); + + } else { + + // Logging + logAction("Cron-Mail-Queue", "Locked", "Cron Mail Queuer attempted to execute but was already executing so instead it terminated."); + + exit("Script is already running. Exiting."); + } +} + +// Create a lock file +file_put_contents($lock_file_path, "Locked"); + +// Process Mail Queue + +// Email Status: +// 0 Queued +// 1 Sending +// 2 Failed +// 3 Sent + +/* + * ############################################################################################################### + * Initial email send + * ############################################################################################################### + */ +// Get Mail Queue that has status of Queued and send it to the function sendSingleEmail() located in functions.php +$sql_queue = mysqli_query($mysqli, "SELECT * FROM email_queue WHERE email_status = 0 AND email_queued_at <= NOW()"); + +if (mysqli_num_rows($sql_queue) > 0) { + while ($row = mysqli_fetch_array($sql_queue)) { + $email_id = intval($row['email_id']); + $email_from = $row['email_from']; + $email_from_name = $row['email_from_name']; + $email_recipient = $row['email_recipient']; + $email_recipient_name = $row['email_recipient_name']; + $email_subject = $row['email_subject']; + $email_content = $row['email_content']; + $email_queued_at = $row['email_queued_at']; + $email_sent_at = $row['email_sent_at']; + $email_ics_str = $row['email_cal_str']; + + // First, validate the sender email address + if (filter_var($email_from, FILTER_VALIDATE_EMAIL)) { + + // Sanitized Input + $email_recipient_logging = sanitizeInput($row['email_recipient']); + $email_subject_logging = sanitizeInput($row['email_subject']); + + // Update the status to sending + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id"); + + // Next, verify recipient email is valid + if (filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) { + + $mail = sendSingleEmail( + $config_smtp_host, + $config_smtp_username, + $config_smtp_password, + $config_smtp_encryption, + $config_smtp_port, + $email_from, + $email_from_name, + $email_recipient, + $email_recipient_name, + $email_subject, + $email_content, + $email_ics_str + ); + + if ($mail !== true) { + // Update Message - Failure + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = 1 WHERE email_id = $email_id"); + + appNotify("Cron-Mail-Queue", "Failed to send email #$email_id to $email_recipient_logging"); + + // Logging + logAction("Cron-Mail-Queue", "Error", "Failed to send email: $email_id to $email_recipient_logging regarding $email_subject_logging. $mail"); + } else { + // Update Message - Success + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = 1 WHERE email_id = $email_id"); + } + + } else { + + // Recipient email isn't valid, mark as failed and log the error + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99 WHERE email_id = $email_id"); + + // Logging + logAction("Cron-Mail-Queue", "Error", "Failed to send email: $email_id due to invalid recipient address. Email subject was: $email_subject_logging"); + } + + } else { + error_log("Failed to send email due to invalid sender address (' $email_from ') - check configuration in settings."); + + $email_from_logging = sanitizeInput($row['email_from']); + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_attempts = 99 WHERE email_id = $email_id"); + + // Logging + logAction("Cron-Mail-Queue", "Error", "Failed to send email #$email_id due to invalid sender address: $email_from_logging - check configuration in settings."); + + appNotify("Mail", "Failed to send email #$email_id due to invalid sender address"); + + } + + } +} + + +/* + * ############################################################################################################### + * Retries + * ############################################################################################################### + */ +// Get Mail that failed to send and attempt to send Failed Mail up to 4 times every 30 mins +$sql_failed_queue = mysqli_query($mysqli, "SELECT * FROM email_queue WHERE email_status = 2 AND email_attempts < 4 AND email_failed_at < NOW() + INTERVAL 30 MINUTE"); + +if (mysqli_num_rows($sql_failed_queue) > 0) { + while ($row = mysqli_fetch_array($sql_failed_queue)) { + $email_id = intval($row['email_id']); + $email_from = $row['email_from']; + $email_from_name = $row['email_from_name']; + $email_recipient = $row['email_recipient']; + $email_recipient_name = $row['email_recipient_name']; + $email_subject = $row['email_subject']; + $email_content = $row['email_content']; + $email_queued_at = $row['email_queued_at']; + $email_sent_at = $row['email_sent_at']; + $email_ics_str = $row['email_cal_str']; + // Increment the attempts + $email_attempts = intval($row['email_attempts']) + 1; + + // Sanitized Input + $email_recipient_logging = sanitizeInput($row['email_recipient']); + $email_subject_logging = sanitizeInput($row['email_subject']); + + // Update the status to sending before actually sending + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 1 WHERE email_id = $email_id"); + + // Verify recipient email is valid + if (filter_var($email_recipient, FILTER_VALIDATE_EMAIL)) { + + $mail = sendSingleEmail( + $config_smtp_host, + $config_smtp_username, + $config_smtp_password, + $config_smtp_encryption, + $config_smtp_port, + $email_from, + $email_from_name, + $email_recipient, + $email_recipient_name, + $email_subject, + $email_content, + $email_ics_str + ); + + if ($mail !== true) { + // Update Message + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 2, email_failed_at = NOW(), email_attempts = $email_attempts WHERE email_id = $email_id"); + + // Logging + logAction("Cron-Mail-Queue", "Error", "Failed to re-send email #$email_id to $email_recipient_logging regarding $email_subject_logging. $mail"); + + } else { + + // Update Message + mysqli_query($mysqli, "UPDATE email_queue SET email_status = 3, email_sent_at = NOW(), email_attempts = $email_attempts WHERE email_id = $email_id"); + + } + } + } +} + +// Remove the lock file once mail has finished processing +unlink($lock_file_path); diff --git a/cron_ticket_email_parser.php b/cron_ticket_email_parser.php new file mode 100644 index 00000000..538aca44 --- /dev/null +++ b/cron_ticket_email_parser.php @@ -0,0 +1,556 @@ + Ticketing > Email-to-ticket parsing. See https://docs.itflow.org/ticket_email_parse -- Quitting.."); +} + +// Get system temp directory +$temp_dir = sys_get_temp_dir(); + +// Create the path for the lock file using the temp directory +$lock_file_path = "{$temp_dir}/itflow_email_parser_{$installation_id}.lock"; + +// Check for lock file to prevent concurrent script runs +if (file_exists($lock_file_path)) { + $file_age = time() - filemtime($lock_file_path); + + // If file is older than 5 minutes (300 seconds), delete and continue + if ($file_age > 300) { + unlink($lock_file_path); + + // Logging + logApp("Cron-Email-Parser", "warning", "Cron Email Parser detected a lock file was present but was over 5 minutes old so it removed it."); + + } else { + + // Logging + logApp("Cron-Email-Parser", "warning", "Lock file present. Cron Email Parser attempted to execute but was already executing, so instead it terminated."); + + exit("Script is already running. Exiting."); + } +} + +// Create a lock file +file_put_contents($lock_file_path, "Locked"); + +// PHP Mail Parser +use PhpMimeMailParser\Parser; +require_once "plugins/php-mime-mail-parser/Contracts/CharsetManager.php"; +require_once "plugins/php-mime-mail-parser/Contracts/Middleware.php"; +require_once "plugins/php-mime-mail-parser/Attachment.php"; +require_once "plugins/php-mime-mail-parser/Charset.php"; +require_once "plugins/php-mime-mail-parser/Exception.php"; +require_once "plugins/php-mime-mail-parser/Middleware.php"; +require_once "plugins/php-mime-mail-parser/MiddlewareStack.php"; +require_once "plugins/php-mime-mail-parser/MimePart.php"; +require_once "plugins/php-mime-mail-parser/Parser.php"; + +// Allowed attachment extensions +$allowed_extensions = array('jpg', 'jpeg', 'gif', 'png', 'webp', 'pdf', 'txt', 'md', 'doc', 'docx', 'csv', 'xls', 'xlsx', 'xlsm', 'zip', 'tar', 'gz'); + +// Function to raise a new ticket for a given contact and email them confirmation (if configured) +function addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message, $attachments, $original_message_file) { + global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_ticket_client_general_notifications, $config_ticket_new_ticket_notification_email, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $config_ticket_default_billable, $allowed_extensions; + + $ticket_number_sql = mysqli_fetch_array(mysqli_query($mysqli, "SELECT config_ticket_next_number FROM settings WHERE company_id = 1")); + $ticket_number = intval($ticket_number_sql['config_ticket_next_number']); + $new_config_ticket_next_number = $ticket_number + 1; + mysqli_query($mysqli, "UPDATE settings SET config_ticket_next_number = $new_config_ticket_next_number WHERE company_id = 1"); + + // Clean up the message + $message = trim($message); // Remove leading/trailing whitespace + $message = preg_replace('/\s+/', ' ', $message); // Replace multiple spaces with a single space + $message = nl2br($message); // Convert newlines to
+ + // Wrap the message in a div with controlled line height + $message = "Email from: $contact_name <$contact_email> at $date:-

$message
"; + + $ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix); + $message_esc = mysqli_real_escape_string($mysqli, $message); + $contact_email_esc = mysqli_real_escape_string($mysqli, $contact_email); + $client_id = intval($client_id); + + //Generate a unique URL key for clients to access + $url_key = randomString(156); + + mysqli_query($mysqli, "INSERT INTO tickets SET ticket_prefix = '$ticket_prefix_esc', ticket_number = $ticket_number, ticket_subject = '$subject', ticket_details = '$message_esc', ticket_priority = 'Low', ticket_status = 1, ticket_billable = $config_ticket_default_billable, ticket_created_by = 0, ticket_contact_id = $contact_id, ticket_url_key = '$url_key', ticket_client_id = $client_id"); + $id = mysqli_insert_id($mysqli); + + // Logging + logAction("Ticket", "Create", "Email parser: Client contact $contact_email_esc created ticket $ticket_prefix_esc$ticket_number ($subject) ($id)", $client_id, $id); + + mkdirMissing('uploads/tickets/'); + $att_dir = "uploads/tickets/" . $id . "/"; + mkdirMissing($att_dir); + + rename("uploads/tmp/{$original_message_file}", "{$att_dir}/{$original_message_file}"); + $original_message_file_esc = mysqli_real_escape_string($mysqli, $original_message_file); + mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = 'Original-parsed-email.eml', ticket_attachment_reference_name = '$original_message_file_esc', ticket_attachment_ticket_id = $id"); + + foreach ($attachments as $attachment) { + $att_name = $attachment->getFilename(); + $att_extarr = explode('.', $att_name); + $att_extension = strtolower(end($att_extarr)); + + if (in_array($att_extension, $allowed_extensions)) { + $att_saved_filename = md5(uniqid(rand(), true)) . '.' . $att_extension; + $att_saved_path = $att_dir . $att_saved_filename; + file_put_contents($att_saved_path, $attachment->getContent()); + + $ticket_attachment_name = sanitizeInput($att_name); + $ticket_attachment_reference_name = sanitizeInput($att_saved_filename); + + $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_name); + $ticket_attachment_reference_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_reference_name); + mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_ticket_id = $id"); + } else { + $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name); + logAction("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $contact_email_esc for ticket $ticket_prefix_esc$ticket_number", $client_id, $id); + } + } + + // Guest ticket watchers + if ($client_id == 0) { + mysqli_query($mysqli, "INSERT INTO ticket_watchers SET watcher_email = '$contact_email_esc', watcher_ticket_id = $id"); + } + + $data = []; + if ($config_ticket_client_general_notifications == 1) { + $subject_email = "Ticket created - [$config_ticket_prefix$ticket_number] - $subject"; + $body = "##- Please type your reply above this line -##

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: New
Portal: View ticket

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $contact_email, + 'recipient_name' => $contact_name, + 'subject' => $subject_email, + 'body' => mysqli_real_escape_string($mysqli, $body) + ]; + } + + if ($config_ticket_new_ticket_notification_email) { + if ($client_id == 0) { + $client_name = "Guest"; + } else { + $client_sql = mysqli_query($mysqli, "SELECT client_name FROM clients WHERE client_id = $client_id"); + $client_row = mysqli_fetch_array($client_sql); + $client_name = sanitizeInput($client_row['client_name']); + } + $email_subject = "$config_app_name - New Ticket - $client_name: $subject"; + $email_body = "Hello,

This is a notification that a new ticket has been raised in ITFlow.
Client: $client_name
Priority: Low (email parsed)
Link: https://$config_base_url/ticket.php?ticket_id=$id

--------------------------------

$subject
$message"; + + $data[] = [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $config_ticket_new_ticket_notification_email, + 'recipient_name' => $config_ticket_from_name, + 'subject' => $email_subject, + 'body' => mysqli_real_escape_string($mysqli, $email_body) + ]; + } + + addToMailQueue($data); + + // Custom action/notif handler + customAction('ticket_create', $id); + + return true; +} + +// Add Reply Function +function addReply($from_email, $date, $subject, $ticket_number, $message, $attachments) { + global $mysqli, $config_app_name, $company_name, $company_phone, $config_ticket_prefix, $config_base_url, $config_ticket_from_name, $config_ticket_from_email, $allowed_extensions; + + $ticket_reply_type = 'Client'; + // Clean up the message + $message_parts = explode("##- Please type your reply above this line -##", $message); + $message_body = $message_parts[0]; + $message_body = trim($message_body); // Remove leading/trailing whitespace + $message_body = preg_replace('/\r\n|\r|\n/', ' ', $message_body); // Replace newlines with a space + $message_body = nl2br($message_body); // Convert remaining newlines to
+ + // Wrap the message in a div with controlled line height + $message = "Email from: $from_email at $date:-

$message_body
"; + + $ticket_number_esc = intval($ticket_number); + $message_esc = mysqli_real_escape_string($mysqli, $message); + $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); + + $row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT ticket_id, ticket_subject, ticket_status, ticket_contact_id, ticket_client_id, contact_email, client_name + FROM tickets + LEFT JOIN contacts on tickets.ticket_contact_id = contacts.contact_id + LEFT JOIN clients on tickets.ticket_client_id = clients.client_id + WHERE ticket_number = $ticket_number_esc LIMIT 1")); + + if ($row) { + $ticket_id = intval($row['ticket_id']); + $ticket_subject = sanitizeInput($row['ticket_subject']); + $ticket_status = sanitizeInput($row['ticket_status']); + $ticket_reply_contact = intval($row['ticket_contact_id']); + $ticket_contact_email = sanitizeInput($row['contact_email']); + $client_id = intval($row['ticket_client_id']); + $client_name = sanitizeInput($row['client_name']); + + if ($ticket_status == 5) { + $config_ticket_prefix_esc = mysqli_real_escape_string($mysqli, $config_ticket_prefix); + $ticket_number_esc = mysqli_real_escape_string($mysqli, $ticket_number); + + appNotify("Ticket", "Email parser: $from_email attempted to re-open ticket $config_ticket_prefix_esc$ticket_number_esc (ID $ticket_id) - check inbox manually to see email", "ticket.php?ticket_id=$ticket_id", $client_id); + + $email_subject = "Action required: This ticket is already closed"; + $email_body = "Hi there,

You've tried to reply to a ticket that is closed - we won't see your response.

Please raise a new ticket by sending a new e-mail to our support address below.

--
$company_name - Support
$config_ticket_from_email
$company_phone"; + + $data = [ + [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $from_email, + 'recipient_name' => $from_email, + 'subject' => $email_subject, + 'body' => mysqli_real_escape_string($mysqli, $email_body) + ] + ]; + + addToMailQueue($data); + + return true; + } + + if (empty($ticket_contact_email) || $ticket_contact_email !== $from_email) { + $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); + $row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT contact_id FROM contacts WHERE contact_email = '$from_email_esc' AND contact_client_id = $client_id LIMIT 1")); + if ($row) { + $ticket_reply_contact = intval($row['contact_id']); + } else { + $ticket_reply_type = 'Internal'; + $ticket_reply_contact = '0'; + $message = "WARNING: Contact email mismatch
$message"; + $message_esc = mysqli_real_escape_string($mysqli, $message); + } + } + + mysqli_query($mysqli, "INSERT INTO ticket_replies SET ticket_reply = '$message_esc', ticket_reply_type = '$ticket_reply_type', ticket_reply_time_worked = '00:00:00', ticket_reply_by = $ticket_reply_contact, ticket_reply_ticket_id = $ticket_id"); + $reply_id = mysqli_insert_id($mysqli); + + mkdirMissing('uploads/tickets/'); + foreach ($attachments as $attachment) { + $att_name = $attachment->getFilename(); + $att_extarr = explode('.', $att_name); + $att_extension = strtolower(end($att_extarr)); + + if (in_array($att_extension, $allowed_extensions)) { + $att_saved_filename = md5(uniqid(rand(), true)) . '.' . $att_extension; + $att_saved_path = "uploads/tickets/" . $ticket_id . "/" . $att_saved_filename; + file_put_contents($att_saved_path, $attachment->getContent()); + + $ticket_attachment_name = sanitizeInput($att_name); + $ticket_attachment_reference_name = sanitizeInput($att_saved_filename); + + $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_name); + $ticket_attachment_reference_name_esc = mysqli_real_escape_string($mysqli, $ticket_attachment_reference_name); + mysqli_query($mysqli, "INSERT INTO ticket_attachments SET ticket_attachment_name = '$ticket_attachment_name_esc', ticket_attachment_reference_name = '$ticket_attachment_reference_name_esc', ticket_attachment_reply_id = $reply_id, ticket_attachment_ticket_id = $ticket_id"); + } else { + $ticket_attachment_name_esc = mysqli_real_escape_string($mysqli, $att_name); + logAction("Ticket", "Edit", "Email parser: Blocked attachment $ticket_attachment_name_esc from Client contact $from_email_esc for ticket $config_ticket_prefix$ticket_number_esc", $client_id, $ticket_id); + } + } + + $ticket_assigned_to_sql = mysqli_query($mysqli, "SELECT ticket_assigned_to FROM tickets WHERE ticket_id = $ticket_id LIMIT 1"); + + if ($ticket_assigned_to_sql) { + $row = mysqli_fetch_array($ticket_assigned_to_sql); + $ticket_assigned_to = intval($row['ticket_assigned_to']); + + if ($ticket_assigned_to) { + $tech_sql = mysqli_query($mysqli, "SELECT user_email, user_name FROM users WHERE user_id = $ticket_assigned_to LIMIT 1"); + $tech_row = mysqli_fetch_array($tech_sql); + $tech_email = sanitizeInput($tech_row['user_email']); + $tech_name = sanitizeInput($tech_row['user_name']); + + $email_subject = "$config_app_name - Ticket updated - [$config_ticket_prefix$ticket_number] $ticket_subject"; + $email_body = "Hello $tech_name,

A new reply has been added to the below ticket, check ITFlow for full details.

Client: $client_name
Ticket: $config_ticket_prefix$ticket_number
Subject: $ticket_subject

https://$config_base_url/ticket.php?ticket_id=$ticket_id"; + + $data = [ + [ + 'from' => $config_ticket_from_email, + 'from_name' => $config_ticket_from_name, + 'recipient' => $tech_email, + 'recipient_name' => $tech_name, + 'subject' => mysqli_real_escape_string($mysqli, $email_subject), + 'body' => mysqli_real_escape_string($mysqli, $email_body) + ] + ]; + + addToMailQueue($data); + } + } + + mysqli_query($mysqli, "UPDATE tickets SET ticket_status = 2, ticket_resolved_at = NULL WHERE ticket_id = $ticket_id AND ticket_client_id = $client_id LIMIT 1"); + + logAction("Ticket", "Edit", "Email parser: Client contact $from_email_esc updated ticket $config_ticket_prefix$ticket_number_esc ($subject)", $client_id, $ticket_id); + + customAction('ticket_reply_client', $ticket_id); + + return true; + + } else { + return false; + } +} + +// Function to create a folder in the mailbox if it doesn't exist +function createMailboxFolder($imap, $mailbox, $folderName) { + $folders = imap_list($imap, $mailbox, '*'); + $folderExists = false; + if ($folders !== false) { + foreach ($folders as $folder) { + $folder = str_replace($mailbox, '', $folder); + if ($folder == $folderName) { + $folderExists = true; + break; + } + } + } + if (!$folderExists) { + imap_createmailbox($imap, $mailbox . imap_utf7_encode($folderName)); + imap_subscribe($imap, $mailbox . $folderName); + } +} + +// Initialize IMAP connection +$validate_cert = true; // or false based on your configuration + +$imap_encryption = $config_imap_encryption; // e.g., 'ssl', 'tls', or '' (empty string) for none + +// Start building the mailbox string +$mailbox = '{' . $config_imap_host . ':' . $config_imap_port; + +// Only add the encryption part if $imap_encryption is not empty +if (!empty($imap_encryption)) { + $mailbox .= '/' . $imap_encryption; +} + +// Add the certificate validation part +if ($validate_cert) { + $mailbox .= '/validate-cert'; +} else { + $mailbox .= '/novalidate-cert'; +} + +$mailbox .= '}'; + +// Append 'INBOX' to specify the mailbox folder +$inbox_mailbox = $mailbox . 'INBOX'; + +// Open the IMAP connection +$imap = imap_open($inbox_mailbox, $config_imap_username, $config_imap_password); + +if ($imap === false) { + echo "Error connecting to IMAP server: " . imap_last_error(); + exit; +} + +// Create the "ITFlow" mailbox folder if it doesn't exist +createMailboxFolder($imap, $mailbox, 'ITFlow'); + +// Search for unseen messages and get UIDs +$emails = imap_search($imap, 'UNSEEN', SE_UID); + +// Set Processed and Unprocessed Email count to 0 +$processed_count = 0; +$unprocessed_count = 0; + +if ($emails !== false) { + foreach ($emails as $email_uid) { + $email_processed = false; + + // Save original message + mkdirMissing('uploads/tmp/'); + $original_message_file = "processed-eml-" . randomString(200) . ".eml"; + + $raw_message = imap_fetchheader($imap, $email_uid, FT_UID) . imap_body($imap, $email_uid, FT_UID); + file_put_contents("uploads/tmp/{$original_message_file}", $raw_message); + + // Parse the message using php-mime-mail-parser + $parser = new \PhpMimeMailParser\Parser(); + $parser->setText($raw_message); + + // Get from address + $from_addresses = $parser->getAddresses('from'); + $from_email = sanitizeInput($from_addresses[0]['address'] ?? 'itflow-guest@example.com'); + $from_name = sanitizeInput($from_addresses[0]['display'] ?? 'Unknown'); + + $from_domain = explode("@", $from_email); + $from_domain = sanitizeInput(end($from_domain)); + + // Get subject + $subject = sanitizeInput($parser->getHeader('subject') ?? 'No Subject'); + + // Get date + $date = sanitizeInput($parser->getHeader('date') ?? date('Y-m-d H:i:s')); + + // Get message body + $message_body_html = $parser->getMessageBody('html'); + $message_body_text = $parser->getMessageBody('text'); + $message_body = $message_body_html ?: nl2br(htmlspecialchars($message_body_text)); + + // Handle inline images + $attachments = $parser->getAttachments(); + $inline_attachments = []; + foreach ($attachments as $attachment) { + if ($attachment->getContentDisposition() === 'inline' && $attachment->getContentID()) { + $cid = trim($attachment->getContentID(), '<>'); + $data = base64_encode($attachment->getContent()); + $mime = $attachment->getContentType(); + $dataUri = "data:$mime;base64,$data"; + $message_body = str_replace("cid:$cid", $dataUri, $message_body); + } else { + $inline_attachments[] = $attachment; + } + } + $attachments = $inline_attachments; + + // Process the email + if (preg_match("/\[$config_ticket_prefix(\d+)\]/", $subject, $ticket_number_matches)) { + $ticket_number = intval($ticket_number_matches[1]); + + if (addReply($from_email, $date, $subject, $ticket_number, $message_body, $attachments)) { + $email_processed = true; + } + } else { + // Check if the sender is a known contact + $from_email_esc = mysqli_real_escape_string($mysqli, $from_email); + $any_contact_sql = mysqli_query($mysqli, "SELECT * FROM contacts WHERE contact_email = '$from_email_esc' LIMIT 1"); + $row = mysqli_fetch_array($any_contact_sql); + + if ($row) { + $contact_name = sanitizeInput($row['contact_name']); + $contact_id = intval($row['contact_id']); + $contact_email = sanitizeInput($row['contact_email']); + $client_id = intval($row['contact_client_id']); + + if (addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file)) { + $email_processed = true; + } + } else { + // Check if the domain is associated with a client + $from_domain_esc = mysqli_real_escape_string($mysqli, $from_domain); + $domain_sql = mysqli_query($mysqli, "SELECT * FROM domains WHERE domain_name = '$from_domain_esc' LIMIT 1"); + $row = mysqli_fetch_assoc($domain_sql); + + if ($row && $from_domain == $row['domain_name']) { + $client_id = intval($row['domain_client_id']); + + // Create a new contact + $contact_name = $from_name; + $contact_email = $from_email; + mysqli_query($mysqli, "INSERT INTO contacts SET contact_name = '".mysqli_real_escape_string($mysqli, $contact_name)."', contact_email = '".mysqli_real_escape_string($mysqli, $contact_email)."', contact_notes = 'Added automatically via email parsing.', contact_client_id = $client_id"); + $contact_id = mysqli_insert_id($mysqli); + + // Logging + logAction("Contact", "Create", "Email parser: created contact " . mysqli_real_escape_string($mysqli, $contact_name) . "", $client_id, $contact_id); + customAction('contact_create', $contact_id); + + if (addTicket($contact_id, $contact_name, $contact_email, $client_id, $date, $subject, $message_body, $attachments, $original_message_file)) { + $email_processed = true; + } + } elseif ($config_ticket_email_parse_unknown_senders) { + // Parse even if the sender is unknown + $bad_from_pattern = "/daemon|postmaster/i"; + if (!(preg_match($bad_from_pattern, $from_email))) { + if (addTicket(0, $from_name, $from_email, 0, $date, $subject, $message_body, $attachments, $original_message_file)) { + $email_processed = true; + } + } + } + } + } + + if ($email_processed) { + // Mark the message as seen + imap_setflag_full($imap, $email_uid, "\\Seen", ST_UID); + // Move the message to the 'ITFlow' folder + imap_mail_move($imap, $email_uid, 'ITFlow', CP_UID); + // Get a Processed Email Count + $processed_count++; + } else { + // Flag the message for manual review without marking it as read + imap_setflag_full($imap, $email_uid, "\\Flagged", ST_UID); + // Clear the Seen flag to ensure the email remains unread + imap_clearflag_full($imap, $email_uid, "\\Seen", ST_UID); + // Get an Unprocessed email count + $unprocessed_count++; + } + + // Delete the temporary message file + if (file_exists("uploads/tmp/{$original_message_file}")) { + unlink("uploads/tmp/{$original_message_file}"); + } + } +} + +// Expunge deleted mails +imap_expunge($imap); + +// Close the IMAP connection +imap_close($imap); + +// Calculate the total execution time -uncomment the code below to get exec time +$script_end_time = microtime(true); +$execution_time = $script_end_time - $script_start_time; +$execution_time_formatted = number_format($execution_time, 2); + +// Insert a log entry into the logs table +$processed_info = "Processed: $processed_count email(s), Unprocessed: $unprocessed_count email(s)"; +// Remove Comment below for Troubleshooting + +//logAction("Cron-Email-Parser", "Execution", "Cron Email Parser executed in $execution_time_formatted seconds. $processed_info"); + +// END Calculate execution time + +// Remove the lock file +unlink($lock_file_path); + +// DEBUG +echo "\nLock File Path: $lock_file_path\n"; +if (file_exists($lock_file_path)) { + echo "\nLock is present\n\n"; +} +echo "Processed Emails into tickets: $processed_count\n"; +echo "Unprocessed Emails: $unprocessed_count\n"; diff --git a/mfa_enforcement.php b/mfa_enforcement.php index 2b45bc13..a43fd89f 100644 --- a/mfa_enforcement.php +++ b/mfa_enforcement.php @@ -4,6 +4,11 @@ require_once "functions.php"; require_once "check_login.php"; require_once 'plugins/totp/totp.php'; +// Get Company Logo +$sql = mysqli_query($mysqli, "SELECT company_logo FROM companies"); +$row = mysqli_fetch_array($sql); +$company_logo = nullable_htmlentities($row['company_logo']); + // Only generate the token once and store it in session: if (empty($_SESSION['mfa_token'])) { @@ -60,24 +65,19 @@ $data = "otpauth://totp/ITFlow:$session_email?secret=$token";
-
- - ID - - Queued @@ -137,7 +132,7 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); Attempts ActionAction
$email_from_name"?> $email_recipient_name"?> + diff --git a/includes/app_version.php b/includes/app_version.php index b4263e0b..7588b7c5 100644 --- a/includes/app_version.php +++ b/includes/app_version.php @@ -2,7 +2,7 @@ /* * ITFlow * This file defines the current ITFlow release/version - * Update this file each time we merge develop into master. Format is YY.M (add a .v if there is more than one release a month. + * Update this file each time we merge develop into master. Format is YY.MM (add a .v if there is more than one release a month. */ -DEFINE("APP_VERSION", "25.01"); +DEFINE("APP_VERSION", "25.01.1");