403Webshell
Server IP : 173.209.174.21  /  Your IP : 216.73.216.89
Web Server : Apache/2.4.58 (Ubuntu)
System : Linux wcfs-server 6.8.0-124-generic #124-Ubuntu SMP PREEMPT_DYNAMIC Tue May 26 13:00:45 UTC 2026 x86_64
User : nodor ( 1000)
PHP Version : 8.3.6
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : OFF  |  Sudo : ON  |  Pkexec : OFF
Directory :  /var/www/thelittlebigshow/self-hosted/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ Back ]     

Current File : /var/www/thelittlebigshow/self-hosted/self_hosted_activation_helpers.php
<?php

require_once __DIR__ . '/self_hosted_config.php';

function selfHostedModeEnabled(): bool
{
    return defined('SELF_HOSTED_MODE') && SELF_HOSTED_MODE === true;
}

function selfHostedCurrentDomain(?string $overrideHost = null): string
{
    $host = trim((string) ($overrideHost ?? ($_SERVER['HTTP_HOST'] ?? '')));
    if ($host === '') {
        $host = php_uname('n');
    }

    $host = strtolower($host);
    $host = preg_replace('/:\d+$/', '', $host);

    return trim((string) $host);
}

function selfHostedCurrentFingerprint(?string $dbName = null): string
{
    $parts = [
        php_uname('n'),
        php_uname('m'),
        php_uname('s'),
        __DIR__,
        (string) ($dbName ?? SELF_HOSTED_DB_NAME),
    ];

    return hash('sha256', implode('|', $parts));
}

function selfHostedLocalConfigPath(): string
{
    return __DIR__ . '/self_hosted_local_config.php';
}

function selfHostedHasLocalConfig(): bool
{
    return is_file(selfHostedLocalConfigPath());
}

function selfHostedInstallerAllowed(): bool
{
    $blockedHosts = defined('SELF_HOSTED_INSTALL_BLOCKED_HOSTS') && is_array(SELF_HOSTED_INSTALL_BLOCKED_HOSTS)
        ? SELF_HOSTED_INSTALL_BLOCKED_HOSTS
        : [];

    return !in_array(selfHostedCurrentDomain(), $blockedHosts, true);
}

function selfHostedWriteLocalConfig(array $config): void
{
    $content = <<<PHP
<?php
define('SELF_HOSTED_MODE', true);
define('SELF_HOSTED_LICENSE_API_URL', %s);
define('SELF_HOSTED_LICENSE_STATE_FILE', __DIR__ . '/self_hosted_license_state.json');
define('SELF_HOSTED_VALIDATE_INTERVAL_SECONDS', %d);
define('SELF_HOSTED_DB_HOST', %s);
define('SELF_HOSTED_DB_NAME', %s);
define('SELF_HOSTED_DB_USER', %s);
define('SELF_HOSTED_DB_PASSWORD', %s);
define('SELF_HOSTED_STORE_NAME', %s);
PHP;

    $rendered = sprintf(
        $content,
        var_export((string) ($config['license_api_url'] ?? SELF_HOSTED_LICENSE_API_URL), true),
        (int) ($config['validate_interval_seconds'] ?? SELF_HOSTED_VALIDATE_INTERVAL_SECONDS),
        var_export((string) ($config['db_host'] ?? ''), true),
        var_export((string) ($config['db_name'] ?? ''), true),
        var_export((string) ($config['db_user'] ?? ''), true),
        var_export((string) ($config['db_password'] ?? ''), true),
        var_export((string) ($config['store_name'] ?? 'HouseTab Pro'), true)
    );

    $written = file_put_contents(selfHostedLocalConfigPath(), $rendered . PHP_EOL);
    if ($written === false) {
        throw new RuntimeException('Could not write the local self-hosted config file.');
    }
}

function selfHostedStateFilePath(): string
{
    return SELF_HOSTED_LICENSE_STATE_FILE;
}

