mirror of https://github.com/itflow-org/itflow
Merge pull request #1136 from itflow-org/cron-scripts-move
Move cli/cron scripts
This commit is contained in:
commit
740f477d4c
8
cron.php
8
cron.php
|
|
@ -1,5 +1,8 @@
|
|||
<?php
|
||||
|
||||
// Cron scripts have now moved to the /scripts folder
|
||||
// This file will soon be removed from the project
|
||||
|
||||
// Set working directory to the directory this cron script lives at.
|
||||
chdir(dirname(__FILE__));
|
||||
|
||||
|
|
@ -1003,8 +1006,9 @@ if ($updates->current_version !== $updates->latest_version) {
|
|||
* ###############################################################################################################
|
||||
*/
|
||||
|
||||
// Send Alert to inform Cron was run
|
||||
appNotify("Cron", "Cron successfully executed", "admin_audit_log.php");
|
||||
// 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");
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
<FilesMatch "\.(php)$">
|
||||
Require all denied
|
||||
</FilesMatch>
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,69 @@
|
|||
<?php
|
||||
|
||||
require_once "config.php";
|
||||
|
||||
// Set Timezone
|
||||
require_once "inc_set_timezone.php";
|
||||
|
||||
require_once "functions.php";
|
||||
|
||||
|
||||
$sql_settings = mysqli_query($mysqli, "SELECT * FROM settings WHERE settings.company_id = 1");
|
||||
|
||||
$row = mysqli_fetch_array($sql_settings);
|
||||
|
||||
// Company Settings
|
||||
$config_enable_cron = intval($row['config_enable_cron']);
|
||||
$config_cron_key = $row['config_cron_key'];
|
||||
|
||||
$argv = $_SERVER['argv'];
|
||||
|
||||
// Check cron is enabled
|
||||
if ($config_enable_cron == 0) {
|
||||
exit("Cron: is not enabled -- Quitting..");
|
||||
}
|
||||
|
||||
// Check Cron Key
|
||||
if ( $argv[1] !== $config_cron_key ) {
|
||||
exit("Cron Key invalid -- Quitting..");
|
||||
}
|
||||
|
||||
/*
|
||||
* ###############################################################################################################
|
||||
* UPDATE CERTIFICATE EXPIRY DATE
|
||||
* ###############################################################################################################
|
||||
*/
|
||||
|
||||
$sql_certificates = mysqli_query(
|
||||
$mysqli,
|
||||
"SELECT * FROM certificates
|
||||
LEFT JOIN clients ON certificates.certificate_client_id = clients.client_id
|
||||
WHERE certificate_archived_at IS NULL
|
||||
AND client_archived_at IS NULL"
|
||||
);
|
||||
|
||||
while ($row = mysqli_fetch_array($sql_certificates)) {
|
||||
$certificate_id = intval($row['certificate_id']);
|
||||
$domain = sanitizeInput($row['certificate_domain']);
|
||||
|
||||
$certificate = getSSL($domain);
|
||||
|
||||
$expire = sanitizeInput($certificate['expire']);
|
||||
$issued_by = sanitizeInput($certificate['issued_by']);
|
||||
$public_key = sanitizeInput($certificate['public_key']);
|
||||
|
||||
if (!empty($expire)) {
|
||||
|
||||
echo "\n$domain\n";
|
||||
echo "$issued_by\n";
|
||||
echo "$expire\n";
|
||||
echo "$public_key\n\n";
|
||||
|
||||
$expire = "'" . $expire . "'";
|
||||
mysqli_query($mysqli,"UPDATE certificates SET certificate_issued_by = '$issued_by', certificate_expire = $expire, certificate_public_key = '$public_key' WHERE certificate_id = $certificate_id");
|
||||
|
||||
} else {
|
||||
error_log("Certificate Cron Error - Error updating $domain");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,82 @@
|
|||
<?php
|
||||
|
||||
require_once "config.php";
|
||||
|
||||
// Set Timezone
|
||||
require_once "inc_set_timezone.php";
|
||||
|
||||
require_once "functions.php";
|
||||
|
||||
|
||||
$sql_settings = mysqli_query($mysqli, "SELECT * FROM settings WHERE settings.company_id = 1");
|
||||
|
||||
$row = mysqli_fetch_array($sql_settings);
|
||||
|
||||
// Company Settings
|
||||
$config_enable_cron = intval($row['config_enable_cron']);
|
||||
$config_cron_key = $row['config_cron_key'];
|
||||
|
||||
$argv = $_SERVER['argv'];
|
||||
|
||||
// Check cron is enabled
|
||||
if ($config_enable_cron == 0) {
|
||||
exit("Cron: is not enabled -- Quitting..");
|
||||
}
|
||||
|
||||
// Check Cron Key
|
||||
if ( $argv[1] !== $config_cron_key ) {
|
||||
exit("Cron Key invalid -- Quitting..");
|
||||
}
|
||||
|
||||
/*
|
||||
* ###############################################################################################################
|
||||
* REFRESH DATA
|
||||
* ###############################################################################################################
|
||||
*/
|
||||
// 2023-02-20 JQ Commenting this code out as its intermitently breaking cron executions, investigating
|
||||
// ERROR
|
||||
// php cron.php
|
||||
// PHP Fatal error: Uncaught TypeError: mysqli_fetch_array(): Argument #1 ($result) must be of type mysqli_result, bool given in cron.php:141
|
||||
// Stack trace:
|
||||
//#0 cron.php(141): mysqli_fetch_array()
|
||||
//#1 {main}
|
||||
// thrown in cron.php on line 141
|
||||
// END ERROR
|
||||
// REFRESH DOMAIN WHOIS DATA (1 a day)
|
||||
// Get the oldest updated domain (MariaDB shows NULLs first when ordering by default)
|
||||
$row = mysqli_fetch_array(mysqli_query($mysqli, "SELECT domain_id, domain_name, domain_expire FROM `domains` ORDER BY domain_updated_at LIMIT 1"));
|
||||
|
||||
if ($row) {
|
||||
|
||||
// Get current data in database
|
||||
$domain_id = intval($row['domain_id']);
|
||||
$domain_name = sanitizeInput($row['domain_name']);
|
||||
$current_expire = sanitizeInput($row['domain_expire']);
|
||||
|
||||
// Touch the record we're refreshing to ensure we don't loop
|
||||
mysqli_query($mysqli, "UPDATE domains SET domain_updated_at = NOW() WHERE domain_id = $domain_id");
|
||||
|
||||
// Lookup fresh info
|
||||
$expire = getDomainExpirationDate($domain_name);
|
||||
$records = getDomainRecords($domain_name);
|
||||
$a = sanitizeInput($records['a']);
|
||||
$ns = sanitizeInput($records['ns']);
|
||||
$mx = sanitizeInput($records['mx']);
|
||||
$txt = sanitizeInput($records['txt']);
|
||||
$whois = sanitizeInput($records['whois']);
|
||||
|
||||
// Handle expiry date
|
||||
if (strtotime($expire)) {
|
||||
$expire = "'" . $expire . "'"; // Valid
|
||||
} elseif (!strtotime($expire) && strtotime($current_expire)) {
|
||||
// New expiry date is invalid, but old one is OK - reverting back
|
||||
$expire = "'" . $current_expire . "'";
|
||||
} else {
|
||||
// Neither are valid, setting expiry to NULL
|
||||
$expire = 'NULL';
|
||||
}
|
||||
|
||||
|
||||
// Update the domain
|
||||
mysqli_query($mysqli, "UPDATE domains SET domain_name = '$domain_name', domain_expire = $expire, domain_ip = '$a', domain_name_servers = '$ns', domain_mail_servers = '$mx', domain_txt = '$txt', domain_raw_whois = '$whois' WHERE domain_id = $domain_id");
|
||||
}
|
||||
|
|
@ -0,0 +1,228 @@
|
|||
<?php
|
||||
|
||||
require_once "config.php";
|
||||
|
||||
// Set Timezone
|
||||
require_once "inc_set_timezone.php";
|
||||
|
||||
require_once "functions.php";
|
||||
|
||||
$sql_settings = mysqli_query($mysqli, "SELECT * FROM settings WHERE company_id = 1");
|
||||
|
||||
$row = mysqli_fetch_array($sql_settings);
|
||||
|
||||
// Company Settings
|
||||
$config_enable_cron = intval($row['config_enable_cron']);
|
||||
$config_cron_key = $row['config_cron_key'];
|
||||
$config_smtp_host = $row['config_smtp_host'];
|
||||
$config_smtp_username = $row['config_smtp_username'];
|
||||
$config_smtp_password = $row['config_smtp_password'];
|
||||
$config_smtp_port = intval($row['config_smtp_port']);
|
||||
$config_smtp_encryption = $row['config_smtp_encryption'];
|
||||
|
||||
$argv = $_SERVER['argv'];
|
||||
|
||||
// Check cron is enabled
|
||||
if ($config_enable_cron == 0) {
|
||||
error_log("Mail queue error - Cron is not enabled");
|
||||
exit("Cron: is not enabled -- Quitting..");
|
||||
}
|
||||
|
||||
// Check Cron Key
|
||||
if ($argv[1] !== $config_cron_key) {
|
||||
error_log("Mail queue error - Invalid cron key supplied");
|
||||
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_mail_queue_{$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 10 minutes (600 seconds), delete and continue
|
||||
if ($file_age > 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);
|
||||
|
|
@ -0,0 +1,558 @@
|
|||
<?php
|
||||
/*
|
||||
* CRON - Email Parser
|
||||
* Process emails and create/update tickets using PHP's native IMAP functions with UIDs
|
||||
*/
|
||||
|
||||
// Start the timer
|
||||
$script_start_time = microtime(true); // unComment when Debugging Execution time
|
||||
|
||||
// Set working directory to the directory this cron script lives at.
|
||||
chdir(dirname(__FILE__));
|
||||
|
||||
// Get ITFlow config & helper functions
|
||||
require_once "config.php";
|
||||
|
||||
// Set Timezone
|
||||
require_once "inc_set_timezone.php";
|
||||
require_once "functions.php";
|
||||
|
||||
// Get settings for the "default" company
|
||||
require_once "get_settings.php";
|
||||
|
||||
$config_ticket_prefix = sanitizeInput($config_ticket_prefix);
|
||||
$config_ticket_from_name = sanitizeInput($config_ticket_from_name);
|
||||
$config_ticket_email_parse_unknown_senders = intval($row['config_ticket_email_parse_unknown_senders']);
|
||||
|
||||
// Get company name & phone & timezone
|
||||
$sql = mysqli_query($mysqli, "SELECT * FROM companies, settings WHERE companies.company_id = settings.company_id AND companies.company_id = 1");
|
||||
$row = mysqli_fetch_array($sql);
|
||||
$company_name = sanitizeInput($row['company_name']);
|
||||
$company_phone = sanitizeInput(formatPhoneNumber($row['company_phone']));
|
||||
|
||||
// Check setting enabled
|
||||
if ($config_ticket_email_parse == 0) {
|
||||
exit("Email Parser: Feature is not enabled - check Settings > 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 <br>
|
||||
|
||||
// Wrap the message in a div with controlled line height
|
||||
$message = "<i>Email from: <b>$contact_name</b> <$contact_email> at $date:-</i> <br><br><div style='line-height:1.5;'>$message</div>";
|
||||
|
||||
$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 = "<i style='color: #808080'>##- Please type your reply above this line -##</i><br><br>Hello $contact_name,<br><br>Thank you for your email. A ticket regarding \"$subject\" has been automatically created for you.<br><br>Ticket: $config_ticket_prefix$ticket_number<br>Subject: $subject<br>Status: New<br>https://$config_base_url/portal/ticket.php?id=$id<br><br>--<br>$company_name - Support<br>$config_ticket_from_email<br>$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, <br><br>This is a notification that a new ticket has been raised in ITFlow. <br>Client: $client_name<br>Priority: Low (email parsed)<br>Link: https://$config_base_url/ticket.php?ticket_id=$id <br><br>--------------------------------<br><br><b>$subject</b><br>$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($mysqli, $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 <br>
|
||||
|
||||
// Wrap the message in a div with controlled line height
|
||||
$message = "<i>Email from: $from_email at $date:-</i> <br><br><div style='line-height:1.5;'>$message_body</div>";
|
||||
|
||||
$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, <br><br>You've tried to reply to a ticket that is closed - we won't see your response. <br><br>Please raise a new ticket by sending a new e-mail to our support address below. <br><br>--<br>$company_name - Support<br>$config_ticket_from_email<br>$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($mysqli, $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 = "<b>WARNING: Contact email mismatch</b><br>$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,<br><br>A new reply has been added to the below ticket, check ITFlow for full details.<br><br>Client: $client_name<br>Ticket: $config_ticket_prefix$ticket_number<br>Subject: $ticket_subject<br><br>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($mysqli, $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";
|
||||
|
|
@ -0,0 +1,389 @@
|
|||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
// Example
|
||||
//php setup_cli.php --help
|
||||
//php setup_cli.php --host=localhost --username=itflow --password=secret --database=itflow --base-url=example.com/itflow --locale=en_US --timezone=UTC --currency=USD --company-name="My Company" --country="United States" --user-name="John Doe" --user-email="john@example.com" --user-password="admin123" --non-interactive
|
||||
|
||||
// Change to the directory of this script so that all shell commands run here
|
||||
chdir(__DIR__);
|
||||
|
||||
// Ensure we're running from command line
|
||||
if (php_sapi_name() !== 'cli') {
|
||||
die("This setup script must be run from the command line.\n");
|
||||
}
|
||||
|
||||
// Define required arguments
|
||||
$required_args = [
|
||||
'host' => '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 "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 = "<?php\n\n";
|
||||
$new_config .= "\$dbhost = " . var_export($host, true) . ";\n";
|
||||
$new_config .= "\$dbusername = " . var_export($username, true) . ";\n";
|
||||
$new_config .= "\$dbpassword = " . var_export($password, true) . ";\n";
|
||||
$new_config .= "\$database = " . var_export($database, true) . ";\n";
|
||||
$new_config .= "\$mysqli = mysqli_connect(\$dbhost, \$dbusername, \$dbpassword, \$database) or die('Database Connection Failed');\n";
|
||||
$new_config .= "\$config_app_name = 'ITFlow';\n";
|
||||
$new_config .= "\$config_base_url = '" . addslashes($base_url) . "';\n";
|
||||
$new_config .= "\$config_https_only = TRUE;\n";
|
||||
$new_config .= "\$repo_branch = 'master';\n";
|
||||
$new_config .= "\$installation_id = '$installation_id';\n";
|
||||
|
||||
if (file_put_contents("config.php", $new_config) === false) {
|
||||
die("Failed to write config.php. Check file permissions.\n");
|
||||
}
|
||||
|
||||
if (!file_exists('config.php')) {
|
||||
die("config.php does not exist after write attempt.\n");
|
||||
}
|
||||
|
||||
include "config.php";
|
||||
|
||||
// Import DB Schema
|
||||
echo "Importing database schema...\n";
|
||||
$filename = 'db.sql';
|
||||
if (!file_exists($filename)) {
|
||||
die("db.sql file not found.\n");
|
||||
}
|
||||
$templine = '';
|
||||
$lines = file($filename);
|
||||
foreach ($lines as $line) {
|
||||
if (substr($line, 0, 2) == '--' || trim($line) == '')
|
||||
continue;
|
||||
$templine .= $line;
|
||||
if (substr(trim($line), -1, 1) == ';') {
|
||||
mysqli_query($mysqli, $templine) or die("Error performing query: $templine\n" . mysqli_error($mysqli) . "\n");
|
||||
$templine = '';
|
||||
}
|
||||
}
|
||||
echo "Database imported successfully.\n";
|
||||
|
||||
// Create User
|
||||
$password_hash = password_hash(trim($user_password_plain), PASSWORD_DEFAULT);
|
||||
$site_encryption_master_key = randomString();
|
||||
$user_specific_encryption_ciphertext = setupFirstUserSpecificKey($user_password_plain, $site_encryption_master_key);
|
||||
|
||||
mysqli_query($mysqli,"INSERT INTO users SET user_name = '$user_name', user_email = '$user_email', user_password = '$password_hash', user_specific_encryption_ciphertext = '$user_specific_encryption_ciphertext'");
|
||||
mysqli_query($mysqli,"INSERT INTO user_settings SET user_id = 1, user_role = 3");
|
||||
echo "User $user_name created successfully.\n";
|
||||
|
||||
// Company Details
|
||||
mysqli_query($mysqli,"INSERT INTO companies SET company_name = '$company_name', company_address = '$address', company_city = '$city', company_state = '$state', company_zip = '$zip', company_country = '$country', company_phone = '$phone', company_email = '$company_email', company_website = '$website', company_locale = '$locale', company_currency = '$currency_code'");
|
||||
|
||||
// Insert default settings and categories
|
||||
$latest_database_version = LATEST_DATABASE_VERSION;
|
||||
mysqli_query($mysqli,"INSERT INTO settings SET company_id = 1, config_current_database_version = '$latest_database_version', config_invoice_prefix = 'INV-', config_invoice_next_number = 1, config_recurring_prefix = 'REC-', config_recurring_next_number = 1, config_invoice_overdue_reminders = '1,3,7', config_quote_prefix = 'QUO-', config_quote_next_number = 1, config_default_net_terms = 30, config_ticket_next_number = 1, config_ticket_prefix = 'TCK-'");
|
||||
|
||||
// Categories
|
||||
mysqli_query($mysqli,"INSERT INTO categories SET category_name = 'Office Supplies', category_type = 'Expense', category_color = 'blue'");
|
||||
mysqli_query($mysqli,"INSERT INTO categories SET category_name = 'Travel', category_type = 'Expense', category_color = 'red'");
|
||||
mysqli_query($mysqli,"INSERT INTO categories SET category_name = 'Advertising', category_type = 'Expense', category_color = 'green'");
|
||||
mysqli_query($mysqli,"INSERT INTO categories SET category_name = 'Service', category_type = 'Income', category_color = 'blue'");
|
||||
mysqli_query($mysqli,"INSERT INTO categories SET category_name = 'Friend', category_type = 'Referral', category_color = 'blue'");
|
||||
mysqli_query($mysqli,"INSERT INTO categories SET category_name = 'Search Engine', category_type = 'Referral', category_color = 'red'");
|
||||
mysqli_query($mysqli,"INSERT INTO categories SET category_name = 'Cash', category_type = 'Payment Method', category_color = 'blue'");
|
||||
mysqli_query($mysqli,"INSERT INTO categories SET category_name = 'Check', category_type = 'Payment Method', category_color = 'red'");
|
||||
mysqli_query($mysqli,"INSERT INTO categories SET category_name = 'Bank Transfer', category_type = 'Payment Method', category_color = 'green'");
|
||||
|
||||
// Calendar
|
||||
mysqli_query($mysqli,"INSERT INTO calendars SET calendar_name = 'Default', calendar_color = 'blue'");
|
||||
|
||||
// Ticket Statuses
|
||||
mysqli_query($mysqli, "INSERT INTO ticket_statuses SET ticket_status_name = 'New', ticket_status_color = '#dc3545'");
|
||||
mysqli_query($mysqli, "INSERT INTO ticket_statuses SET ticket_status_name = 'Open', ticket_status_color = '#007bff'");
|
||||
mysqli_query($mysqli, "INSERT INTO ticket_statuses SET ticket_status_name = 'On Hold', ticket_status_color = '#28a745'");
|
||||
mysqli_query($mysqli, "INSERT INTO ticket_statuses SET ticket_status_name = 'Resolved', ticket_status_color = '#343a40'");
|
||||
mysqli_query($mysqli, "INSERT INTO ticket_statuses SET ticket_status_name = 'Closed', ticket_status_color = '#343a40'");
|
||||
|
||||
// Modules
|
||||
mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_client', module_description = 'General client & contact management'");
|
||||
mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_support', module_description = 'Access to ticketing, assets and documentation'");
|
||||
mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_credential', module_description = 'Access to client credentials - usernames, passwords and 2FA codes'");
|
||||
mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_sales', module_description = 'Access to quotes, invoices and products'");
|
||||
mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_financial', module_description = 'Access to payments, accounts, expenses and budgets'");
|
||||
mysqli_query($mysqli, "INSERT INTO modules SET module_name = 'module_reporting', module_description = 'Access to all reports'");
|
||||
|
||||
// Roles
|
||||
mysqli_query($mysqli, "INSERT INTO user_roles SET user_role_id = 1, user_role_name = 'Accountant', user_role_description = 'Built-in - Limited access to financial-focused modules'");
|
||||
mysqli_query($mysqli, "INSERT INTO user_role_permissions SET user_role_id = 1, module_id = 1, user_role_permission_level = 1");
|
||||
mysqli_query($mysqli, "INSERT INTO user_role_permissions SET user_role_id = 1, module_id = 2, user_role_permission_level = 1");
|
||||
mysqli_query($mysqli, "INSERT INTO user_role_permissions SET user_role_id = 1, module_id = 4, user_role_permission_level = 1");
|
||||
mysqli_query($mysqli, "INSERT INTO user_role_permissions SET user_role_id = 1, module_id = 5, user_role_permission_level = 2");
|
||||
mysqli_query($mysqli, "INSERT INTO user_role_permissions SET user_role_id = 1, module_id = 6, user_role_permission_level = 1");
|
||||
|
||||
mysqli_query($mysqli, "INSERT INTO user_roles SET user_role_id = 2, user_role_name = 'Technician', user_role_description = 'Built-in - Limited access to technical-focused modules'");
|
||||
mysqli_query($mysqli, "INSERT INTO user_role_permissions SET user_role_id = 2, module_id = 1, user_role_permission_level = 2");
|
||||
mysqli_query($mysqli, "INSERT INTO user_role_permissions SET user_role_id = 2, module_id = 2, user_role_permission_level = 2");
|
||||
mysqli_query($mysqli, "INSERT INTO user_role_permissions SET user_role_id = 2, module_id = 3, user_role_permission_level = 2");
|
||||
mysqli_query($mysqli, "INSERT INTO user_role_permissions SET user_role_id = 2, module_id = 4, user_role_permission_level = 2");
|
||||
|
||||
mysqli_query($mysqli, "INSERT INTO user_roles SET user_role_id = 3, user_role_name = 'Administrator', user_role_description = 'Built-in - Full administrative access', user_role_is_admin = 1");
|
||||
|
||||
// Custom Links
|
||||
mysqli_query($mysqli,"INSERT INTO custom_links SET custom_link_name = 'Docs', custom_link_uri = 'https://docs.itflow.org', custom_link_new_tab = 1, custom_link_icon = 'question-circle'");
|
||||
|
||||
// Finalizing
|
||||
mysqli_query($mysqli,"UPDATE companies SET company_locale = '$locale', company_currency = '$currency_code' WHERE company_id = 1");
|
||||
mysqli_query($mysqli,"UPDATE settings SET config_timezone = '$timezone', config_phone_mask = 1 WHERE company_id = 1");
|
||||
mysqli_query($mysqli,"INSERT INTO accounts SET account_name = 'Cash', account_currency_code = '$currency_code'");
|
||||
|
||||
// Telemetry (optional if interactive)
|
||||
if (!$non_interactive) {
|
||||
echo "\n=== Telemetry ===\n";
|
||||
echo "Would you like to share anonymous usage data with the project maintainers? [y/N]: ";
|
||||
$share = strtolower(trim(fgets(STDIN)));
|
||||
if ($share === 'y') {
|
||||
mysqli_query($mysqli,"UPDATE settings SET config_telemetry = 2");
|
||||
|
||||
echo "Any comments to include? Press Enter if none: ";
|
||||
$comments = trim(fgets(STDIN));
|
||||
|
||||
$sql = mysqli_query($mysqli,"SELECT * FROM companies WHERE company_id = 1");
|
||||
$row = mysqli_fetch_array($sql);
|
||||
$company_name_db = $row['company_name'];
|
||||
$website_db = $row['company_website'];
|
||||
$city_db = $row['company_city'];
|
||||
$state_db = $row['company_state'];
|
||||
$country_db = $row['company_country'];
|
||||
$currency_db = $row['company_currency'];
|
||||
|
||||
$postdata = http_build_query([
|
||||
'installation_id' => "$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);
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
// Change to the directory of this script so that all shell commands run here
|
||||
chdir(__DIR__);
|
||||
|
||||
// Ensure script is run only from the CLI
|
||||
if (php_sapi_name() !== 'cli') {
|
||||
die("This script can only be run from the command line.\n");
|
||||
}
|
||||
|
||||
// Ensure the script is run by the owner of the file
|
||||
$fileOwner = fileowner(__FILE__);
|
||||
$currentUser = posix_geteuid(); // Get the current effective user ID
|
||||
|
||||
if ($currentUser !== $fileOwner) {
|
||||
$ownerInfo = posix_getpwuid($fileOwner);
|
||||
$ownerName = $ownerInfo['name'] ?? 'unknown';
|
||||
fwrite(STDERR, "Error: This script must be run by the file owner ($ownerName) to proceed.\nYou could try sudo -u $ownerName php update_cli.php\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
require_once "config.php";
|
||||
require_once "functions.php";
|
||||
|
||||
// A function to print the help message so that we don't duplicate it
|
||||
function printHelp() {
|
||||
echo "Usage: php update_cli.php [options]\n\n";
|
||||
echo "Options:\n";
|
||||
echo " --help Show this help message.\n";
|
||||
echo " --update Perform a git pull to update the application.\n";
|
||||
echo " --force_update Perform a git fetch and hard reset to origin/master.\n";
|
||||
echo " --update_db Update the database structure to the latest version.\n";
|
||||
echo "\nIf no options are provided, a standard update (git pull) is performed.\n";
|
||||
}
|
||||
|
||||
// Define allowed options (removed 'user')
|
||||
$allowed_options = [
|
||||
'help',
|
||||
'update',
|
||||
'force_update',
|
||||
'update_db'
|
||||
];
|
||||
|
||||
// Parse command-line options
|
||||
$options = getopt('', ['update', 'force_update', 'update_db', 'help']);
|
||||
|
||||
// Check for invalid options by comparing argv against allowed options
|
||||
$argv_copy = $argv;
|
||||
array_shift($argv_copy); // Remove script name
|
||||
|
||||
foreach ($argv_copy as $arg) {
|
||||
if (substr($arg, 0, 2) === '--') {
|
||||
// Extract the option name (everything after -- and before = if present)
|
||||
$eqPos = strpos($arg, '=');
|
||||
if ($eqPos !== false) {
|
||||
$optName = substr($arg, 2, $eqPos - 2);
|
||||
} else {
|
||||
$optName = substr($arg, 2);
|
||||
}
|
||||
|
||||
// Check if option name is allowed
|
||||
if (!in_array($optName, $allowed_options)) {
|
||||
echo "Error: Unrecognized option: $arg\n\n";
|
||||
printHelp();
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If "help" is requested, show instructions and exit
|
||||
if (isset($options['help'])) {
|
||||
printHelp();
|
||||
exit;
|
||||
}
|
||||
|
||||
// If no recognized options are passed, default to --update
|
||||
if (count($options) === 0) {
|
||||
$options['update'] = true;
|
||||
}
|
||||
|
||||
// If "update" or "force_update" is requested
|
||||
if (isset($options['update']) || isset($options['force_update'])) {
|
||||
if (isset($options['force_update'])) {
|
||||
// Perform a hard reset
|
||||
exec("git fetch --all 2>&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 "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";
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue