diff --git a/ajax/ajax_service_details.php b/ajax/ajax_service_details.php index 6dc0eea5..9f2bb3c0 100644 --- a/ajax/ajax_service_details.php +++ b/ajax/ajax_service_details.php @@ -129,7 +129,7 @@ ob_start(); } else { $ip = ''; } - echo "
  • $row[asset_name] $ip
  • "; + echo "
  • $row[asset_name] $ip
  • "; } ?> @@ -165,7 +165,7 @@ ob_start(); } foreach($networks as $network) { $network = explode(":", $network); - echo "
  • $network[0] (VLAN $network[1])
  • "; + echo "
  • $network[0] (VLAN $network[1])
  • "; } ?> @@ -200,7 +200,7 @@ ob_start(); $location"; + echo "
  • $location
  • "; } ?> @@ -220,7 +220,7 @@ ob_start(); // Showing linked domains while ($row = mysqli_fetch_array($sql_domains)) { if (!empty($row['domain_name'])) { - echo "
  • $row[domain_name]
  • "; + echo "
  • $row[domain_name]
  • "; } } ?> @@ -241,7 +241,7 @@ ob_start(); // Showing linked certs while ($row = mysqli_fetch_array($sql_certificates)) { if (!empty($row['certificate_name'])) { - echo "
  • $row[certificate_name] ($row[certificate_domain])
  • "; + echo "
  • $row[certificate_name] ($row[certificate_domain])
  • "; } } ?> @@ -270,7 +270,7 @@ ob_start(); @@ -288,7 +288,7 @@ ob_start(); mysqli_data_seek($sql_contacts, 0); while ($row = mysqli_fetch_array($sql_contacts)) { - echo "
  • $row[contact_name]
  • "; + echo "
  • $row[contact_name]
  • "; } ?> @@ -309,14 +309,14 @@ ob_start(); // Showing logins linked to assets while ($row = mysqli_fetch_array($sql_assets)) { if (!empty($row['login_name'])) { - echo "
  • $row[login_name]
  • "; + echo "
  • $row[login_name]
  • "; } } // Showing explicitly linked logins while ($row = mysqli_fetch_array($sql_logins)) { if (!empty($row['login_name'])) { - echo "
  • $row[login_name]
  • "; + echo "
  • $row[login_name]
  • "; } } ?> diff --git a/assets.php b/assets.php index 2f6ed856..14eb96d3 100644 --- a/assets.php +++ b/assets.php @@ -46,16 +46,14 @@ if (!$client_url) { } } -if ($client_url) { - // Location Filter - if (isset($_GET['location']) & !empty($_GET['location'])) { - $location_query = 'AND (asset_location_id = ' . intval($_GET['location']) . ')'; - $location_filter = intval($_GET['location']); - } else { - // Default - any - $location_query = ''; - $location_filter = ''; - } +// Location Filter +if ($client_url && isset($_GET['location']) && !empty($_GET['location'])) { + $location_query = 'AND (asset_location_id = ' . intval($_GET['location']) . ')'; + $location_filter = intval($_GET['location']); +} else { + // Default - any + $location_query = ''; + $location_filter = ''; } //Get Asset Counts diff --git a/client_document_details.php b/client_document_details.php index e9f8b869..00f05086 100644 --- a/client_document_details.php +++ b/client_document_details.php @@ -299,7 +299,7 @@ $page_title = $row['document_name']; ?>
    - + diff --git a/contact_details.php b/contact_details.php index 0d27e314..a55e533b 100644 --- a/contact_details.php +++ b/contact_details.php @@ -247,7 +247,7 @@ if (isset($_GET['contact_id'])) { @@ -369,15 +369,6 @@ if (isset($_GET['contact_id'])) { $asset_physical_location = nullable_htmlentities($row['asset_physical_location']); $asset_notes = nullable_htmlentities($row['asset_notes']); $asset_created_at = nullable_htmlentities($row['asset_created_at']); - $asset_vendor_id = intval($row['asset_vendor_id']); - $asset_location_id = intval($row['asset_location_id']); - $asset_network_id = intval($row['interface_network_id']); - $asset_contact_id = intval($row['asset_contact_id']); - - $login_id = $row['login_id']; - $login_username = nullable_htmlentities(decryptLoginEntry($row['login_username'])); - $login_password = nullable_htmlentities(decryptLoginEntry($row['login_password'])); - $device_icon = getAssetIcon($asset_type); ?> diff --git a/contacts.php b/contacts.php index 607268e6..801faa0d 100644 --- a/contacts.php +++ b/contacts.php @@ -43,16 +43,14 @@ if (!$client_url) { } } -if ($client_url) { +if ($client_url && isset($_GET['location']) && !empty($_GET['location'])) { // Location Filter - if (isset($_GET['location']) & !empty($_GET['location'])) { - $location_query = 'AND (contact_location_id = ' . intval($_GET['location']) . ')'; - $location_filter = intval($_GET['location']); - } else { - // Default - any - $location_query = ''; - $location_filter = ''; - } + $location_query = 'AND (contact_location_id = ' . intval($_GET['location']) . ')'; + $location_filter = intval($_GET['location']); +} else { + // Default - any + $location_query = ''; + $location_filter = ''; } //Rebuild URL diff --git a/credentials.php b/credentials.php index d8b8afc2..68024fdf 100644 --- a/credentials.php +++ b/credentials.php @@ -50,18 +50,16 @@ if (!$client_url) { } } -if ($client_url) { - // Location Filter - if (isset($_GET['location']) & !empty($_GET['location'])) { - $location_query = 'AND (a.asset_location_id = ' . intval($_GET['location']) . ')'; - $location_query_innerjoin = 'INNER JOIN assets a on a.asset_id = l.login_asset_id '; - $location_filter = intval($_GET['location']); - } else { - // Default - any - $location_query_innerjoin = ''; - $location_query = ''; - $location_filter = ''; - } +// Location Filter +if ($client_url && isset($_GET['location']) && !empty($_GET['location'])) { + $location_query = 'AND (a.asset_location_id = ' . intval($_GET['location']) . ')'; + $location_query_innerjoin = 'INNER JOIN assets a on a.asset_id = l.login_asset_id '; + $location_filter = intval($_GET['location']); +} else { + // Default - any + $location_query_innerjoin = ''; + $location_query = ''; + $location_filter = ''; } $sql = mysqli_query( @@ -77,7 +75,6 @@ $sql = mysqli_query( AND (l.login_name LIKE '%$q%' OR l.login_description LIKE '%$q%' OR l.login_uri LIKE '%$q%' OR tag_name LIKE '%$q%' OR client_name LIKE '%$q%') $location_query $client_query - GROUP BY l.login_id ORDER BY l.login_important DESC, $sort $order LIMIT $record_from, $record_to" ); diff --git a/cron.php b/cron.php deleted file mode 100644 index e5a7ea22..00000000 --- a/cron.php +++ /dev/null @@ -1,1169 +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"); - - // 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 - * ############################################################################################################### - */ - -// 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"); diff --git a/cron_certificate_refresher.php b/cron_certificate_refresher.php deleted file mode 100644 index 67f3575a..00000000 --- a/cron_certificate_refresher.php +++ /dev/null @@ -1,68 +0,0 @@ - $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 deleted file mode 100644 index 19337e6f..00000000 --- a/cron_mail_queue.php +++ /dev/null @@ -1,225 +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 00970092..00000000 --- a/cron_ticket_email_parser.php +++ /dev/null @@ -1,556 +0,0 @@ - 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/global_search.php b/global_search.php index a7130489..b8e130bd 100644 --- a/global_search.php +++ b/global_search.php @@ -698,6 +698,8 @@ if (isset($_GET['query'])) { diff --git a/includes/client_overview_side_nav.php b/includes/client_overview_side_nav.php index a66aa30f..7a5c1253 100644 --- a/includes/client_overview_side_nav.php +++ b/includes/client_overview_side_nav.php @@ -34,18 +34,6 @@

    ALL Assets

    - - + + - - - = 1) { ?> - - - diff --git a/post/user/asset_model.php b/post/user/asset_model.php index bb2a1256..144d1ad0 100644 --- a/post/user/asset_model.php +++ b/post/user/asset_model.php @@ -19,11 +19,11 @@ $mac = sanitizeInput($_POST['mac']); $uri = sanitizeInput($_POST['uri']); $uri_2 = sanitizeInput($_POST['uri_2']); $status = sanitizeInput($_POST['status']); -$location = intval($_POST['location']); +$location = intval($_POST['location'] ?? 0); $physical_location = sanitizeInput($_POST['physical_location']); -$vendor = intval($_POST['vendor']); -$contact = intval($_POST['contact']); -$network = intval($_POST['network']); +$vendor = intval($_POST['vendor'] ?? 0); +$contact = intval($_POST['contact'] ?? 0); +$network = intval($_POST['network'] ?? 0); $purchase_reference = sanitizeInput($_POST['purchase_reference']); $purchase_date = sanitizeInput($_POST['purchase_date']); if (empty($purchase_date)) { diff --git a/post/user/certificate_model.php b/post/user/certificate_model.php index 4629b479..2b99e5a5 100644 --- a/post/user/certificate_model.php +++ b/post/user/certificate_model.php @@ -8,5 +8,5 @@ $issued_by = sanitizeInput($_POST['issued_by']); $expire = sanitizeInput($_POST['expire']); $public_key = sanitizeInput($_POST['public_key']); $notes = sanitizeInput($_POST['notes']); -$domain_id = intval($_POST['domain_id']); +$domain_id = intval($_POST['domain_id'] ?? 0); $client_id = intval($_POST['client_id']); diff --git a/post/user/contact_model.php b/post/user/contact_model.php index cfc98732..40bcb127 100644 --- a/post/user/contact_model.php +++ b/post/user/contact_model.php @@ -14,7 +14,7 @@ $contact_primary = intval($_POST['contact_primary'] ?? 0); $contact_important = intval($_POST['contact_important'] ?? 0); $contact_billing = intval($_POST['contact_billing'] ?? 0); $contact_technical = intval($_POST['contact_technical'] ?? 0); -$location_id = intval($_POST['location']); +$location_id = intval($_POST['location'] ?? 0); $pin = sanitizeInput($_POST['pin']); $auth_method = sanitizeInput($_POST['auth_method']); diff --git a/post/user/credential_model.php b/post/user/credential_model.php index 655a770d..48c7adf0 100644 --- a/post/user/credential_model.php +++ b/post/user/credential_model.php @@ -12,7 +12,7 @@ $password = encryptLoginEntry(trim($_POST['password'])); $otp_secret = sanitizeInput($_POST['otp_secret']); $note = sanitizeInput($_POST['note']); $important = intval($_POST['important'] ?? 0); -$contact_id = intval($_POST['contact']); -$vendor_id = intval($_POST['vendor']); -$asset_id = intval($_POST['asset']); -$software_id = intval($_POST['software']); +$contact_id = intval($_POST['contact'] ?? 0); +$vendor_id = intval($_POST['vendor'] ?? 0); +$asset_id = intval($_POST['asset'] ?? 0); +$software_id = intval($_POST['software'] ?? 0); diff --git a/post/user/domain_model.php b/post/user/domain_model.php index 13a79c57..0281b1ce 100644 --- a/post/user/domain_model.php +++ b/post/user/domain_model.php @@ -3,10 +3,9 @@ defined('FROM_POST_HANDLER') || die("Direct file access is not allowed"); $name = preg_replace("(^https?://)", "", sanitizeInput($_POST['name'])); $description = sanitizeInput($_POST['description']); -$registrar = intval($_POST['registrar']); -$dnshost = intval($_POST['dnshost']); -$webhost = intval($_POST['webhost']); -$mailhost = intval($_POST['mailhost']); +$registrar = intval($_POST['registrar'] ?? 0); +$dnshost = intval($_POST['dnshost'] ?? 0); +$webhost = intval($_POST['webhost'] ?? 0); +$mailhost = intval($_POST['mailhost'] ?? 0); $expire = sanitizeInput($_POST['expire']); $notes = sanitizeInput($_POST['notes']); - diff --git a/post/user/location_model.php b/post/user/location_model.php index 8b7780ed..35788818 100644 --- a/post/user/location_model.php +++ b/post/user/location_model.php @@ -13,5 +13,5 @@ $phone = preg_replace("/[^0-9]/", '',$_POST['phone']); $fax = preg_replace("/[^0-9]/", '',$_POST['fax']); $hours = sanitizeInput($_POST['hours']); $notes = sanitizeInput($_POST['notes']); -$contact = intval($_POST['contact']); +$contact = intval($_POST['contact'] ?? 0); $location_primary = intval($_POST['location_primary'] ?? 0); diff --git a/post/user/network_model.php b/post/user/network_model.php index a25f1b4d..500a4832 100644 --- a/post/user/network_model.php +++ b/post/user/network_model.php @@ -11,5 +11,5 @@ $primary_dns = sanitizeInput($_POST['primary_dns']); $secondary_dns = sanitizeInput($_POST['secondary_dns']); $dhcp_range = sanitizeInput($_POST['dhcp_range']); $notes = sanitizeInput($_POST['notes']); -$location_id = intval($_POST['location']); +$location_id = intval($_POST['location'] ?? 0); $client_id = intval($_POST['client_id']); diff --git a/report_tickets_unbilled.php b/report_tickets_unbilled.php index 32c20c60..0bc306f0 100644 --- a/report_tickets_unbilled.php +++ b/report_tickets_unbilled.php @@ -152,7 +152,7 @@ $rows = 0; - + diff --git a/scripts/cron.php b/scripts/cron.php index a2f0c9ca..540496b1 100644 --- a/scripts/cron.php +++ b/scripts/cron.php @@ -229,7 +229,7 @@ foreach ($certificateAlertArray as $day) { $client_id = intval($row['client_id']); $client_name = sanitizeInput($row['client_name']); - appNotify("Certificate Expiring", "Certificate $certificate_name for $client_name will expire in $day Days on $certificate_expire", "client_certificates.php?client_id=$client_id", $client_id); + appNotify("Certificate Expiring", "Certificate $certificate_name for $client_name will expire in $day Days on $certificate_expire", "certificates.php?client_id=$client_id", $client_id); } diff --git a/software.php b/software.php index ae97ba71..66f62c97 100644 --- a/software.php +++ b/software.php @@ -157,11 +157,12 @@ $num_rows = mysqli_fetch_row(mysqli_query($mysqli, "SELECT FOUND_ROWS()")); $tr_class = "table-danger"; } elseif ($days_until_expiry <= 90) { $tr_class = "table-warning"; + } else { + $tr_class = ''; } } else { $software_expire_display = "-"; - $tr_class = ''; } $software_notes = nullable_htmlentities($row['software_notes']); diff --git a/tickets.php b/tickets.php index fc218624..91a0b428 100644 --- a/tickets.php +++ b/tickets.php @@ -45,6 +45,17 @@ if (isset($_GET['status']) && is_array($_GET['status']) && !empty($_GET['status' } } +if (isset($_GET['billable']) && ($_GET['billable']) == '1') { + if (isset($_GET['unbilled'])) { + $billable = 1; + $ticket_billable_snippet = "AND ticket_billable = 1 AND ticket_invoice_id = 0"; + $ticket_status_snippet = '1 = 1'; + } +} else { + $billable = 0; + $ticket_billable_snippet = ''; +} + if (isset($_GET['category'])) { $category = sanitizeInput($_GET['category']); if ($category == 'empty') { @@ -98,6 +109,7 @@ $sql = mysqli_query( $category_snippet AND DATE(ticket_created_at) BETWEEN '$dtf' AND '$dtt' AND (CONCAT(ticket_prefix,ticket_number) LIKE '%$q%' OR client_name LIKE '%$q%' OR ticket_subject LIKE '%$q%' OR ticket_status_name LIKE '%$q%' OR ticket_priority LIKE '%$q%' OR user_name LIKE '%$q%' OR contact_name LIKE '%$q%' OR asset_name LIKE '%$q%' OR vendor_name LIKE '%$q%' OR ticket_vendor_ticket_number LIKE '%q%') + $ticket_billable_snippet $ticket_permission_snippet $client_query ORDER BY