function selfHostedLoadState(): array
{
    $path = selfHostedStateFilePath();
    if (!is_file($path)) {
        return [];
    }

    $json = file_get_contents($path);
    if ($json === false || trim($json) === '') {
        return [];
    }

    $data = json_decode($json, true);

    return is_array($data) ? $data : [];
}

function selfHostedSaveState(array $state): void
{
    $path = selfHostedStateFilePath();
    $directory = dirname($path);

    if (!is_dir($directory)) {
        if (!mkdir($directory, 0775, true) && !is_dir($directory)) {
            throw new RuntimeException('Could not create the local self-hosted state directory.');
        }
    }

    $written = file_put_contents(
        $path,
        json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
    );

    if ($written === false) {
        throw new RuntimeException('Could not write the local self-hosted license state file.');
    }
}

function selfHostedClearState(): void
{
    $path = selfHostedStateFilePath();
    if (is_file($path)) {
        unlink($path);
    }
}

function selfHostedValidationIsFresh(array $state): bool
{
    $lastValidatedAt = trim((string) ($state['last_validated_at'] ?? ''));
    if ($lastValidatedAt === '') {
        return false;
    }

    $validatedTs = strtotime($lastValidatedAt);
    if ($validatedTs === false) {
        return false;
    }

    return (time() - $validatedTs) < (int) SELF_HOSTED_VALIDATE_INTERVAL_SECONDS;
}

function selfHostedValidationErrorAllowsOfflineGrace(string $error): bool
{
    $error = strtolower(trim($error));
    if ($error === '') {
        return false;
    }

    foreach ([
        'could not reach the licensing server',
        'unexpected response from the licensing server',
        'operation timed out',
        'timed out',
        'ssl',
        'name or service not known',
        'couldn\'t connect',
        'failed to open stream',
    ] as $fragment) {
        if (strpos($error, $fragment) !== false) {
            return true;
        }
    }

    return false;
}

function selfHostedApiRequest(string $action, string $licenseKey, ?string $domain = null, ?string $fingerprint = null): array
{
    $payload = http_build_query([
        'action' => $action,
        'license_key' => $licenseKey,
        'domain' => selfHostedCurrentDomain($domain),
        'fingerprint' => $fingerprint ?? selfHostedCurrentFingerprint(),
    ]);

    $url = SELF_HOSTED_LICENSE_API_URL;
    $headers = [
        'Content-Type: application/x-www-form-urlencoded',
        'Content-Length: ' . strlen($payload),
    ];

    $body = false;

    if (function_exists('curl_init')) {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $payload,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_TIMEOUT => 20,
        ]);
        $body = curl_exec($ch);
        $error = curl_error($ch);
        $statusCode = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
        curl_close($ch);

        if ($body === false) {
            return [
                'ok' => false,
                'error' => $error !== '' ? $error : 'Could not reach the licensing server.',
            ];
        }
    } else {
        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => implode("\r\n", $headers),
                'content' => $payload,
                'timeout' => 20,
            ],
        ]);

        $body = @file_get_contents($url, false, $context);
        $statusCode = 200;
        if (isset($http_response_header) && is_array($http_response_header)) {
            foreach ($http_response_header as $line) {
                if (preg_match('/^HTTP\/\S+\s+(\d{3})/', $line, $matches)) {
                    $statusCode = (int) $matches[1];
                    break;
                }
            }
        }

        if ($body === false) {
            return [
                'ok' => false,
                'error' => 'Could not reach the licensing server.',
            ];
        }
    }

    $decoded = json_decode((string) $body, true);
    if (!is_array($decoded)) {
        return [
            'ok' => false,
            'error' => 'Unexpected response from the licensing server.',
        ];
    }

    if ($statusCode >= 400 || empty($decoded['ok'])) {
        return [
            'ok' => false,
            'error' => trim((string) ($decoded['error'] ?? $decoded['message'] ?? 'License request failed.')),
        ];
    }

    return $decoded;
}

