<?php
class WebSecurityMonitor {
    private $suspiciousPatterns = [
        'SQL injection' => '/(\%27)|(\')|(\-\-)|(%23)|(#)/',
        'XSS' => '/((\%3C)|<)((\%2F)|\/)*[a-z0-9\%]+((\%3E)|>)/',
        'File inclusion' => '/((\.\.\/)|(%2e%2e%2f))/',
        'Command injection' => '/(&)|(\|)|(\;)/'
    ];
    
    private $logFile = 'security.log';
    
    public function monitorRequest() {
        // Monitor GET and POST separately since $_REQUEST might not be available
        $this->checkArray($_GET, 'GET');
        $this->checkArray($_POST, 'POST');
        
        $this->checkServerVariables();
        $this->logAccess();
        
        echo "Security check completed.\n";
    }
    
    private function checkArray($array, $type) {
        foreach ($array as $key => $value) {
            $this->checkInput($key, $value, $type);
        }
    }
    
    private function checkInput($key, $value, $type) {
        if (is_array($value)) {
            foreach ($value as $subKey => $subValue) {
                $this->checkInput($key . '[' . $subKey . ']', $subValue, $type);
            }
            return;
        }
        
        foreach ($this->suspiciousPatterns as $attack => $pattern) {
            if (preg_match($pattern, $value)) {
                $this->logAttack($attack, "$type: $key", $value);
                $this->blockRequest();
            }
        }
    }
    
    private function checkServerVariables() {
        $importantes = ['HTTP_USER_AGENT', 'HTTP_REFERER', 'REQUEST_METHOD'];
        foreach ($importantes as $header) {
            if (isset($_SERVER[$header])) {
                $this->checkInput($header, $_SERVER[$header], 'SERVER');
            }
        }
    }
    
    private function logAttack($type, $input, $value) {
        $log = sprintf(
            "[%s] Attack detected: %s, Input: %s, Value: %s\n",
            date('Y-m-d H:i:s'),
            $type,
            $input,
            $value
        );
        error_log($log);  // Write to error log instead of file
        echo $log;  // Also output to console for testing
    }
    
    private function logAccess() {
        $log = sprintf(
            "[%s] Access logged - IP: %s, Method: %s, URI: %s\n",
            date('Y-m-d H:i:s'),
            $_SERVER['REMOTE_ADDR'] ?? 'unknown',
            $_SERVER['REQUEST_METHOD'] ?? 'unknown',
            $_SERVER['REQUEST_URI'] ?? 'unknown'
        );
        error_log($log);
        echo $log;
    }
    
    private function blockRequest() {
        echo "Access Denied - Suspicious activity detected\n";
        exit();
    }
}

// Test the monitor
$monitor = new WebSecurityMonitor();

// Simulate some requests for testing
$_GET['test1'] = 'normal input';
$_GET['test2'] = "'; DROP TABLE users; --";  // SQL injection attempt
$_POST['test3'] = '<script>alert("xss")</script>';  // XSS attempt

$monitor->monitorRequest();
?>