Removed unused legacy functions and split the functions into their own file and use function.php to call them

This commit is contained in:
johnnyq
2026-07-14 16:32:45 -04:00
parent c1447f5bad
commit a2a96f9752
11 changed files with 1978 additions and 2307 deletions

File diff suppressed because one or more lines are too long

341
functions/app.php Normal file
View File

@@ -0,0 +1,341 @@
<?php
// App/UI helpers - icons, badges, lookups, mail queue, iCal, taxes, update check
// Split from the former monolithic functions.php
function getAssetIcon($asset_type)
{
if ($asset_type == 'Laptop') {
$device_icon = "laptop";
} elseif ($asset_type == 'Desktop') {
$device_icon = "desktop";
} elseif ($asset_type == 'Server') {
$device_icon = "server";
} elseif ($asset_type == 'Printer') {
$device_icon = "print";
} elseif ($asset_type == 'Camera') {
$device_icon = "video";
} elseif ($asset_type == 'Switch') {
$device_icon = "network-wired";
} elseif ($asset_type == 'Firewall/Router') {
$device_icon = "fire-alt";
} elseif ($asset_type == 'Access Point') {
$device_icon = "wifi";
} elseif ($asset_type == 'Phone') {
$device_icon = "phone";
} elseif ($asset_type == 'Mobile Phone') {
$device_icon = "mobile-alt";
} elseif ($asset_type == 'Tablet') {
$device_icon = "tablet-alt";
} elseif ($asset_type == 'Display') {
$device_icon = "tv";
} elseif ($asset_type == 'Virtual Machine') {
$device_icon = "cloud";
} else {
$device_icon = "tag";
}
return $device_icon;
}
function getInvoiceBadgeColor($invoice_status)
{
if ($invoice_status == "Sent") {
$invoice_badge_color = "warning text-white";
} elseif ($invoice_status == "Viewed") {
$invoice_badge_color = "info";
} elseif ($invoice_status == "Partial") {
$invoice_badge_color = "primary";
} elseif ($invoice_status == "Paid") {
$invoice_badge_color = "success";
} elseif ($invoice_status == "Cancelled") {
$invoice_badge_color = "danger";
} else {
$invoice_badge_color = "secondary";
}
return $invoice_badge_color;
}
function getTicketStatusName($ticket_status) {
global $mysqli;
$status_id = intval($ticket_status);
$row = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM ticket_statuses WHERE ticket_status_id = $status_id LIMIT 1"));
if ($row) {
return nullable_htmlentities($row['ticket_status_name']);
}
// Default return
return "Unknown";
}
// Helper function for missing data fallback
function getFallback($data) {
return !empty($data) ? $data : '-';
}
/**
* Retrieves a specified field's value from a table based on the record's id.
* It validates the table and field names, automatically determines the primary key (or uses the first column as fallback),
* and returns the field value with an appropriate escaping method.
*
* @param string $table The name of the table.
* @param int $id The record's id.
* @param string $field The field (column) to retrieve.
* @param string $escape_method The escape method: 'sql' (default, auto-detects int), 'html', 'json', or 'int'.
*
* @return mixed The escaped field value, or null if not found or invalid input.
*/
function getFieldById($table, $id, $field, $escape_method = 'sql') {
global $mysqli; // Use the global MySQLi connection
// Validate table and field names to allow only letters, numbers, and underscores
if (!preg_match('/^[a-zA-Z0-9_]+$/', $table) || !preg_match('/^[a-zA-Z0-9_]+$/', $field)) {
return null; // Invalid table or field name
}
// Sanitize id as an integer
$id = (int)$id;
// Get the list of columns and their details from the table
$columns_result = mysqli_query($mysqli, "SHOW COLUMNS FROM `$table`");
if (!$columns_result || mysqli_num_rows($columns_result) == 0) {
return null; // Table not found or has no columns
}
// Build an associative array with column details
$columns = [];
while ($row = mysqli_fetch_assoc($columns_result)) {
$columns[$row['Field']] = [
'type' => $row['Type'],
'key' => $row['Key']
];
}
// Find the primary key field if available
$id_field = null;
foreach ($columns as $col => $details) {
if ($details['key'] === 'PRI') {
$id_field = $col;
break;
}
}
// Fallback: if no primary key is found, use the first column
if (!$id_field) {
reset($columns);
$id_field = key($columns);
}
// Ensure the requested field exists; if not, default to the id field
if (!array_key_exists($field, $columns)) {
$field = $id_field;
}
// Build and execute the query to fetch the specified field value
$query = "SELECT `$field` FROM `$table` WHERE `$id_field` = $id";
$sql = mysqli_query($mysqli, $query);
if ($sql && mysqli_num_rows($sql) > 0) {
$row = mysqli_fetch_assoc($sql);
$value = $row[$field];
// Apply the desired escaping method or auto-detect integer type if using SQL escaping
switch ($escape_method) {
case 'raw':
return $value; // Return as-is from the database
case 'html':
return htmlspecialchars($value ?? '', ENT_QUOTES, 'UTF-8'); // Escape for HTML
case 'json':
return json_encode($value); // Escape for JSON
case 'int':
return (int)$value; // Explicitly cast value to integer
case 'sql':
default:
// Auto-detect if the field type is integer
if (stripos($columns[$field]['type'], 'int') !== false) {
return (int)$value;
} else {
return sanitizeInput($value); // Escape for SQL using a custom function
}
}
}
return null; // Return null if no record was found
}
// Recursive function to display folder options - Used in folders files and documents
function display_folder_options($parent_folder_id, $client_id, $indent = 0) {
global $mysqli;
$sql_folders = mysqli_query($mysqli, "SELECT * FROM folders WHERE parent_folder = $parent_folder_id AND folder_client_id = $client_id ORDER BY folder_name ASC");
while ($row = mysqli_fetch_assoc($sql_folders)) {
$folder_id = intval($row['folder_id']);
$folder_name = nullable_htmlentities($row['folder_name']);
// Indentation for subfolders
$indentation = str_repeat('&nbsp;', $indent * 4);
// Check if this folder is selected
$selected = '';
if ((isset($_GET['folder_id']) && intval($_GET['folder_id']) === $folder_id) ||
(isset($_POST['folder']) && intval($_POST['folder']) === $folder_id)) {
$selected = 'selected';
}
echo "<option value=\"$folder_id\" $selected>$indentation$folder_name</option>";
// Recursively display subfolders
display_folder_options($folder_id, $client_id, $indent + 1);
}
}
function fetchUpdates() {
global $repo_branch;
// Fetch the latest code changes but don't apply them
exec("git fetch", $output, $result);
$latest_version = exec("git rev-parse origin/$repo_branch");
$current_version = exec("git rev-parse HEAD");
if ($current_version == $latest_version) {
$update_message = "No Updates available";
} else {
$update_message = "New Updates are Available [$latest_version]";
}
$updates = new stdClass();
$updates->output = $output;
$updates->result = $result;
$updates->current_version = $current_version;
$updates->latest_version = $latest_version;
$updates->update_message = $update_message;
return $updates;
}
function getMonthlyTax($tax_name, $month, $year, $mysqli)
{
// SQL to calculate monthly tax
$sql = "SELECT SUM(item_tax) AS monthly_tax FROM invoice_items
LEFT JOIN invoices ON invoice_items.item_invoice_id = invoices.invoice_id
LEFT JOIN payments ON invoices.invoice_id = payments.payment_invoice_id
WHERE YEAR(payments.payment_date) = $year AND MONTH(payments.payment_date) = $month
AND invoice_items.item_tax_id = (SELECT tax_id FROM taxes WHERE tax_name = '$tax_name')";
$result = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_assoc($result);
return $row['monthly_tax'] ?? 0;
}
function getQuarterlyTax($tax_name, $quarter, $year, $mysqli)
{
// Calculate start and end months for the quarter
$start_month = ($quarter - 1) * 3 + 1;
$end_month = $start_month + 2;
// SQL to calculate quarterly tax
$sql = "SELECT SUM(item_tax) AS quarterly_tax FROM invoice_items
LEFT JOIN invoices ON invoice_items.item_invoice_id = invoices.invoice_id
LEFT JOIN payments ON invoices.invoice_id = payments.payment_invoice_id
WHERE YEAR(payments.payment_date) = $year AND MONTH(payments.payment_date) BETWEEN $start_month AND $end_month
AND invoice_items.item_tax_id = (SELECT tax_id FROM taxes WHERE tax_name = '$tax_name')";
$result = mysqli_query($mysqli, $sql);
$row = mysqli_fetch_assoc($result);
return $row['quarterly_tax'] ?? 0;
}
function addToMailQueue($data) {
global $mysqli;
foreach ($data as $email) {
$from = strval($email['from']);
$from_name = strval($email['from_name']);
$recipient = strval($email['recipient']);
$recipient_name = strval($email['recipient_name']);
$subject = strval($email['subject']);
$body = strval($email['body']);
$cal_str = '';
if (isset($email['cal_str'])) {
$cal_str = mysqli_escape_string($mysqli, $email['cal_str']);
}
// Check if 'email_queued_at' is set and not empty
if (isset($email['queued_at']) && !empty($email['queued_at'])) {
$queued_at = "'" . sanitizeInput($email['queued_at']) . "'";
} else {
// Use the current date and time if 'email_queued_at' is not set or empty
$queued_at = 'CURRENT_TIMESTAMP()';
}
mysqli_query($mysqli, "INSERT INTO email_queue SET email_recipient = '$recipient', email_recipient_name = '$recipient_name', email_from = '$from', email_from_name = '$from_name', email_subject = '$subject', email_content = '$body', email_queued_at = $queued_at, email_cal_str = '$cal_str'");
}
return true;
}
function createiCalStr($datetime, $title, $description, $location)
{
require_once "plugins/zapcal/zapcallib.php";
// Create the iCal object
$cal_event = new ZCiCal();
$event = new ZCiCalNode("VEVENT", $cal_event->curnode);
// Set the method to REQUEST to indicate an invite
$event->addNode(new ZCiCalDataNode("METHOD:REQUEST"));
$event->addNode(new ZCiCalDataNode("SUMMARY:" . $title));
$event->addNode(new ZCiCalDataNode("DTSTART:" . ZCiCal::fromSqlDateTime($datetime)));
// Assuming the end time is the same as start time.
// Todo: adjust this for actual duration
$event->addNode(new ZCiCalDataNode("DTEND:" . ZCiCal::fromSqlDateTime($datetime)));
$event->addNode(new ZCiCalDataNode("DTSTAMP:" . ZCiCal::fromSqlDateTime()));
$uid = date('Y-m-d-H-i-s') . "@" . $_SERVER['SERVER_NAME'];
$event->addNode(new ZCiCalDataNode("UID:" . $uid));
$event->addNode(new ZCiCalDataNode("LOCATION:" . $location));
$event->addNode(new ZCiCalDataNode("DESCRIPTION:" . $description));
// Todo: add organizer details
// $event->addNode(new ZCiCalDataNode("ORGANIZER;CN=Organizer Name:MAILTO:organizer@example.com"));
// Return the iCal string
return $cal_event->export();
}
function createiCalStrCancel($originaliCalStr) {
require_once "plugins/zapcal/zapcallib.php";
// Import the original iCal string
$cal_event = new ZCiCal($originaliCalStr);
// Iterate through the iCalendar object to find VEVENT nodes
foreach($cal_event->tree->child as $node) {
if($node->getName() == "VEVENT") {
// Check if STATUS node exists, update it, or add a new one
$statusFound = false;
foreach($node->data as $key => $value) {
if($key == "STATUS") {
$value->setValue("CANCELLED");
$statusFound = true;
break; // Exit the loop once the STATUS is updated
}
}
// If STATUS node is not found, add a new STATUS node
if (!$statusFound) {
$node->addNode(new ZCiCalDataNode("STATUS:CANCELLED"));
}
}
}
// Return the modified iCal string
return $cal_event->export();
}