function selfHostedActivateLicense(string $licenseKey, ?string $dbName = null, ?string $domain = null): array
{
    $licenseKey = strtoupper(trim($licenseKey));
    if ($licenseKey === '') {
        return ['ok' => false, 'error' => 'Please enter a license key.'];
    }

    $domain = selfHostedCurrentDomain($domain);
    $fingerprint = selfHostedCurrentFingerprint($dbName);
    $result = selfHostedApiRequest('activate', $licenseKey, $domain, $fingerprint);
    if (empty($result['ok'])) {
        return $result;
    }

    $state = [
        'license_key' => $licenseKey,
        'license_status' => (string) ($result['license_status'] ?? 'active'),
        'plan_type' => (string) ($result['plan_type'] ?? 'self_hosted'),
        'remote_setup_included' => !empty($result['remote_setup_included']),
        'domain' => $domain,
        'fingerprint' => $fingerprint,
        'activated_at' => gmdate('c'),
        'last_validated_at' => gmdate('c'),
    ];

    selfHostedSaveState($state);

    return ['ok' => true, 'state' => $state];
}

function selfHostedValidateSavedLicense(bool $force = false): array
{
    $state = selfHostedLoadState();
    $licenseKey = trim((string) ($state['license_key'] ?? ''));
    if ($licenseKey === '') {
        return ['ok' => false, 'error' => 'No license key is stored yet.'];
    }

    $result = selfHostedApiRequest('validate', $licenseKey);
    if (empty($result['ok'])) {
        $state['last_error'] = trim((string) ($result['error'] ?? 'License validation failed.'));
        selfHostedSaveState($state);

        if (!$force && selfHostedValidationIsFresh($state) && selfHostedValidationErrorAllowsOfflineGrace($state['last_error'])) {
            return ['ok' => true, 'state' => $state, 'offline_grace' => true];
        }

        return ['ok' => false, 'error' => $state['last_error'], 'state' => $state];
    }

    $state['license_status'] = (string) ($result['license_status'] ?? ($state['license_status'] ?? 'active'));
    $state['plan_type'] = (string) ($result['plan_type'] ?? ($state['plan_type'] ?? 'self_hosted'));
    $state['remote_setup_included'] = !empty($result['remote_setup_included']);
    $state['domain'] = selfHostedCurrentDomain();
    $state['fingerprint'] = selfHostedCurrentFingerprint();
    $state['last_validated_at'] = gmdate('c');
    unset($state['last_error']);
    selfHostedSaveState($state);

    return ['ok' => true, 'state' => $state];
}

function selfHostedDbConfigured(): bool
{
    return trim((string) SELF_HOSTED_DB_NAME) !== ''
        && trim((string) SELF_HOSTED_DB_USER) !== '';
}

function selfHostedDbConfigurationError(): string
{
    if (selfHostedDbConfigured()) {
        return '';
    }

    return 'Finish the self-hosted installer or set the local database settings before using self-hosted mode.';
}

function selfHostedRequireActivation(): void
{
    if (!selfHostedModeEnabled()) {
        return;
    }

    $currentScript = basename((string) ($_SERVER['SCRIPT_NAME'] ?? ''));
    if (in_array($currentScript, ['self_hosted_setup.php', 'self_hosted_install.php'], true)) {
        return;
    }

    $state = selfHostedLoadState();
    if (empty($state['license_key'])) {
        header('Location: /app/self_hosted_setup.php');
        exit;
    }

    $validation = selfHostedValidateSavedLicense(false);
    if (empty($validation['ok'])) {
        header('Location: /app/self_hosted_setup.php?license_error=1');
        exit;
    }
}

function selfHostedConnectDb(): mysqli
{
    $conn = new mysqli(
        SELF_HOSTED_DB_HOST,
        SELF_HOSTED_DB_USER,
        SELF_HOSTED_DB_PASSWORD,
        SELF_HOSTED_DB_NAME
    );

    if ($conn->connect_error) {
        throw new RuntimeException('Connection failed: ' . $conn->connect_error);
    }

    return $conn;
}

function selfHostedConnectInstallerServer(string $host, string $user, string $password): mysqli
{
    $conn = new mysqli($host, $user, $password);
    if ($conn->connect_error) {
        throw new RuntimeException('Could not connect to the database server: ' . $conn->connect_error);
    }

    return $conn;
}

