T.ME/BIBIL_0DAY
CasperSecurity


Server : Apache/2
System : Linux server-15-235-50-60 5.15.0-164-generic #174-Ubuntu SMP Fri Nov 14 20:25:16 UTC 2025 x86_64
User : gositeme ( 1004)
PHP Version : 8.2.29
Disable Function : exec,system,passthru,shell_exec,proc_close,proc_open,dl,popen,show_source,posix_kill,posix_mkfifo,posix_getpwuid,posix_setpgid,posix_setsid,posix_setuid,posix_setgid,posix_seteuid,posix_setegid,posix_uname
Directory :  /home/gositeme/domains/soundstudiopro.com/private_html/includes/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /home/gositeme/domains/soundstudiopro.com/private_html/includes/security_tracking.php
<?php
// Security Tracking Functions - Part 1
require_once __DIR__ . '/../config/database.php';

// Function to get client IP address
function getClientIP() {
    $ipKeys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
    foreach ($ipKeys as $key) {
        if (array_key_exists($key, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$key]) as $ip) {
                $ip = trim($ip);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                    return $ip;
                }
            }
        }
    }
    return $_SERVER['REMOTE_ADDR'] ?? 'unknown';
}

// Function to get device information
function getDeviceInfo() {
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    
    // Detect browser
    $browser = 'Unknown';
    if (preg_match('/Chrome/i', $userAgent)) $browser = 'Chrome';
    elseif (preg_match('/Firefox/i', $userAgent)) $browser = 'Firefox';
    elseif (preg_match('/Safari/i', $userAgent)) $browser = 'Safari';
    elseif (preg_match('/Edge/i', $userAgent)) $browser = 'Edge';
    elseif (preg_match('/Opera/i', $userAgent)) $browser = 'Opera';
    
    // Detect OS
    $os = 'Unknown';
    if (preg_match('/Windows/i', $userAgent)) $os = 'Windows';
    elseif (preg_match('/Mac/i', $userAgent)) $os = 'macOS';
    elseif (preg_match('/Linux/i', $userAgent)) $os = 'Linux';
    elseif (preg_match('/Android/i', $userAgent)) $os = 'Android';
    elseif (preg_match('/iOS/i', $userAgent)) $os = 'iOS';
    
    // Detect device type
    $deviceType = 'Desktop';
    if (preg_match('/Mobile|Android|iPhone|iPad/i', $userAgent)) $deviceType = 'Mobile';
    elseif (preg_match('/Tablet|iPad/i', $userAgent)) $deviceType = 'Tablet';
    
    return [
        'browser' => $browser,
        'os' => $os,
        'device_type' => $deviceType,
        'user_agent' => $userAgent
    ];
}

// Function to get geographic location
// OPTIMIZED: Non-blocking with timeout to prevent homepage slowdown
function getGeoLocation($ip) {
    if ($ip === 'unknown' || $ip === '127.0.0.1' || $ip === '::1') {
        return ['country' => 'Local', 'city' => 'Local', 'timezone' => 'Local'];
    }
    
    try {
        $url = "http://ip-api.com/json/{$ip}?fields=status,message,country,regionName,city,timezone";
        
        // Use cURL with timeout to prevent blocking (max 1 second)
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 1, // 1 second max - don't block page load
            CURLOPT_CONNECTTIMEOUT => 1,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_MAXREDIRS => 2
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        // Only process if we got a response quickly
        if ($response && $httpCode === 200) {
            $data = json_decode($response, true);
            
            if ($data && $data['status'] === 'success') {
                return [
                    'country' => $data['country'] ?? 'Unknown',
                    'city' => $data['city'] ?? 'Unknown',
                    'timezone' => $data['timezone'] ?? 'Unknown'
                ];
            }
        }
    } catch (Exception $e) {
        // Silently fail - don't log to avoid spam, geo location is non-critical
    }
    
    // Return defaults immediately if API is slow/unavailable
    return ['country' => 'Unknown', 'city' => 'Unknown', 'timezone' => 'Unknown'];
}

// Function to log security events
function logSecurityEvent($eventType, $userId = null, $additionalData = []) {
    try {
        $pdo = getDBConnection();
        
        $ip = getClientIP();
        $deviceInfo = getDeviceInfo();
        $geoInfo = getGeoLocation($ip);
        
        $stmt = $pdo->prepare("
            INSERT INTO security_events 
            (event_type, user_id, ip_address, user_agent, request_url, request_method, request_data, response_code, error_message, session_id, country, city, timezone, device_type, browser, os, referrer, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $eventType,
            $userId,
            $ip,
            $deviceInfo['user_agent'],
            $_SERVER['REQUEST_URI'] ?? null,
            $_SERVER['REQUEST_METHOD'] ?? null,
            json_encode($additionalData),
            http_response_code(),
            $additionalData['error_message'] ?? null,
            session_status() === PHP_SESSION_ACTIVE ? session_id() : null,
            $geoInfo['country'],
            $geoInfo['city'],
            $geoInfo['timezone'],
            $deviceInfo['device_type'],
            $deviceInfo['browser'],
            $deviceInfo['os'],
            $_SERVER['HTTP_REFERER'] ?? null
        ]);
        
        return true;
    } catch (Exception $e) {
        error_log("Error logging security event: " . $e->getMessage());
        return false;
    }
}

// Function to log page visits
function logPageVisit($userId = null) {
    try {
        $pdo = getDBConnection();
        if (!$pdo) return false;
        
        // Ensure page_visits table exists
        static $tableChecked = false;
        if (!$tableChecked) {
            try {
                $pdo->exec("
                    CREATE TABLE IF NOT EXISTS page_visits (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        user_id INT NULL,
                        session_id VARCHAR(255),
                        ip_address VARCHAR(45) NOT NULL,
                        page_url VARCHAR(500) NOT NULL,
                        page_title VARCHAR(255),
                        referrer_url VARCHAR(500),
                        user_agent TEXT,
                        country VARCHAR(100),
                        city VARCHAR(100),
                        timezone VARCHAR(100),
                        device_type VARCHAR(50),
                        browser VARCHAR(100),
                        os VARCHAR(100),
                        language VARCHAR(10),
                        visit_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        INDEX idx_user_id (user_id),
                        INDEX idx_visit_time (visit_time),
                        INDEX idx_ip_address (ip_address)
                    )
                ");
                $tableChecked = true;
            } catch (Exception $e) {
                // Table might already exist, that's fine
                $tableChecked = true;
            }
        }
        
        $ip = getClientIP();
        $deviceInfo = getDeviceInfo();
        $geoInfo = getGeoLocation($ip);
        
        $stmt = $pdo->prepare("
            INSERT INTO page_visits 
            (user_id, session_id, ip_address, page_url, page_title, referrer_url, user_agent, country, city, timezone, device_type, browser, os, language, visit_time)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $userId,
            session_status() === PHP_SESSION_ACTIVE ? session_id() : null,
            $ip,
            $_SERVER['REQUEST_URI'] ?? '',
            '',
            $_SERVER['HTTP_REFERER'] ?? null,
            $deviceInfo['user_agent'],
            $geoInfo['country'],
            $geoInfo['city'],
            $geoInfo['timezone'],
            $deviceInfo['device_type'],
            $deviceInfo['browser'],
            $deviceInfo['os'],
            $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? 'en'
        ]);
        
        return true;
    } catch (Exception $e) {
        error_log("Error logging page visit: " . $e->getMessage());
        return false;
    }
}

// Function to log login attempts
function logLoginAttempt($email, $success, $userId = null, $failureReason = null) {
    try {
        $pdo = getDBConnection();
        
        $ip = getClientIP();
        $deviceInfo = getDeviceInfo();
        $geoInfo = getGeoLocation($ip);
        
        $stmt = $pdo->prepare("
            INSERT INTO user_login_history 
            (user_id, email, ip_address, user_agent, success, failure_reason, session_id, country, city, device_info, login_time)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $userId,
            $email,
            $ip,
            $deviceInfo['user_agent'],
            $success,
            $failureReason,
            session_status() === PHP_SESSION_ACTIVE ? session_id() : null,
            $geoInfo['country'],
            $geoInfo['city'],
            json_encode($deviceInfo)
        ]);
        
        // Also log as security event
        $eventType = $success ? 'login_success' : 'login_failed';
        logSecurityEvent($eventType, $userId, [
            'email' => $email,
            'failure_reason' => $failureReason
        ]);
        
        return true;
    } catch (Exception $e) {
        error_log("Error logging login attempt: " . $e->getMessage());
        return false;
    }
}

// Function to log registration attempts
function logRegistrationAttempt($email, $name, $success, $failureReason = null, $validationErrors = []) {
    try {
        $pdo = getDBConnection();
        
        $ip = getClientIP();
        $deviceInfo = getDeviceInfo();
        $geoInfo = getGeoLocation($ip);
        
        $stmt = $pdo->prepare("
            INSERT INTO registration_events 
            (email, name, ip_address, user_agent, success, failure_reason, validation_errors, country, city, device_info, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
        ");
        
        $stmt->execute([
            $email,
            $name,
            $ip,
            $deviceInfo['user_agent'],
            $success,
            $failureReason,
            json_encode($validationErrors),
            $geoInfo['country'],
            $geoInfo['city'],
            json_encode($deviceInfo)
        ]);
        
        // Also log as security event
        $eventType = $success ? 'registration_success' : 'registration_failed';
        logSecurityEvent($eventType, null, [
            'email' => $email,
            'name' => $name,
            'failure_reason' => $failureReason,
            'validation_errors' => $validationErrors
        ]);
        
        return true;
    } catch (Exception $e) {
        error_log("Error logging registration attempt: " . $e->getMessage());
        return false;
    }
}

// Auto-include tracking for all pages (only when not in admin context)
if (!defined('SECURITY_TRACKING_LOADED') && !defined('ADMIN_CONTEXT')) {
    define('SECURITY_TRACKING_LOADED', true);
    
    // Skip tracking for API calls, assets, and AJAX
    $skipPaths = ['/api/', '/assets/', '/uploads/', '/admin'];
    $currentPath = $_SERVER['REQUEST_URI'] ?? '';
    $shouldTrack = true;
    foreach ($skipPaths as $skip) {
        if (strpos($currentPath, $skip) !== false) {
            $shouldTrack = false;
            break;
        }
    }
    
    if ($shouldTrack) {
        // Log page visit for all requests (logged-in and anonymous)
        try {
            // Check if session is active, if not start it for tracking
            if (session_status() === PHP_SESSION_NONE) {
                @session_start();
            }
            
            // Log the page visit
            $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
            $result = logPageVisit($userId);
            
            // Debug: uncomment to verify tracking works
            // error_log("Page visit tracked: " . ($result ? 'SUCCESS' : 'FAILED') . " - User: " . ($userId ?? 'anonymous') . " - Page: " . $currentPath);
            
        } catch (Exception $e) {
            // Silently fail - don't break the page
            error_log("Page visit tracking error: " . $e->getMessage());
        }
    }
}
?> 

CasperSecurity Mini