142
functions/auth.php Normal file
View File

@@ -0,0 +1,142 @@
<?php
// Role and permission enforcement
// Split from the former monolithic functions.php
/*
* LEGACY Role validation
* Admin - 3
* Tech - 2
* Accountant - 1
*/
function validateAdminRole() {
global $session_user_role;
if (!isset($session_user_role) || $session_user_role != 3) {
$_SESSION['alert_type'] = "danger";
$_SESSION['alert_message'] = WORDING_ROLECHECK_FAILED;
header("Location: " . $_SERVER["HTTP_REFERER"]);
exit();
}
}
// LEGACY
// Validates a user is an accountant (or admin). Stops page load and attempts to direct away from the page if not (i.e. user is a tech)
function validateAccountantRole() {
global $session_user_role;
if (!isset($session_user_role) || $session_user_role == 2) {
$_SESSION['alert_type'] = "danger";
$_SESSION['alert_message'] = WORDING_ROLECHECK_FAILED;
header("Location: " . $_SERVER["HTTP_REFERER"]);
exit();
}
}
// When provided a module name (e.g. module_support), returns the associated permission level (false=none, 1=read, 2=write, 3=full)
function lookupUserPermission($module) {
global $mysqli, $session_is_admin, $session_user_role;
if (isset($session_is_admin) && $session_is_admin === true) {
return 3;
}
$module = sanitizeInput($module);
$sql = mysqli_query(
$mysqli,
"SELECT
user_role_permissions.user_role_permission_level
FROM
modules
JOIN
user_role_permissions
ON
modules.module_id = user_role_permissions.module_id
WHERE
module_name = '$module' AND user_role_permissions.user_role_id = $session_user_role"
);
$row = mysqli_fetch_assoc($sql);
if (isset($row['user_role_permission_level'])) {
return intval($row['user_role_permission_level']);
}
// Default return for no module permission
return false;
}
// Ensures a user has access to a module (e.g. module_support) with at least the required permission level provided (defaults to read)
function enforceUserPermission($module, $check_access_level = 1) {
$permitted_access_level = lookupUserPermission($module);
if (!$permitted_access_level || $permitted_access_level < $check_access_level) {
$_SESSION['alert_type'] = "danger";
$_SESSION['alert_message'] = WORDING_ROLECHECK_FAILED;
$map = [
"1" => "read",
"2" => "write",
"3" => "full"
];
exit(WORDING_ROLECHECK_FAILED . "<br>Tell your admin: $map[$check_access_level] access to $module is not permitted for your role.");
}
}
function enforceClientAccess($client_id = null) {
global $mysqli, $session_user_id, $session_is_admin, $session_name;
// Use global $client_id if none passed
if ($client_id === null) {
global $client_id;
}
if ($session_is_admin) {
return true;
}
$client_id = (int) $client_id;
$session_user_id = (int) $session_user_id;
if (empty($client_id) || empty($session_user_id)) {
flash_alert('Access Denied.', 'error');
redirect('clients.php');
}
// Check if this user has any client permissions set
$permissions_sql = "SELECT client_id
FROM user_client_permissions
WHERE user_id = $session_user_id
LIMIT 1";
$permissions_result = mysqli_query($mysqli, $permissions_sql);
// If no permission rows exist for this user, allow access by default
if ($permissions_result && mysqli_num_rows($permissions_result) == 0) {
return true;
}
// If permission rows exist, require this client
$access_sql = "SELECT client_id
FROM user_client_permissions
WHERE user_id = $session_user_id
AND client_id = $client_id
LIMIT 1";
$access_result = mysqli_query($mysqli, $access_sql);
if ($access_result && mysqli_num_rows($access_result) > 0) {
return true;
}
logAction(
'Client',
'Access',
"$session_name was denied permission from accessing client",
$client_id,
$client_id
);
flash_alert('Access Denied - You do not have permission to access that client!', 'error');
redirect('clients.php');
}

