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"; - } -}