function selfHostedProvisionDatabase(string $host, string $dbName, string $user, string $password): mysqli
{
    $server = selfHostedConnectInstallerServer($host, $user, $password);
    $safeDbName = '`' . str_replace('`', '``', $dbName) . '`';

    if (!$server->query("CREATE DATABASE IF NOT EXISTS {$safeDbName} CHARACTER SET latin1 COLLATE latin1_swedish_ci")) {
        throw new RuntimeException('Could not create or select the database: ' . $server->error);
    }

    $server->close();

    $conn = new mysqli($host, $user, $password, $dbName);
    if ($conn->connect_error) {
        throw new RuntimeException('Could not connect to the selected database: ' . $conn->connect_error);
    }

    return $conn;
}

function selfHostedInstallSchema(mysqli $conn): void
{
    $queries = [
        "CREATE TABLE IF NOT EXISTS customers (
            id INT(11) NOT NULL AUTO_INCREMENT,
            first_name VARCHAR(100) DEFAULT NULL,
            last_name VARCHAR(100) DEFAULT NULL,
            contact_info TEXT DEFAULT NULL,
            PRIMARY KEY (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci",
        "CREATE TABLE IF NOT EXISTS items (
            id INT(11) NOT NULL AUTO_INCREMENT,
            name VARCHAR(100) NOT NULL,
            price DECIMAL(10,2) NOT NULL,
            PRIMARY KEY (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci",
        "CREATE TABLE IF NOT EXISTS app_settings (
            setting_key VARCHAR(100) NOT NULL PRIMARY KEY,
            setting_value VARCHAR(255) DEFAULT NULL,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci",
        "CREATE TABLE IF NOT EXISTS transactions (
            id INT(11) NOT NULL AUTO_INCREMENT,
            customer_id INT(11) DEFAULT NULL,
            item_name VARCHAR(100) DEFAULT NULL,
            price DECIMAL(10,2) DEFAULT NULL,
            quantity DECIMAL(10,2) DEFAULT NULL,
            taxable TINYINT(1) NOT NULL DEFAULT 0,
            notes TEXT DEFAULT NULL,
            date DATE NOT NULL,
            PRIMARY KEY (id),
            KEY customer_id (customer_id),
            CONSTRAINT transactions_ibfk_1 FOREIGN KEY (customer_id) REFERENCES customers (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci",
        "CREATE TABLE IF NOT EXISTS archived_transactions (
            id INT(11) NOT NULL AUTO_INCREMENT,
            customer_id INT(11) DEFAULT NULL,
            item_name VARCHAR(255) DEFAULT NULL,
            price DECIMAL(10,2) DEFAULT NULL,
            quantity DECIMAL(10,2) DEFAULT NULL,
            taxable TINYINT(1) DEFAULT NULL,
            notes TEXT DEFAULT NULL,
            original_date DATE DEFAULT NULL,
            archived_on DATE DEFAULT NULL,
            PRIMARY KEY (id),
            KEY customer_id (customer_id),
            CONSTRAINT archived_transactions_ibfk_1 FOREIGN KEY (customer_id) REFERENCES customers (id)
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci",
        "INSERT INTO app_settings (setting_key, setting_value)
         VALUES ('sales_tax_rate', '0.0820')
         ON DUPLICATE KEY UPDATE setting_value = setting_value",
    ];

    foreach ($queries as $sql) {
        if (!$conn->query($sql)) {
            throw new RuntimeException('Could not install the self-hosted database schema: ' . $conn->error);
        }
    }
}

function selfHostedAppLoginPath(): string
{
    return '/app/self_hosted_login.php';
}

function selfHostedAllowedAuthScripts(): array
{
    return ['self_hosted_setup.php', 'self_hosted_install.php', 'self_hosted_login.php'];
}

function selfHostedEnsureAppSettingsTable(mysqli $conn): void
{
    $sql = "
        CREATE TABLE IF NOT EXISTS app_settings (
            setting_key VARCHAR(100) NOT NULL PRIMARY KEY,
            setting_value VARCHAR(255) DEFAULT NULL,
            updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_swedish_ci
    ";

    if (!$conn->query($sql)) {
        throw new RuntimeException('Could not prepare self-hosted app settings: ' . $conn->error);
    }
}

function selfHostedGetAppSetting(mysqli $conn, string $key): string
{
    selfHostedEnsureAppSettingsTable($conn);

    $stmt = $conn->prepare("SELECT setting_value FROM app_settings WHERE setting_key = ? LIMIT 1");
    $stmt->bind_param("s", $key);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result ? $result->fetch_assoc() : null;
    $stmt->close();

    return trim((string) ($row['setting_value'] ?? ''));
}

function selfHostedSetAppSetting(mysqli $conn, string $key, string $value): void
{
    selfHostedEnsureAppSettingsTable($conn);

    $stmt = $conn->prepare("
        INSERT INTO app_settings (setting_key, setting_value)
        VALUES (?, ?)
        ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)
    ");
    $stmt->bind_param("ss", $key, $value);
    $stmt->execute();
    $stmt->close();
}

function selfHostedAppCredentialsConfigured(mysqli $conn): bool
{
    return selfHostedGetAppSetting($conn, 'self_hosted_admin_email') !== ''
        && selfHostedGetAppSetting($conn, 'self_hosted_admin_password_hash') !== '';
}

function selfHostedSetAppCredentials(mysqli $conn, string $email, string $password): void
{
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new RuntimeException('Please enter a valid admin email address.');
    }

    if (strlen($password) < 8) {
        throw new RuntimeException('Password must be at least 8 characters.');
    }

    selfHostedSetAppSetting($conn, 'self_hosted_admin_email', trim($email));
    selfHostedSetAppSetting($conn, 'self_hosted_admin_password_hash', password_hash($password, PASSWORD_DEFAULT));
}

function selfHostedAuthenticateAppUser(mysqli $conn, string $email, string $password): bool
{
    $storedEmail = selfHostedGetAppSetting($conn, 'self_hosted_admin_email');
    $storedHash = selfHostedGetAppSetting($conn, 'self_hosted_admin_password_hash');

    if ($storedEmail === '' || $storedHash === '') {
        return false;
    }

    return hash_equals(strtolower($storedEmail), strtolower(trim($email)))
        && password_verify($password, $storedHash);
}

function selfHostedRequireAppLogin(): void
{
    if (!selfHostedModeEnabled()) {
        return;
    }

    $currentScript = basename((string) ($_SERVER['SCRIPT_NAME'] ?? ''));
    if (in_array($currentScript, selfHostedAllowedAuthScripts(), true)) {
        return;
    }

    if (!selfHostedDbConfigured()) {
        header('Location: ' . selfHostedAppLoginPath() . '?setup_required=1');
        exit;
    }

    $conn = selfHostedConnectDb();

    if (!selfHostedAppCredentialsConfigured($conn)) {
        $conn->close();
        header('Location: ' . selfHostedAppLoginPath() . '?setup_required=1');
        exit;
    }

    $lastActivity = (int) ($_SESSION['self_hosted_app_last_activity_at'] ?? 0);
    $now = time();
    if ($lastActivity > 0 && ($now - $lastActivity) > (int) SELF_HOSTED_APP_SESSION_TIMEOUT_SECONDS) {
        unset($_SESSION['self_hosted_app_logged_in'], $_SESSION['self_hosted_app_email'], $_SESSION['self_hosted_app_last_activity_at']);
        $conn->close();
        header('Location: ' . selfHostedAppLoginPath() . '?session_expired=1');
        exit;
    }

    if (empty($_SESSION['self_hosted_app_logged_in'])) {
        $conn->close();
        header('Location: ' . selfHostedAppLoginPath());
        exit;
    }

    $_SESSION['self_hosted_app_last_activity_at'] = $now;
    $conn->close();
}

Youez - 2016 - github.com/yon3zu
LinuXploit