224
functions/db.php Normal file
View File

@@ -0,0 +1,224 @@
<?php
// Prepared-statement DB wrapper layer.
// NOTE: NEW DB LAYER - adoption pending. Not yet called from app code;
// intended target for the gradual prepared-statement migration. Do not remove.
// Split from the former monolithic functions.php
/**
* Simple mysqli helper functions
* - Prepared statements under the hood
* - "Old style" INSERT/UPDATE SET feeling
*/
/**
* Core executor: prepares, binds, executes.
*
* @throws Exception on error
*/
function dbExecute(mysqli $mysqli, string $sql, array $params = []): mysqli_stmt
{
$stmt = $mysqli->prepare($sql);
if (!$stmt) {
throw new Exception('MySQLi prepare error: ' . $mysqli->error . ' | SQL: ' . $sql);
}
if (!empty($params)) {
$types = '';
$values = [];
foreach ($params as $param) {
if (is_int($param)) {
$types .= 'i';
} elseif (is_float($param)) {
$types .= 'd';
} elseif (is_bool($param)) {
$types .= 'i';
$param = $param ? 1 : 0;
} elseif (is_null($param)) {
$types .= 's';
$param = null;
} else {
$types .= 's';
}
$values[] = $param;
}
if (!$stmt->bind_param($types, ...$values)) {
throw new Exception('MySQLi bind_param error: ' . $stmt->error . ' | SQL: ' . $sql);
}
}
if (!$stmt->execute()) {
throw new Exception('MySQLi execute error: ' . $stmt->error . ' | SQL: ' . $sql);
}
return $stmt;
}
/**
* Fetch all rows as associative arrays.
*/
function dbFetchAll(mysqli $mysqli, string $sql, array $params = []): array
{
$stmt = dbExecute($mysqli, $sql, $params);
$result = $stmt->get_result();
if ($result === false) {
return [];
}
return $result->fetch_all(MYSQLI_ASSOC);
}
/**
* Fetch a single row (assoc) or null if none.
*/
function dbFetchOne(mysqli $mysqli, string $sql, array $params = []): ?array
{
$stmt = dbExecute($mysqli, $sql, $params);
$result = $stmt->get_result();
if ($result === false) {
return null;
}
$row = $result->fetch_assoc();
return $row !== null ? $row : null;
}
/**
* Fetch a single scalar value (first column of first row) or null.
*/
function dbFetchValue(mysqli $mysqli, string $sql, array $params = [])
{
$row = dbFetchOne($mysqli, $sql, $params);
if ($row === null) {
return null;
}
return reset($row);
}
/**
* INSERT using "SET" style.
* Example:
* $id = dbInsert($mysqli, 'clients', [
* 'client_name' => $name,
* 'client_type' => $type,
* ]);
*
* @return int insert_id
*
* @throws InvalidArgumentException
* @throws Exception
*/
function dbInsert(mysqli $mysqli, string $table, array $data): int
{
if (empty($data)) {
throw new InvalidArgumentException('dbInsert called with empty $data');
}
$setParts = [];
foreach ($data as $column => $_) {
$setParts[] = "$column = ?";
}
$sql = "INSERT INTO $table SET " . implode(', ', $setParts);
$params = array_values($data);
dbExecute($mysqli, $sql, $params);
return $mysqli->insert_id;
}
function dbUpdate(
mysqli $mysqli,
string $table,
array $data,
$where,
array $whereParams = []
): int {
if (empty($data)) {
throw new InvalidArgumentException('dbUpdate called with empty $data');
}
if (empty($where)) {
throw new InvalidArgumentException('dbUpdate requires a WHERE clause');
}
$setParts = [];
foreach ($data as $column => $_) {
$setParts[] = "$column = ?";
}
if (is_array($where)) {
$whereParts = [];
$whereParams = [];
foreach ($where as $column => $value) {
$whereParts[] = "$column = ?";
$whereParams[] = $value;
}
$whereSql = implode(' AND ', $whereParts);
} else {
$whereSql = $where;
}
$sql = "UPDATE $table SET " . implode(', ', $setParts) . " WHERE $whereSql";
$params = array_merge(array_values($data), $whereParams);
$stmt = dbExecute($mysqli, $sql, $params);
return $stmt->affected_rows;
}
/**
* DELETE helper.
*
* WHERE can be:
* - array: ['client_id' => $id] (auto "client_id = ?")
* - string: 'client_id = ?' (use with $whereParams)
*
* @return int affected_rows
*
* @throws InvalidArgumentException
* @throws Exception
*/
function dbDelete(
mysqli $mysqli,
string $table,
$where,
array $whereParams = []
): int {
if (empty($where)) {
throw new InvalidArgumentException('dbDelete requires a WHERE clause');
}
if (is_array($where)) {
$whereParts = [];
$whereParams = [];
foreach ($where as $column => $value) {
$whereParts[] = "$column = ?";
$whereParams[] = $value;
}
$whereSql = implode(' AND ', $whereParts);
} else {
$whereSql = $where;
}
$sql = "DELETE FROM $table WHERE $whereSql";
$stmt = dbExecute($mysqli, $sql, $whereParams);
return $stmt->affected_rows;
}
/**
* Transaction helpers (optional sugar).
*/
function dbBegin(mysqli $mysqli): void
{
$mysqli->begin_transaction();
}
function dbCommit(mysqli $mysqli): void
{
$mysqli->commit();
}
function dbRollback(mysqli $mysqli): void
{
$mysqli->rollback();
}

228
functions/domain.php Normal file
View File

@@ -0,0 +1,228 @@
<?php
// DNS, SSL and domain expiration lookups (WHOIS/RDAP)
// Split from the former monolithic functions.php
// Get domain general info (whois + NS/A/MX records)
function getDomainRecords($name)
{
$records = array();
// Only run if we think the domain is valid
if (!filter_var($name, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) || !checkdnsrr($name, 'SOA')) {
$records['a'] = '';
$records['ns'] = '';
$records['mx'] = '';
$records['whois'] = '';
return $records;
}
$domain = escapeshellarg(str_replace('www.', '', $name));
// Get A, NS, MX, TXT, and WHOIS records
$records['a'] = trim(strip_tags(shell_exec("dig +short $domain")));
$records['ns'] = trim(strip_tags(shell_exec("dig +short NS $domain")));
$records['mx'] = trim(strip_tags(shell_exec("dig +short MX $domain")));
$records['txt'] = trim(strip_tags(shell_exec("dig +short TXT $domain")));
$records['whois'] = substr(trim(strip_tags(shell_exec("whois -H $domain | head -30 | sed 's/ //g'"))), 0, 254);
// Sort A records (if multiple records exist)
if (!empty($records['a'])) {
$a_records = explode("\n", $records['a']);
array_walk($a_records, function(&$record) {
$record = trim($record);
});
sort($a_records);
$records['a'] = implode("\n", $a_records);
}
// Sort NS records (if multiple records exist)
if (!empty($records['ns'])) {
$ns_records = explode("\n", $records['ns']);
array_walk($ns_records, function(&$record) {
$record = trim($record);
});
sort($ns_records);
$records['ns'] = implode("\n", $ns_records);
}
// Sort MX records (if multiple records exist)
if (!empty($records['mx'])) {
$mx_records = explode("\n", $records['mx']);
array_walk($mx_records, function(&$record) {
$record = trim($record);
});
sort($mx_records);
$records['mx'] = implode("\n", $mx_records);
}
// Sort TXT records (if multiple records exist)
if (!empty($records['txt'])) {
$txt_records = explode("\n", $records['txt']);
array_walk($txt_records, function(&$record) {
$record = trim($record);
});
sort($txt_records);
$records['txt'] = implode("\n", $txt_records);
}
return $records;
}
// Used to automatically attempt to get SSL certificates as part of adding domains
// The logic for the fetch (sync) button on the client_certificates page is in ajax.php, and allows ports other than 443
function getSSL($full_name)
{
// Parse host and port
$name = parse_url("//$full_name", PHP_URL_HOST);
$port = parse_url("//$full_name", PHP_URL_PORT);
// Default port
if (!$port) {
$port = "443";
}
$certificate = array();
$certificate['success'] = false;
// Only run if we think the domain is valid
if (!filter_var($name, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
$certificate['expire'] = '';
$certificate['issued_by'] = '';
$certificate['public_key'] = '';
return $certificate;
}
// Get SSL/TSL certificate (using verify peer false to allow for self-signed certs) for domain on default port
$socket = "ssl://$name:$port";
$get = stream_context_create(array("ssl" => array("capture_peer_cert" => true, "verify_peer" => false,)));
$read = stream_socket_client($socket, $errno, $errstr, 5, STREAM_CLIENT_CONNECT, $get);
// If the socket connected
if ($read) {
$cert = stream_context_get_params($read);
$cert_public_key_obj = openssl_x509_parse($cert['options']['ssl']['peer_certificate']);
openssl_x509_export($cert['options']['ssl']['peer_certificate'], $export);
if ($cert_public_key_obj) {
$certificate['success'] = true;
$certificate['expire'] = date('Y-m-d', $cert_public_key_obj['validTo_time_t']);
$certificate['issued_by'] = strip_tags($cert_public_key_obj['issuer']['O']);
$certificate['public_key'] = $export;
}
}
return $certificate;
}
function getDomainExpirationDate($domain) {
// Execute the whois command
$result = shell_exec("whois " . escapeshellarg($domain));
if (!$result || !checkdnsrr($domain, 'SOA')) {
return null; // Return null if WHOIS query fails
}
$expireDate = '';
// Regular expressions to match different date formats
$patterns = [
'/Expiration Date: (.+)/',
'/Registry Expiry Date: (.+)/',
'/expires: (.+)/',
'/Expiry Date: (.+)/',
'/renewal date: (.+)/',
'/Expires On: (.+)/',
'/paid-till: (.+)/',
'/Expiration Time: (.+)/',
'/\[Expires on\]\s+(.+)/',
'/expire: (.+)/',
'/validity: (.+)/',
'/Expires on.*: (.+)/i',
'/Expiry on.*: (.+)/i',
'/renewal: (.+)/i',
'/Expir\w+ Date: (.+)/i',
'/Valid Until: (.+)/i',
'/Valid until: (.+)/i',
'/expire-date: (.+)/i',
'/Expiration Date: (.+)/i',
'/Registry Expiry Date: (.+)/i',
'/Expire Date: (.+)/i',
'/expiry: (.+)/i',
'/expires: (.+)/i',
'/Registry Expiry Date: (.+)/i',
'/Expiration Time: (.+)/i',
'/validity: (.+)/i',
'/expires: (.+)/i',
'/paid-till: (.+)/i',
'/Expire Date: (.+)/i',
'/Expiration Date: (.+)/i',
'/expire: (.+)/i',
'/expiry: (.+)/i',
'/renewal date: (.+)/i',
'/Expiration Date: (.+)/i',
'/Expiration Time: (.+)/i',
'/Expires: (.+)/i',
];
// Known date formats
$knownFormats = [
"d-M-Y",
"d-F-Y",
"d-m-Y",
"Y-m-d",
"d.m.Y",
"Y.m.d",
"Y/m/d",
"Y/m/d H:i:s",
"Ymd",
"Ymd H:i:s",
"d/m/Y",
"Y. m. d.",
"Y.m.d H:i:s",
"d-M-Y H:i:s",
"D M d H:i:s T Y",
"D M d Y",
"Y-m-d\TH:i:s",
"Y-m-d\TH:i:s\Z",
"Y-m-d H:i:s\Z",
"Y-m-d H:i:s",
"d M Y H:i:s",
"d/m/Y H:i:s",
"d/m/Y H:i:s T",
"B d Y",
"d.m.Y H:i:s",
"before M-Y",
"before Y-m-d",
"before Ymd",
"Y-m-d H:i:s (\T\Z\Z)",
"Y-M-d.",
];
// Check each pattern to find a match
foreach ($patterns as $pattern) {
if (preg_match($pattern, $result, $matches)) {
$expireDate = trim($matches[1]);
break;
}
}
if ($expireDate) {
// Try parsing with known formats
foreach ($knownFormats as $format) {
$parsedDate = DateTime::createFromFormat($format, $expireDate);
if ($parsedDate && $parsedDate->format($format) === $expireDate) {
return $parsedDate->format('Y-m-d');
}
}
// If none of the formats matched, try to parse it directly
$parsedDate = date_create($expireDate);
if ($parsedDate) {
return $parsedDate->format('Y-m-d');
}
}
return null; // Return null if expiration date is not found
}

168
functions/files.php Normal file
View File

@@ -0,0 +1,168 @@
<?php
// Filesystem and embedded-image helpers
// Split from the former monolithic functions.php
function removeDirectory($path) {
if (!file_exists($path)) {
return;
}
$files = glob($path . '/*');
foreach ($files as $file) {
is_dir($file) ? removeDirectory($file) : unlink($file);
}
rmdir($path);
}
function copyDirectory($src, $dst) {
if (!is_dir($src)) {
return;
}
if (!is_dir($dst)) {
mkdir($dst, 0775, true);
}
$items = scandir($src);
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$srcPath = $src . '/' . $item;
$dstPath = $dst . '/' . $item;
if (is_dir($srcPath)) {
copyDirectory($srcPath, $dstPath);
} else {
copy($srcPath, $dstPath);
}
}
}
function mkdirMissing($dir) {
if (!is_dir($dir)) {
mkdir($dir);
}
}
function saveBase64Images(string $html, string $baseFsPath, string $baseWebPath, int $ownerId): string {
// Normalize paths
$baseFsPath = rtrim($baseFsPath, '/\\') . '/';
$baseWebPath = rtrim($baseWebPath, '/\\') . '/';
$targetDir = $baseFsPath . $ownerId . "/";
$folderCreated = false; // <-- NEW FLAG
$savedAny = false; // <-- Track if ANY images processed
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $html);
libxml_clear_errors();
$imgs = $dom->getElementsByTagName('img');
foreach ($imgs as $img) {
$src = $img->getAttribute('src');
// Match base64 images
if (preg_match('/^data:image\/([a-zA-Z0-9+]+);base64,(.*)$/s', $src, $matches)) {
$savedAny = true; // <-- We are actually saving at least 1 image
// Create folder ONLY when needed
if (!$folderCreated) {
if (!is_dir($targetDir)) {
mkdir($targetDir, 0775, true);
}
$folderCreated = true;
}
$mimeType = strtolower($matches[1]);
$base64 = $matches[2];
$binary = base64_decode($base64);
if ($binary === false) {
continue;
}
// Extension mapping
switch ($mimeType) {
case 'jpeg':
case 'jpg': $ext = 'jpg'; break;
case 'png': $ext = 'png'; break;
case 'gif': $ext = 'gif'; break;
case 'webp': $ext = 'webp'; break;
default: $ext = 'png';
}
// Secure random filename
$uid = bin2hex(random_bytes(16));
$filename = "img_{$uid}.{$ext}";
$filePath = $targetDir . $filename;
if (file_put_contents($filePath, $binary) !== false) {
$webPath = "/" . $baseWebPath . $ownerId . "/" . $filename;
$img->setAttribute('src', $webPath);
}
}
}
// If no images were processed, return original HTML immediately
if (!$savedAny) {
return $html;
}
// Extract body content only
$body = $dom->getElementsByTagName('body')->item(0);
if ($body) {
$innerHTML = '';
foreach ($body->childNodes as $child) {
$innerHTML .= $dom->saveHTML($child);
}
return $innerHTML;
}
return $html;
}
function cleanupUnusedImages(string $html, string $folderFsPath, string $folderWebPath) {
$folderFsPath = rtrim($folderFsPath, '/\\') . '/';
$folderWebPath = rtrim($folderWebPath, '/\\') . '/';
if (!is_dir($folderFsPath)) {
return; // no folder = nothing to delete
}
// 1. Get all files currently on disk
$filesOnDisk = glob($folderFsPath . "*");
// 2. Find all <img src="">
preg_match_all('/<img[^>]+src=["\']([^"\']+)["\']/i', $html, $matches);
$htmlImagePaths = $matches[1] ?? [];
// Normalize paths: keep only filenames belonging to this template folder
$referencedFiles = [];
foreach ($htmlImagePaths as $src) {
if (strpos($src, $folderWebPath) !== false) {
$filename = basename($src);
$referencedFiles[] = $filename;
}
}
// 3. Delete any physical file not referenced in the HTML
foreach ($filesOnDisk as $filePath) {
$filename = basename($filePath);
if (!in_array($filename, $referencedFiles)) {
unlink($filePath);
}
}
}

332
functions/format.php Normal file

File diff suppressed because one or more lines are too long

65
functions/logging.php Normal file
View File

@@ -0,0 +1,65 @@
<?php
// Logging, notifications and custom action triggers
// Split from the former monolithic functions.php
function customAction($trigger, $entity) {
$original_dir = getcwd(); // Save
chdir(dirname(__FILE__));
if (file_exists(__DIR__ . "/custom/custom_action_handler.php")) {
include_once __DIR__ . "/custom/custom_action_handler.php";
}
chdir($original_dir); // Restore original working directory
}
function appNotify($type, $details, $action = null, $client_id = 0, $entity_id = 0) {
global $mysqli;
if (is_null($action)) {
$action = "NULL"; // Without quotes for SQL NULL
}
$type = substr($type, 0, 200);
$details = substr($details, 0, 1000);
$action = substr($action, 0, 250);
$sql = mysqli_query($mysqli, "SELECT user_id FROM users
WHERE user_type = 1 AND user_status = 1 AND user_archived_at IS NULL
");
while ($row = mysqli_fetch_assoc($sql)) {
$user_id = intval($row['user_id']);
mysqli_query($mysqli, "INSERT INTO notifications SET notification_type = '$type', notification = '$details', notification_action = '$action', notification_client_id = $client_id, notification_entity_id = $entity_id, notification_user_id = $user_id");
}
}
function logAction($type, $action, $description, $client_id = 0, $entity_id = 0) {
global $mysqli, $session_user_agent, $session_ip, $session_user_id;
$client_id = intval($client_id);
$entity_id = intval($entity_id);
$session_user_id = intval($session_user_id);
if (empty($session_user_id)) {
$session_user_id = 0;
}
$type = substr($type, 0, 200);
$action = substr($action, 0, 255);
$description = substr($description, 0, 1000);
mysqli_query($mysqli, "INSERT INTO logs SET log_type = '$type', log_action = '$action', log_description = '$description', log_ip = '$session_ip', log_user_agent = '$session_user_agent', log_client_id = $client_id, log_user_id = $session_user_id, log_entity_id = $entity_id");
}
function logApp($category, $type, $details) {
global $mysqli;
$category = mysqli_real_escape_string($mysqli, substr($category, 0, 200));
$details = mysqli_real_escape_string($mysqli, substr($details, 0, 1000));
mysqli_query($mysqli, "INSERT INTO app_logs SET app_log_category = '$category', app_log_type = '$type', app_log_details = '$details'");
}

100
functions/request.php Normal file
View File

@@ -0,0 +1,100 @@
<?php
// Request/client detection (IP, UA, browser, OS) and response helpers
// Split from the former monolithic functions.php
function getUserAgent() {
return $_SERVER['HTTP_USER_AGENT'];
}
function getIP() {
// Default way to get IP
$ip = $_SERVER['REMOTE_ADDR'];
// Allow overrides via config.php in-case we use a proxy - https://docs.itflow.org/config_php
if (defined("CONST_GET_IP_METHOD") && CONST_GET_IP_METHOD == "HTTP_X_FORWARDED_FOR") {
$ip = explode(',', getenv('HTTP_X_FORWARDED_FOR'))[0] ?? $_SERVER['REMOTE_ADDR'];
} elseif (defined("CONST_GET_IP_METHOD") && CONST_GET_IP_METHOD == "HTTP_CF_CONNECTING_IP") {
$ip = $_SERVER["HTTP_CF_CONNECTING_IP"] ?? $_SERVER['REMOTE_ADDR'];
}
// Abort if something isn't right
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
error_log("ITFlow - Could not validate remote IP address");
error_log("ITFlow - IP was [$ip] using method " . CONST_GET_IP_METHOD);
exit("Potential Security Violation");
}
return $ip;
}
function getWebBrowser($user_browser) {
$browser = "-";
$browser_array = array(
'/msie/i' => "<i class='fab fa-fw fa-internet-explorer text-secondary'></i> Internet Explorer",
'/firefox/i' => "<i class='fab fa-fw fa-firefox text-secondary'></i> Firefox",
'/safari/i' => "<i class='fab fa-fw fa-safari text-secondary'></i> Safari",
'/chrome/i' => "<i class='fab fa-fw fa-chrome text-secondary'></i> Chrome",
'/edg/i' => "<i class='fab fa-fw fa-edge text-secondary'></i> Edge",
'/opr/i' => "<i class='fab fa-fw fa-opera text-secondary'></i> Opera",
'/ddg/i' => "<i class='fas fa-fw fa-globe text-secondary'></i> DuckDuckGo"
);
foreach ($browser_array as $regex => $value) {
if (preg_match($regex, $user_browser)) {
$browser = $value;
}
}
return $browser;
}
function getOS($user_os) {
$os_platform = "-";
$os_array = array(
'/windows/i' => "<i class='fab fa-fw fa-windows text-secondary'></i> Windows",
'/macintosh|mac os x/i' => "<i class='fab fa-fw fa-apple text-secondary'></i> MacOS",
'/linux/i' => "<i class='fab fa-fw fa-linux text-secondary'></i> Linux",
'/ubuntu/i' => "<i class='fab fa-fw fa-ubuntu text-secondary'></i> Ubuntu",
'/fedora/i' => "<i class='fab fa-fw fa-fedora text-secondary'></i> Fedora",
'/iphone/i' => "<i class='fab fa-fw fa-apple text-secondary'></i> iPhone",
'/ipad/i' => "<i class='fab fa-fw fa-apple text-secondary'></i> iPad",
'/android/i' => "<i class='fab fa-fw fa-android text-secondary'></i> Android"
);
foreach ($os_array as $regex => $value) {
if (preg_match($regex, $user_os)) {
$os_platform = $value;
}
}
return $os_platform;
}
function isMobile()
{
// Check if the user agent is a mobile device
return preg_match('/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|opera mini|palm|phone|pie|tablet|up.browser|up.link|webos|wos)/i', $_SERVER['HTTP_USER_AGENT']);
}
// Redirect Function
function redirect($url = null, $permanent = false) {
// Use referer if no URL is provided
if (!$url) {
$url = $_SERVER['HTTP_REFERER'] ?? 'index.php';
}
if (!headers_sent()) {
header('Location: ' . $url, true, $permanent ? 301 : 302);
exit;
} else {
// Fallback for headers already sent
echo "<script>window.location.href = '" . addslashes($url) . "';</script>";
echo '<noscript><meta http-equiv="refresh" content="0;url=' . htmlspecialchars($url) . '"></noscript>';
exit;
}
}
//Flash Alert Function
function flash_alert(string $message, string $type = 'success'): void {
$_SESSION['alert_type'] = $type;
$_SESSION['alert_message'] = $message;
}

148
functions/sanitize.php Normal file
View File

@@ -0,0 +1,148 @@
<?php
// Input sanitization and upload validation
// Split from the former monolithic functions.php
function nullable_htmlentities($unsanitizedInput) {
//return htmlentities($unsanitizedInput ?? '');
return htmlspecialchars($unsanitizedInput ?? '', ENT_QUOTES, 'UTF-8');
}
function sanitizeInput($input) {
global $mysqli;
if (!empty($input)) {
// Only convert encoding if it's NOT valid UTF-8
if (!mb_check_encoding($input, 'UTF-8')) {
// Try converting from Windows-1252 as a safe default fallback
$input = mb_convert_encoding($input, 'UTF-8', 'Windows-1252');
}
}
// Remove HTML and PHP tags
$input = strip_tags((string) $input);
// Trim white space
$input = trim($input);
// Escape for SQL
$input = mysqli_real_escape_string($mysqli, $input);
return $input;
}
function cleanInput($input) {
// Only process non-empty input
if (!empty($input)) {
// Normalize encoding to UTF-8 if its not valid
if (!mb_check_encoding($input, 'UTF-8')) {
// Convert from Windows-1252 as a safe fallback
$input = mb_convert_encoding($input, 'UTF-8', 'Windows-1252');
}
}
// Remove HTML and PHP tags
$input = strip_tags((string) $input);
// Trim whitespace
$input = trim($input);
return $input;
}
function strtoAZaz09($string)
{
// Gets rid of non-alphanumerics
return preg_replace('/[^A-Za-z0-9_-]/', '', $string);
}
function sanitize_url($url) {
$allowed = ['http', 'https', 'file', 'ftp', 'ftps', 'sftp', 'dav', 'webdav', 'caldav', 'carddav', 'ssh', 'telnet', 'smb', 'rdp', 'vnc', 'rustdesk', 'anydesk', 'connectwise', 'splashtop', 'sip', 'sips', 'ldap', 'ldaps'];
$parts = parse_url($url ?? '');
if (isset($parts['scheme']) && !in_array(strtolower($parts['scheme']), $allowed)) {
// Remove the scheme and colon
$pos = strpos($url, ':');
$without_scheme = $url;
if ($pos !== false) {
$without_scheme = substr($url, $pos + 1); // This keeps slashes (e.g. //pizza.com)
}
// Prepend 'unsupported://' (strip any leading slashes from $without_scheme to avoid triple slashes)
$unsupported = 'unsupported://' . ltrim($without_scheme, '/');
return htmlspecialchars($unsupported, ENT_QUOTES, 'UTF-8');
}
// Safe schemes: return escaped original URL
return htmlspecialchars($url ?? '', ENT_QUOTES, 'UTF-8');
}
// Sanitize File Names
function sanitize_filename($filename, $strict = false) {
// Remove path information and dots around the filename
$filename = basename($filename);
// Replace spaces and underscores with dashes
$filename = str_replace([' ', '_'], '-', $filename);
// Remove anything which isn't a word, number, dot, or dash
$filename = preg_replace('/[^A-Za-z0-9\.\-]/', '', $filename);
// Optionally make filename strict alphanumeric (keep dot and dash)
if ($strict) {
$filename = preg_replace('/[^A-Za-z0-9\.\-]/', '', $filename);
}
// Avoid multiple consecutive dashes
$filename = preg_replace('/-+/', '-', $filename);
// Remove leading/trailing dots and dashes
$filename = trim($filename, '.-');
// Ensure its not empty
if (empty($filename)) {
$filename = 'file';
}
return $filename;
}
// Pass $_FILE['file'] to check an uploaded file before saving it
function checkFileUpload($file, $allowed_extensions)
{
// Variables
$name = $file['name'];
$tmp = $file['tmp_name'];
$size = $file['size'];
$extarr = explode('.', $name);
$extension = strtolower(end($extarr));
// Check a file is actually attached/uploaded
if ($tmp === '') {
// No file uploaded
return false;
}
// Check the extension is allowed
if (!in_array($extension, $allowed_extensions)) {
// Extension not allowed
return false;
}
// Check the size is under 500 MB
$maxSizeBytes = 500 * 1024 * 1024; // 500 MB
if ($size > $maxSizeBytes) {
return "File size exceeds the limit.";
}
// Read the file content
$fileContent = file_get_contents($tmp);
// Hash the file content using SHA-256
$hashedContent = hash('md5', $fileContent);
// Generate a secure filename using the hashed content
$secureFilename = $hashedContent . randomString(2) . '.' . $extension;
return $secureFilename;
}

217
functions/security.php Normal file
View File

@@ -0,0 +1,217 @@
<?php
// Cryptography, key management, credential encryption & token validation
// Split from the former monolithic functions.php
// Function to generate both crypto & URL safe random strings
function randomString(int $length = 16): string {
$bytes = random_bytes((int) ceil($length * 3 / 4));
return substr(
rtrim(strtr(base64_encode($bytes), '+/', '-_'), '='),
0,
$length
);
}
// Older keygen function - only used for TOTP currently
function key32gen() {
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$chars .= "234567";
while (1) {
$key = '';
srand((float) microtime() * 1000000);
for ($i = 0; $i < 32; $i++) {
$key .= substr($chars, (rand() % (strlen($chars))), 1);
}
break;
}
return $key;
}
// Called during initial setup
// Encrypts the master key with the user's password
function setupFirstUserSpecificKey($user_password, $site_encryption_master_key) {
$iv = randomString();
$salt = randomString();
//Generate 128-bit (16 byte/char) kdhash of the users password
$user_password_kdhash = hash_pbkdf2('sha256', $user_password, $salt, 100000, 16);
//Encrypt the master key with the users kdf'd hash and the IV
$ciphertext = openssl_encrypt($site_encryption_master_key, 'aes-128-cbc', $user_password_kdhash, 0, $iv);
return $salt . $iv . $ciphertext;
}
/*
* For additional users / password changes (and now the API)
* New Users: Requires the admin setting up their account have a Specific/Session key configured
* Password Changes: Will use the current info in the session.
*/
function encryptUserSpecificKey($user_password) {
$iv = randomString();
$salt = randomString();
// Get the session info.
$user_encryption_session_ciphertext = $_SESSION['user_encryption_session_ciphertext'];
$user_encryption_session_iv = $_SESSION['user_encryption_session_iv'];
$user_encryption_session_key = $_COOKIE['user_encryption_session_key'];
// Decrypt the session key to get the master key
$site_encryption_master_key = openssl_decrypt($user_encryption_session_ciphertext, 'aes-128-cbc', $user_encryption_session_key, 0, $user_encryption_session_iv);
// Generate 128-bit (16 byte/char) kdhash of the users (new) password
$user_password_kdhash = hash_pbkdf2('sha256', $user_password, $salt, 100000, 16);
// Encrypt the master key with the users kdf'd hash and the IV
$ciphertext = openssl_encrypt($site_encryption_master_key, 'aes-128-cbc', $user_password_kdhash, 0, $iv);
return $salt . $iv . $ciphertext;
}
// Given a ciphertext (incl. IV) and the user's (or API key) password, returns the site master key
// Ran at login, to facilitate generateUserSessionKey
function decryptUserSpecificKey($user_encryption_ciphertext, $user_password)
{
//Get the IV, salt and ciphertext
$salt = substr($user_encryption_ciphertext, 0, 16);
$iv = substr($user_encryption_ciphertext, 16, 16);
$ciphertext = substr($user_encryption_ciphertext, 32);
//Generate 128-bit (16 byte/char) kdhash of the users password
$user_password_kdhash = hash_pbkdf2('sha256', $user_password, $salt, 100000, 16);
//Use this hash to get the original/master key
return openssl_decrypt($ciphertext, 'aes-128-cbc', $user_password_kdhash, 0, $iv);
}
/*
Generates what is probably best described as a session key (ephemeral-ish)
- Allows us to store the master key on the server whilst the user is using the application, without prompting to type their password everytime they want to decrypt a credential
- Ciphertext/IV is stored on the server in the users' session, encryption key is controlled/provided by the user as a cookie
- Only the user can decrypt their session ciphertext to get the master key
- Encryption key never hits the disk in cleartext
*/
function generateUserSessionKey($site_encryption_master_key)
{
$user_encryption_session_key = randomString();
$user_encryption_session_iv = randomString();
$user_encryption_session_ciphertext = openssl_encrypt($site_encryption_master_key, 'aes-128-cbc', $user_encryption_session_key, 0, $user_encryption_session_iv);
// Store ciphertext in the user's session
$_SESSION['user_encryption_session_ciphertext'] = $user_encryption_session_ciphertext;
$_SESSION['user_encryption_session_iv'] = $user_encryption_session_iv;
// Give the user "their" key as a cookie
include 'config.php';
if ($config_https_only) {
setcookie("user_encryption_session_key", "$user_encryption_session_key", ['path' => '/', 'secure' => true, 'httponly' => true, 'samesite' => 'None']);
} else {
setcookie("user_encryption_session_key", $user_encryption_session_key, 0, "/");
$_SESSION['alert_message'] = "Unencrypted connection flag set: Using non-secure cookies.";
}
}
// Decrypts an encrypted password (website/asset credentials), returns it as a string
function decryptCredentialEntry($credential_password_ciphertext)
{
// Split the credential into IV and Ciphertext
$credential_iv = substr($credential_password_ciphertext, 0, 16);
$credential_ciphertext = $salt = substr($credential_password_ciphertext, 16);
// Get the user session info.
$user_encryption_session_ciphertext = $_SESSION['user_encryption_session_ciphertext'];
$user_encryption_session_iv = $_SESSION['user_encryption_session_iv'];
$user_encryption_session_key = $_COOKIE['user_encryption_session_key'];
// Decrypt the session key to get the master key
$site_encryption_master_key = openssl_decrypt($user_encryption_session_ciphertext, 'aes-128-cbc', $user_encryption_session_key, 0, $user_encryption_session_iv);
// Decrypt the credential password using the master key
return openssl_decrypt($credential_ciphertext, 'aes-128-cbc', $site_encryption_master_key, 0, $credential_iv);
}
// Encrypts a website/asset credential password
function encryptCredentialEntry($credential_password_cleartext)
{
$iv = randomString();
// Get the user session info.
$user_encryption_session_ciphertext = $_SESSION['user_encryption_session_ciphertext'];
$user_encryption_session_iv = $_SESSION['user_encryption_session_iv'];
$user_encryption_session_key = $_COOKIE['user_encryption_session_key'];
//Decrypt the session key to get the master key
$site_encryption_master_key = openssl_decrypt($user_encryption_session_ciphertext, 'aes-128-cbc', $user_encryption_session_key, 0, $user_encryption_session_iv);
//Encrypt the website/asset credential using the master key
$ciphertext = openssl_encrypt($credential_password_cleartext, 'aes-128-cbc', $site_encryption_master_key, 0, $iv);
return $iv . $ciphertext;
}
function apiDecryptCredentialEntry($credential_ciphertext, $api_key_decrypt_hash, #[\SensitiveParameter]$api_key_decrypt_password)
{
// Split the Credential entry (username/password) into IV and Ciphertext
$credential_iv = substr($credential_ciphertext, 0, 16);
$credential_ciphertext = $salt = substr($credential_ciphertext, 16);
// Decrypt the api hash to get the master key
$site_encryption_master_key = decryptUserSpecificKey($api_key_decrypt_hash, $api_key_decrypt_password);
// Decrypt the credential password using the master key
return openssl_decrypt($credential_ciphertext, 'aes-128-cbc', $site_encryption_master_key, 0, $credential_iv);
}
function apiEncryptCredentialEntry(#[\SensitiveParameter]$credential_cleartext, $api_key_decrypt_hash, #[\SensitiveParameter]$api_key_decrypt_password)
{
$iv = randomString();
// Decrypt the api hash to get the master key
$site_encryption_master_key = decryptUserSpecificKey($api_key_decrypt_hash, $api_key_decrypt_password);
// Encrypt the credential using the master key
$ciphertext = openssl_encrypt($credential_cleartext, 'aes-128-cbc', $site_encryption_master_key, 0, $iv);
return $iv . $ciphertext;
}
// Cross-Site Request Forgery check for sensitive functions
// Validates the CSRF token provided matches the one in the users session
function validateCSRFToken($token)
{
if (hash_equals($token, $_SESSION['csrf_token'])) {
return true;
} else {
$_SESSION['alert_type'] = "warning";
$_SESSION['alert_message'] = "CSRF token verification failed. Try again, or log out to refresh your token.";
header("Location: index.php");
exit();
}
}
function validateWhitelabelKey($key)
{
$public_key = "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr0k+4ZJudkdGMCFLx5b9
H/sOozvWphFJsjVIF0vPVx9J0bTdml65UdS+32JagIHfPtEUTohaMnI3IAxxCDzl
655qmtjL7RHHdx9UMIKCmtAZOtd2u6rEyZH7vB7cKA49ysKGIaQSGwTQc8DCgsrK
uxRuX04xq9T7T+zuzROw3Y9WjFy9RwrONqLuG8LqO0j7bk5LKYeLAV7u3E/QiqNx
lEljN2UVJ3FZ/LkXeg8ORkV+IHs/toRIfPs/4VQnjEwk5BU6DX2STOvbeZnTqwP3
zgjRYR/zGN5l+az6RB3+0mJRdZdv/y2aRkBlwTxx2gOrPbQAco4a/IOmkE3EbHe7
6wIDAQAP
-----END PUBLIC KEY-----";
if (openssl_public_decrypt(base64_decode($key), $decrypted, $public_key)) {
$key_info = json_decode($decrypted, true);
if ($key_info['expires'] > date('Y-m-d H:i:s', strtotime('-7 day'))) {
return $key_info;
}
}
return false;
}